code
stringlengths
2
1.05M
'use strict'; module.exports.install = function(admin){ admin.menu.addBefore('account', { id:'users', name:'User Management', icon:'fa fa-users', href:'#/users', allowRoles:['admin'] }); // admin angular module dependencies admin.modules.push('neAdmin.users'); // admin routes admin.routes[ '/users' ] = { templateUrl: admin.basePath + 'views/users.html', controller:'UsersCtrl', reloadOnSearch:false }; // include styles // admin.styles.push('css/mystyle.css'); // 3rd-party tools & libs, such as ase editor, or jquery, ... // admin.libs.push('js/somelibrary.js'); // admin scripts, will be loaded // admin.scripts.push('controllers/users-ctrl.js'); framework.rest(admin.basePath + 'users', 'User', [ { route:'/', collection:'all', flags:[ 'get' ], count:true }, { route:'/exists', collection:'exists', flags:['get'] }, { route:'/{id}', collection:'one', flags:[ 'get' ] }, { route:'/', instance:'create', afterValidation:hashPass, flags:[ 'post', 'json' ] }, { route:'/{id}', instance:'create', flags:[ 'post', 'json' ] }, { route:'/{id}', instance:'update', afterValidation:disableSelfDisable, flags:[ 'put', 'json' ] }, { route:'/{id}', instance:'remove', afterValidation:disableSelfRemove, flags:[ 'delete' ] }, { route:'/{id}/resetpass', instance:'resetPass', flags:[ 'post', 'json' ] }, ], ['authorize','!admin']); function hashPass(ctx, next){ ctx.model.hashPass(); next(); } function disableSelfRemove(ctx, next){ if(ctx.params.id === this.user.id){ this.status = 400; this.json({ data:{ id:['selfRemove'] } }); } else next(); } function disableSelfDisable(ctx, next){ if(ctx.body.disabled && ctx.params.id === this.user.id){ this.status = 400; this.json({ data:{ id:['selfDisable'] } }); } else next(); } };
/* * GET users listing. */ exports.index = function(req, res){ res.render('user/index', { title: '/ My Apps'}); };
(function (angular) { "use strict"; angular.module("mfl.reports.controllers", [ "mfl.reports.controllers.base", "mfl.reports.controllers.facilities", "mfl.reports.controllers.facility_reporting", "mfl.reports.controllers.chu_reporting", "mfl.reports.updowngrades.controllers", "ui.bootstrap.buttons" ]); })(window.angular);
git://github.com/viljamis/ResponsiveSlides.js.git
/** * Imports */ import test from 'tape' import PixelGradient from '.' /** * <Pixel Gradient/> tests */ test('<PixelGradient/> should work', t => { })
var WorkerInstance = require("../lib/workers/WorkerInstance.js").WorkerInstance, EventEmitter = require("events").EventEmitter; exports.WorkerPrototypeTests = { setUp: function(done) { done(); }, "Worker has a EventEmitter in prototype chain": function(test) { test.expect(1); var worker = new WorkerInstance(function() {}); test.equal(worker instanceof EventEmitter, true, "should inherits from EventEmitter"); test.done(); }, "Worker should have events on start and finish" : function(test) { test.expect(2); var started = false, finished = false, worker = new WorkerInstance(function() {}); worker.once("task-started", function() { started = true ; }); worker.once("task-finished", function() { finished = true ; }); worker.spawn(); test.equal(started, true, "task-started event should be invoked"); test.equal(finished, true, "task-finished event should be invoked"); test.done(); }, "Worker should return last transaction ID from task-finished" : function(test) { test.expect(1); var lastTransactionId = -1, worker = new WorkerInstance(function() { return 667; }); worker.once("task-finished", function(result) { lastTransactionId = result; }); worker.spawn(); test.equal(lastTransactionId, 667, "task-finished event should return last transaction Id"); test.done(); }, "Worker should invoke die event always - successful case" : function(test) { test.expect(1); var die = false, worker = new WorkerInstance(function() { return 667; }); worker.once("die", function() { die = true; }); worker.spawn(); test.equal(die, true, "die event should occure after successful execution"); test.done(); }, "Worker should invoke die event always - invalid case" : function(test) { test.expect(2); var error = null, die = false, worker = new WorkerInstance(function() { throw "Error"; }); worker.once("die", function(err) { die = true; error = err; }); worker.spawn(); test.equal(die, true, "die event should occure after invalid execution"); test.equal(error, "Error", "die event should return exception object"); test.done(); } };
/* * bootstrap-table - v1.11.1 - 2017-08-03 * https://github.com/wenzhixin/bootstrap-table * Copyright (c) 2017 zhixin wen * Licensed MIT License */ !function(a){"use strict";a.fn.bootstrapTable.locales["th-TH"]={formatLoadingMessage:function(){return"เธเธณเธฅเธฑเธ‡เน‚เธซเธฅเธ”เธ‚เน‰เธญเธกเธนเธฅ, เธเธฃเธธเธ“เธฒเธฃเธญเธชเธฑเธเธ„เธฃเธนเนˆ..."},formatRecordsPerPage:function(a){return a+" เธฃเธฒเธขเธเธฒเธฃเธ•เนˆเธญเธซเธ™เน‰เธฒ"},formatShowingRows:function(a,b,c){return"เธฃเธฒเธขเธเธฒเธฃเธ—เธตเนˆ "+a+" เธ–เธถเธ‡ "+b+" เธˆเธฒเธเธ—เธฑเน‰เธ‡เธซเธกเธ” "+c+" เธฃเธฒเธขเธเธฒเธฃ"},formatSearch:function(){return"เธ„เน‰เธ™เธซเธฒ"},formatNoMatches:function(){return"เน„เธกเนˆเธžเธšเธฃเธฒเธขเธเธฒเธฃเธ—เธตเนˆเธ„เน‰เธ™เธซเธฒ !"},formatRefresh:function(){return"เธฃเธตเน€เธŸเธฃเธช"},formatToggle:function(){return"เธชเธฅเธฑเธšเธกเธธเธกเธกเธญเธ‡"},formatColumns:function(){return"เธ„เธญเธฅเธฑเธกเธ™เนŒ"}},a.extend(a.fn.bootstrapTable.defaults,a.fn.bootstrapTable.locales["th-TH"])}(jQuery);
(function() { var slice = [].slice, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; this.Slider = (function() { var Component, Debug, Fill, Knob, Label, Track, Vector, _, ref; _ = Slider._ = { extend: function() { var args, first, i, j, k, len, o, ref, v; args = 1 <= arguments.length ? slice.call(arguments, 0) : []; if (!args.length) { return; } if (args.length === 1) { return args[0]; } first = (ref = args.splice(0, 1)) != null ? ref[0] : void 0; for (i = j = 0, len = args.length; j < len; i = ++j) { o = args[i]; for (k in o) { v = o[k]; first[k] = v; } } return first; }, map: function(o, f) { var j, k, len, results, results1, v; if (_.isArray(o)) { results = []; for (k = j = 0, len = o.length; j < len; k = ++j) { v = o[k]; results.push(typeof f === "function" ? f(v, k) : void 0); } return results; } else { results1 = []; for (k in o) { v = o[k]; results1.push(typeof f === "function" ? f(v, k) : void 0); } return results1; } }, find: function(o, f) { var j, k, len, v; if (_.isArray(o)) { for (k = j = 0, len = o.length; j < len; k = ++j) { v = o[k]; if (typeof f === "function" ? f(v, k) : void 0) { return v; } } } else { for (k in o) { v = o[k]; if (typeof f === "function" ? f(v, k) : void 0) { return v; } } } }, isObject: function(o) { return "[object Object]" === Object.prototype.toString.call(o); }, isArray: function(o) { return "[object Array]" === Object.prototype.toString.call(o); }, isMobile: 'ontouchstart' in window, delay: function(d, f) { return setTimeout(f, d); }, throttle: function(d, fun, ctx) { var tmout; tmout = null; return function() { var args, k; if (tmout) { clearTimeout(tmout); } args = (function() { var j, len, results; results = []; for (j = 0, len = arguments.length; j < len; j++) { k = arguments[j]; results.push(k); } return results; }).apply(this, arguments); return tmout = setTimeout(function() { return fun != null ? typeof fun.apply === "function" ? fun.apply(ctx != null ? ctx : this, args) : void 0 : void 0; }, d); }; }, addClass: function(e, c) { var ref; return e != null ? (ref = e.classList) != null ? ref.add(c) : void 0 : void 0; }, removeClass: function(e, c) { var ref; return e != null ? (ref = e.classList) != null ? ref.remove(c) : void 0 : void 0; }, toggleClass: function(e, c, t) { var name1, ref; return e != null ? (ref = e.classList) != null ? typeof ref[name1 = t ? 'add' : 'remove'] === "function" ? ref[name1](c) : void 0 : void 0 : void 0; }, offset: function(e) { var offset, parent; if (!(e instanceof Element)) { return; } offset = { x: e.offsetLeft, y: e.offsetTop }; parent = e.offsetParent; while (parent != null) { offset.x += parent.offsetLeft; offset.y += parent.offsetTop; parent = parent.offsetParent; } return offset; }, transform: function(el, x, y) { var ref, style; style = el != null ? el.style : void 0; if (x instanceof Vector) { ref = x, x = ref.x, y = ref.y; } return style.transform = style.WebkitTransform = style.msTransform = "translate3d(" + (x.toFixed(3)) + "px, " + (y.toFixed(3)) + "px, 0)"; }, clamp: function(v, min, max) { if ((min != null) && v < min) { v = min; } if ((max != null) && v > max) { v = max; } return v; }, roundTo: function(n, d) { return d * Math.round(n / d); }, sign: function(n) { if (typeof n !== 'number' || isNaN(n) || !isFinite(n)) { return 0; } if (n >= 0) { return 1; } else { return -1; } }, fixFPError: function(n) { var p, r, str; str = String(n); if (/\..*00000\d$/i.test(str)) { return Number(str.substring(0, str.length - 1)); } else if (/\..*99999\d$/i.test(str)) { r = Number(str[str.length - 1]); p = str.indexOf('.'); p = p - str.length + 1; return n + (_.sign(n)) * (10 - r) * Math.pow(10, p); } else { return n; } }, formatObject: function(v, indent) { if (indent == null) { indent = 0; } return _.map(v, function(val, key) { var t; if (typeof val === 'string') { val = "\"" + val + "\""; } if ('[object Object]' === Object.prototype.toString.call(val)) { val = "\n" + _.formatObject(val, indent + 1); } return "" + (indent ? ((function() { var j, ref, results; results = []; for (t = j = 0, ref = indent; 0 <= ref ? j <= ref : j >= ref; t = 0 <= ref ? ++j : --j) { results.push(' '); } return results; })()).join('') : '') + key + ": " + val; }).join('\n'); }, formatNumber: function(n, options) { var defaults, macro, micro, order, unit; defaults = { inf: "&#8734;", nan: "?", decimalPlaces: 2, separator: '' }; options = _.extend({}, defaults, options != null ? options : {}); if (typeof n !== 'number') { return n; } if (isNaN(n)) { return "?"; } if (!isFinite(n)) { return "&#8734;"; } order = n !== 0 ? Math.floor(Math.log10(Math.abs(n))) : 0; unit = function(order, suffix) { return function(x) { var number; number = _.sign(x) * Math.round(Math.abs(x) / Math.pow(10, order - options.decimalPlaces)) / Math.pow(10, options.decimalPlaces); return number + options.separator + suffix; }; }; macro = [unit(0, ''), unit(3, 'k'), unit(6, 'M'), unit(9, 'G'), unit(12, 'T'), unit(15, 'P'), unit(18, 'E'), unit(21, 'Z'), unit(24, 'Y')]; micro = [unit(0, ''), unit(-3, 'm'), unit(-6, 'ฮผ'), unit(-9, 'n'), unit(-12, 'p'), unit(-15, 'f'), unit(-18, 'a'), unit(-21, 'z'), unit(-24, 'y')]; order = _.sign(order) * Math.floor(Math.abs(order) / 3); if (order >= 0) { order = _.clamp(order, 0, macro.length - 1); return "" + macro[order](n); } else { order = _.clamp(order, -micro.length + 1, 0); return "" + micro[-order](n); } }, log: function(e) { console.log(e); return e; }, tag: function(name) { return function() { var a, arg, args, attr, content, el, j, key, last, len, ref, val; args = 1 <= arguments.length ? slice.call(arguments, 0) : []; attr = {}; last = args[args.length - 1]; if (last instanceof Element || _.isArray(last)) { content = (ref = args.splice(args.length - 1, 1)) != null ? ref[0] : void 0; } for (j = 0, len = args.length; j < len; j++) { arg = args[j]; for (key in arg) { val = arg[key]; attr[key] = val; } } el = document.createElement(name); for (a in attr) { val = attr[a]; el.setAttribute(a, val); } if (!_.isArray(content)) { content = [content]; } content.map(function(c) { if (c instanceof Element) { return el.appendChild(c); } }); return el; }; }, event: function(name, data) { var evt; evt = document.createEvent('Event'); evt.initEvent(name, true, true); return _.extend(evt, data != null ? data : {}); }, listenOnce: function(element, name, listener) { var harness; harness = function(e) { element.removeEventListener(name, harness); return typeof listener === "function" ? listener(e) : void 0; }; return element.addEventListener(name, harness); } }; _.div = _.tag('div'); _.pre = _.tag('pre'); ref = _.isMobile ? ['touchstart', 'touchmove', 'touchend'] : ['mousedown', 'mousemove', 'mouseup'], _.startEvent = ref[0], _.moveEvent = ref[1], _.endEvent = ref[2]; Vector = Slider.Vector = (function() { function Vector(x, y) { var touches; if (x instanceof Event) { if (_.isMobile) { touches = x.type === 'touchend' ? x.changedTouches : x.touches; } this.x = _.isMobile ? touches[0].pageX : x.pageX; this.y = _.isMobile ? touches[0].pageY : x.pageY; } else { this.set({ x: x, y: y }); } } Vector.prototype.set = function(v) { if ((v != null ? v.x : void 0) != null) { this.x = v.x; } if ((v != null ? v.y : void 0) != null) { return this.y = v.y; } }; Vector.prototype.clone = function() { return new Vector(this.x, this.y); }; Vector.prototype.subtract = function(v) { var ref1, ref2; return new Vector((ref1 = this.x - (v != null ? v.x : void 0)) != null ? ref1 : 0, (ref2 = this.y - (v != null ? v.y : void 0)) != null ? ref2 : 0); }; Vector.prototype.add = function(v) { var ref1, ref2; return new Vector((ref1 = this.x + (v != null ? v.x : void 0)) != null ? ref1 : 0, (ref2 = this.y + (v != null ? v.y : void 0)) != null ? ref2 : 0); }; Vector.prototype.magnitude = function() { return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2)); }; Vector.prototype.clamp = function(r) { var ref1, ref2, ref3, ref4; this.x = _.clamp(this.x, r != null ? (ref1 = r.x) != null ? ref1[0] : void 0 : void 0, r != null ? (ref2 = r.x) != null ? ref2[1] : void 0 : void 0); return this.y = _.clamp(this.y, r != null ? (ref3 = r.y) != null ? ref3[0] : void 0 : void 0, r != null ? (ref4 = r.y) != null ? ref4[1] : void 0 : void 0); }; return Vector; })(); Slider.errors = { selectorEmpty: 'slider element selector must return at least one element', elementInvalid: 'first argument must be a selector or an element', valueInvalid: 'slider value must be between options.min and options.max', positionInvalid: 'slider position must be between 0 and 1' }; Slider.polling = { timeout: null, interval: 1931, start: function() { if (this.timeout == null) { return this.timeout = setInterval(function() { return Slider.instances.map(function(slider) { if (slider.options.poll && !slider.transitioning && !slider.dragging) { return slider.position(slider.position()); } }); }, this.interval); } }, stop: function() { if (this.timeout != null) { return clearInterval(this.timeout); } } }; Slider.defaults = { min: 0, max: 1, value: 0, step: 0.1, warnings: true, orientation: 'horizontal', transitionDuration: 350, poll: false, formElement: null }; Slider.instances = []; Slider.getInstance = function(element) { if (!(element instanceof Element)) { return null; } return _.find(Slider.instances, function(i) { return i.element === element; }); }; Slider.prototype.warn = function() { var ref1; if (this.options.warnings) { return typeof console !== "undefined" && console !== null ? (ref1 = console.warn) != null ? ref1.apply(console, arguments) : void 0 : void 0; } }; function Slider(element, options) { var component, ctor, generator, ref1, ref2; this.options = _.extend({}, Slider.defaults, options != null ? options : {}); if (typeof element === 'string') { this.element = document.querySelector(element); if (!this.element) { throw Slider.errors.selectorEmpty; } } else if (element instanceof Element) { this.element = element; } else { throw Slider.errors.elementInvalid; } if ((ref1 = Slider.instances) != null) { if (typeof ref1.push === "function") { ref1.push(this); } } this.onFormElementChange = (function(_this) { return function(e) { var ok, ref2, ref3, ref4, val; val = e != null ? (ref2 = e.target) != null ? ref2.value : void 0 : void 0; if (val != null) { val = Number(val); if (isFinite(val) && !isNaN(val)) { ok = _this.value(val, { updateFormElement: false }); if (ok == null) { return e != null ? (ref3 = e.target) != null ? ref3.value = _this.value() : void 0 : void 0; } } else { _this.warn(Slider.errors.valueInvalid + " : " + val); return e != null ? (ref4 = e.target) != null ? ref4.value = _this.value() : void 0 : void 0; } } }; })(this); if (this.options.formElement) { this.bindFormElement(this.options.formElement); } _.addClass(this.element, 'slider'); _.addClass(this.element, this.options.orientation); ref2 = Slider.components; for (component in ref2) { generator = ref2[component]; if (ctor = generator(this.options)) { this[component] = new ctor(this, this.options[component]); } } this.value(this.options.value, { changeEvent: false, transitionEvent: false }); if (this.options.poll) { Slider.polling.start(); } window.addEventListener('resize', _.throttle(600, (function(_this) { return function() { return _this.refresh(); }; })(this))); } Slider.prototype.refresh = function(o) { var refresh; refresh = (function(_this) { return function() { return _this.position(_this.position(), _.extend({ changeEvent: false, transitionEvent: false }, o)); }; })(this); if (this.transitioning) { return _.listenOnce(this.element, 'transition', refresh); } else { return refresh(); } }; Slider.prototype.bindFormElement = function(element, options) { var defaults; defaults = { unbindOldElement: true }; options = _.extend({}, defaults, options); if (typeof element === 'string') { element = document.querySelector(element); if (!element) { throw Slider.errors.selectorEmpty; } } else if (!(element instanceof Element)) { throw Slider.errors.elementInvalid; } if (options.unbindOldElement && this.formElement && this.onFormElementChange) { this.formElement.removeEventListener('change', this.onFormElementChange); } element.addEventListener('change', this.onFormElementChange); return this.formElement = element; }; Slider.prototype.value = function(v, options) { if (options == null) { options = {}; } return this.position(v, _.extend(options, { normalized: false })); }; Slider.prototype.position = function(p, options) { var comp, ctr, defaults, pos, ref1, ref2, ref3, step, val; if (_.isObject(p)) { options = p; p = void 0; } defaults = { normalized: true, transition: this.options.transitionDuration, changeEvent: true, transitionEvent: true, step: (options != null ? options.normalized : void 0) === false ? this.options.step : this.options.step / (this.options.max - this.options.min), updateFormElement: true }; options = _.extend({}, defaults, options); pos = p === void 0 ? this.normalizedPosition : options.normalized ? p : (p - this.options.min) / (this.options.max - this.options.min); if (options.step) { step = !options.normalized ? options.step / (this.options.max - this.options.min) : options.step; } else { step = 1 / this.knob.range(); } pos = _.fixFPError(_.roundTo(pos, step)); val = options.normalized ? function(x) { return x; } : (function(_this) { return function(x) { return _this.options.min + x * (_this.options.max - _this.options.min); }; })(this); if (p === void 0) { return _.fixFPError(val(pos)); } if (!((val(0) <= p && p <= val(1)))) { this.warn(options.normalized ? Slider.errors.positionInvalid + " : " + p : Slider.errors.valueInvalid + " : " + p); return; } this.normalizedPosition = pos; if (options.transition) { _.addClass(this.element, 'transition'); this.transitioning = true; } ref1 = Slider.components; for (comp in ref1) { ctr = ref1[comp]; if ((ref2 = this[comp]) != null) { if (typeof ref2.position === "function") { ref2.position(this.normalizedPosition, options); } } } if (options.updateFormElement) { if ((ref3 = this.formElement) != null) { ref3.value = this.value(); } } if (options.changeEvent) { this.element.dispatchEvent(_.event('change', { value: this.value() })); } if (options.transition) { _.delay(options.transition, (function(_this) { return function() { return _.delay(17, function() { _.removeClass(_this.element, 'transition'); _this.transitioning = false; if (options.transitionEvent) { return _this.element.dispatchEvent(_.event('transition', { value: _this.value() })); } }); }; })(this)); } return pos; }; Component = Slider.Component = (function() { function Component() {} return Component; })(); Track = Slider.Track = (function(superClass) { extend(Track, superClass); Track.defaults = { dragEvents: true }; Track.prototype.size = function() { switch (this.slider.options.orientation) { case 'horizontal': return this.element.offsetWidth; case 'vertical': return this.element.offsetHeight; } }; function Track(slider1, options) { var knobStartOffset, pixelPos, ref1, start, toggleClass; this.slider = slider1; this.options = _.extend({}, (ref1 = Track.defaults) != null ? ref1 : {}, options != null ? options : {}); this.slider.element.appendChild(this.element = _.div({ "class": 'track' })); start = null; knobStartOffset = null; pixelPos = (function(_this) { return function(pxOffset, options) { var p; p = (function() { switch (this.slider.options.orientation) { case 'horizontal': return pxOffset.x; case 'vertical': return pxOffset.y; } }).call(_this); p = _.clamp((p - _this.slider.knob.size() / 2) / _this.slider.knob.range(), 0, 1); return _this.slider.position(p, options); }; })(this); toggleClass = _.throttle(100, (function(_this) { return function(cls, condition) { if (condition == null) { condition = true; } return _.toggleClass(_this.slider.element, cls, condition); }; })(this)); this.element.addEventListener(_.startEvent, (function(_this) { return function(e) { var trackOffset; start = new Vector(e); trackOffset = _.offset(_this.element); pixelPos(start.subtract(trackOffset), { transition: false, step: false, changeEvent: false }); knobStartOffset = _this.slider.knob.offset.clone(); _.removeClass(_this.slider.element, 'transition'); toggleClass('dragging', true); return _this.slider.dragging = true; }; })(this)); window.addEventListener(_.endEvent, (function(_this) { return function(e) { if (start != null) { toggleClass('dragging', false); _this.slider.dragging = false; _this.slider.refresh({ changeEvent: true, transitionEvent: true }); return start = null; } }; })(this)); window.addEventListener(_.moveEvent, (function(_this) { return function(e) { var orientOffset; if (start) { orientOffset = (function() { switch (this.slider.options.orientation) { case 'horizontal': return { x: this.slider.knob.size() / 2 }; case 'vertical': return { y: this.slider.knob.size() / 2 }; } }).call(_this); pixelPos(knobStartOffset.add(new Vector(e).subtract(start)).add(orientOffset), { transition: false, step: false, changeEvent: false }); if (_this.options.dragEvents) { return _this.slider.element.dispatchEvent(_.event('drag', { position: _this.slider.position(), value: _this.slider.value() })); } } }; })(this)); } return Track; })(Component); Knob = Slider.Knob = (function(superClass) { extend(Knob, superClass); Knob.defaults = { dragEvents: true }; Knob.prototype.size = function() { switch (this.slider.options.orientation) { case 'horizontal': return this.element.offsetWidth + 2 * this.element.offsetLeft; case 'vertical': return this.element.offsetHeight + 2 * this.element.offsetTop; } }; Knob.prototype.range = function() { return this.slider.track.size() - this.size(); }; Knob.prototype.position = function(p, options) { this.offset.set((function() { switch (this.slider.options.orientation) { case 'horizontal': return { x: this.range() * p, y: 0 }; case 'vertical': return { x: 0, y: this.range() * p }; } }).call(this)); return _.transform(this.element, this.offset); }; function Knob(slider1, options) { var ref1; this.slider = slider1; this.options = _.extend({}, (ref1 = Knob.defaults) != null ? ref1 : {}, options != null ? options : {}); this.slider.element.appendChild(this.element = _.div({ "class": 'knob' })); this.offset = new Vector(0, 0); this; } return Knob; })(Component); Label = Slider.Label = (function(superClass) { extend(Label, superClass); Label.defaults = { location: 'knob', precision: 1, popup: true, format: function(v, options) { return _.formatNumber(v, { decimalPlaces: options.precision }); } }; Label.prototype.position = function(p, o) { var base, formatted; Label.__super__.position.call(this, p, o); formatted = typeof (base = this.options).format === "function" ? base.format(this.slider.value(), this.options) : void 0; return this.value.innerText = this.hiddenValue.innerText = this.hiddenKnobValue.innerText = formatted; }; function Label(slider1, options) { this.slider = slider1; Label.__super__.constructor.call(this, this.slider, _.extend({}, Label.defaults, options != null ? options : {})); _.addClass(this.element, 'label'); if (this.options.popup) { _.addClass(this.element, 'popup'); } this.element.appendChild(this.popup = _.div({ "class": 'popup' }, [ this.value = _.div({ "class": 'value' }), _.div({ "class": 'arrow' }) ])); this.element.appendChild(this.hiddenValue = _.div({ "class": 'hidden value' })); if (this.options.location === 'knob') { this.slider.knob.element.appendChild(this.hiddenKnobValue = _.div({ "class": 'hidden value' })); } } return Label; })(Knob); Fill = Slider.Fill = (function(superClass) { extend(Fill, superClass); Fill.defaults = null; Fill.prototype.position = function(p, options) { var styleProp; if (this.options === 'upper') { p = 1 - p; } styleProp = this.slider.options.orientation === 'horizontal' ? 'width' : 'height'; return this.element.style[styleProp] = p * this.slider.knob.range() + this.slider.knob.size() / 2 + 'px'; }; function Fill(slider1, options) { this.slider = slider1; this.options = options != null ? options : Fill.defaults; _.addClass(this.slider.element, "fill-" + this.options); this.slider.track.element.appendChild(this.element = _.div({ "class": 'fill' })); } return Fill; })(Component); Debug = Slider.Debug = (function(superClass) { extend(Debug, superClass); Debug.prototype.position = function(p, options) { return this.element.innerText = _.formatObject({ position: p, value: this.slider.value() }); }; function Debug(slider1, options) { this.slider = slider1; this.slider.element.appendChild(this.element = _.pre({ "class": 'debug' })); } return Debug; })(Component); Slider.components = { track: function() { return Track; }, knob: function() { return Knob; }, label: function() { return Label; }, fill: function(o) { if (o.fill != null) { return Fill; } }, debug: function(o) { if (o.debug) { return Debug; } } }; return Slider; })(); }).call(this);
var util = require( 'util' ); var url = require( 'url' ); var browser = require('../airplay').createBrowser(); var media = { url : 'http://commondatastorage.googleapis.com/gtv-videos-bucket/big_buck_bunny_1080p.mp4', file: '/Users/carlos/Desktop/a.mp4', subtitles: [{ language: 'en-US', url: 'http://carlosguerrero.com/captions_styled.vtt', name: 'English', }, { language: 'es-ES', url: 'http://carlosguerrero.com/captions_styled_es.vtt', name: 'Spanish', } ], cover: { title: 'Big Bug Bunny', url: 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/BigBuckBunny.jpg' }, subtitles_style: { backgroundColor: '#FFFFFFFF', // see http://dev.w3.org/csswg/css-color/#hex-notation foregroundColor: '#000FFFF', // see http://dev.w3.org/csswg/css-color/#hex-notation edgeType: 'DROP_SHADOW', // can be: "NONE", "OUTLINE", "DROP_SHADOW", "RAISED", "DEPRESSED" edgeColor: '#AA00FFFF', // see http://dev.w3.org/csswg/css-color/#hex-notation fontScale: 1.5, // transforms into "font-size: " + (fontScale*100) +"%" fontStyle: 'BOLD_ITALIC', // can be: "NORMAL", "BOLD", "BOLD_ITALIC", "ITALIC", fontFamily: 'Droid Sans', fontGenericFamily: 'CURSIVE', // can be: "SANS_SERIF", "MONOSPACED_SANS_SERIF", "SERIF", "MONOSPACED_SERIF", "CASUAL", "CURSIVE", "SMALL_CAPITALS", windowColor: '#AA00FFFF', // see http://dev.w3.org/csswg/css-color/#hex-notation windowRoundedCornerRadius: 10, // radius in px windowType: 'ROUNDED_CORNERS' // can be: "NONE", "NORMAL", "ROUNDED_CORNERS" } } browser.on( 'deviceOn', function( device ) { console.log( 'device online: ' + device.id ); var hls = require( '../airplay' ).createHLS(); hls.on( 'start', function () { console.info( '[HLS] start: %s', hls.getURI() ); }); hls.on( 'stop', function () { console.info( '[HLS] stop: %s', hls.getURI() ); }); hls.on( 'request', function ( req ) { // var uri = url.parse( req.url, true ); console.info( '[HLS] request: %s', req.url ); }); hls.on( 'process', function ( d ) { console.info( '[HLS] segment process: %s, %s, %s', d.index, d.file, d.out.toString() ); }); hls.on( 'segment', function ( d ) { console.info( '[HLS] segment created: %s, %s, %s', d.index, d.file, d.out ); }); hls.on( 'open', function ( d ) { console.info( '[HLS] opend: %s, %s', d.file, util.inspect( d.info ) ); }); hls.on( 'error', function ( err ) { console.info( '[HLS] segment error: ', util.inspect( err ) ); }); hls.on( 'NoFFMPEG', function ( err ) { device.simpleplay(media.url, 0, function(){ console.log("Playing using normal streaming method (not HLS)") }) }); hls.start( 7001 ); hls.open( media.file, function ( info ) { device.simpleplay( hls.getURI(), '0.000000', function ( res ) { console.info( 'ๅผ€ๅง‹ๆ’ญๆ”พๅ•ฆ: ', res ); setTimeout(function(){ device.status( function ( info ) { console.info( 'AppleTV ็Šถๆ€:', info ? info : 'ๆœชๆ’ญๆ”พ' ); if ( info ) { console.log(info) } }); }, 4000); }); }); // device.status( function ( info ) { // console.info( 'AppleTV ็Šถๆ€:', info ? info : 'ๆœชๆ’ญๆ”พ' ); // }); }); browser.on( 'deviceOff', function( device ) { console.log( 'device offline: ' + device.id ); }); browser.start(); // setTimeout( // function(){ // console.info( browser.getDevices( true ) ); // }, // 2000 // );
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM4 12c0-4.42 3.58-8 8-8 1.85 0 3.55.63 4.9 1.69L5.69 16.9C4.63 15.55 4 13.85 4 12zm8 8c-1.85 0-3.55-.63-4.9-1.69L18.31 7.1C19.37 8.45 20 10.15 20 12c0 4.42-3.58 8-8 8z" }), 'Block');
/** C์˜ ๋ฌธ์žฅ์„ ๋ถ„์„ํ•ฉ๋‹ˆ๋‹ค. */ function initProgramCompilerStatement(compiler, CompilerException) { var _Statement = {}; /** ๋ฌธ์žฅ์„ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค. */ function StatementInfo(stmt) { this.statement = stmt; } StatementInfo.prototype.toString = function() { return Handy.format('%s', this.statement); }; /** ์ˆ˜์‹๋ฌธ์„ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค. @param {ExpressionInfo} exprInfo */ function ExpressionStatementInfo(exprInfo) { this.expressionInfo = exprInfo; } ExpressionStatementInfo.prototype.toString = function() { return Handy.format('[%s]', this.expressionInfo); }; /** ๋ณตํ•ฉ๋ฌธ์„ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค. @param {Array.<DeclarationInfo>} decl_list @param {Array.<StatementInfo>} stmt_list */ function CompoundStatementInfo(decl_list, stmt_list) { this.declarationList = decl_list; this.statementList = stmt_list; } CompoundStatementInfo.prototype.toString = function() { return Handy.format('[%s | %s]', this.declarationList, this.statementList); }; /** ์„ ํƒ๋ฌธ์„ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค. @param {string} selectionType @param {ExpressionInfo} condition @param {StatementInfo} stmt @param {StatementInfo} elseStmt */ function SelectionStatementInfo(selectionType, condition, stmt, elseStmt) { this.selectionType = selectionType; this.condition = condition; this.statement = stmt; this.elseStatement = elseStmt; } SelectionStatementInfo.prototype.toString = function() { var selType = this.selectionType; var condExpr = this.condition; var stmt = this.statement; var elseStmt = this.elseStatement; var after = Handy.format ('%s%s', stmt, elseStmt ? (' else ' + elseStmt) : ''); return Handy.format('%s (%s) %s', selType, condExpr, after); }; /** ๋ฐ˜๋ณต๋ฌธ์„ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค. @param {string} iterationType @param {ExpressionInfo} condition @param {StatementInfo} statement @param {ExpressionInfo} initializer @param {ExpressionInfo} iterator */ function IterationStatementInfo (iterationType, condition, statement, initializer, iterator) { this.iterationType = iterationType; this.condition = condition; this.statement = statement; this.initializer = initializer; this.iterator = iterator; } IterationStatementInfo.prototype.toString = function() { var iterType = this.iterationType; var initExpr = getValid(this.initializer, ''); var condExpr = this.condition; var iterExpr = getValid(this.iterator, ''); var statement = this.statement; return Handy.format ('%s (%s;%s;%s) %s', iterType, initExpr, condExpr, iterExpr, statement); }; /** ์ ํ”„๋ฌธ์„ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค. @param {string} jumpType */ function JumpStatementInfo(jumpType, operand) { this.jumpType = jumpType; this.operand = operand; } JumpStatementInfo.prototype.toString = function() { var jumpType = this.jumpType; var operand = this.operand ? ' ' + this.operand : ''; return Handy.format('%s%s', jumpType, operand); }; /** ๋ ˆ์ด๋ธ”๋ฌธ์„ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค. @param {string} labelType @param {object} value @param {StatementInfo} statement */ function LabeledStatementInfo(labelType, value, statement) { this.labelType = labelType; this.value = value; this.statement = statement; } LabeledStatementInfo.prototype.toString = function() { var labelType = getValid(this.labelType, ''); var value = getValid(this.value, ''); var label = Handy.format('%s %s', labelType, value); return Handy.format('[%s:%s]', label, this.statement); }; /** ๋ฌธ์žฅ์„ ๋ถ„์„ํ•ฉ๋‹ˆ๋‹ค. @param {StringBuffer} buffer @return {StatementInfo} */ function getStatementInfo(buffer) { buffer.trim(); // ๋‹ค์Œ ํ† ํฐ์˜ ์‹œ์ž‘ ์ง€์ ์œผ๋กœ ๋ฒ„ํผ ํฌ์ธํ„ฐ๋ฅผ ์˜ฎ๊น๋‹ˆ๋‹ค. var prevIndex = buffer.idx; // ๋ฒ„ํผ ํฌ์ธํ„ฐ๋ฅผ ๋ณด๊ด€ํ•ฉ๋‹ˆ๋‹ค. var token = buffer.get_ctoken(); // ํ† ํฐ์„ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. buffer.idx = prevIndex; // ๋ฒ„ํผ ํฌ์ธํ„ฐ๋ฅผ ๋ณต๊ตฌํ•ฉ๋‹ˆ๋‹ค. // ํš๋“ํ•œ ํ† ํฐ์„ ๊ธฐ์ค€์œผ๋กœ ์กฐ๊ฑด ๋ถ„๊ธฐํ•ฉ๋‹ˆ๋‹ค. var stmtInfo = null; // ๋ฌธ์žฅ ๊ฐ์ฒด์— ๋Œ€ํ•œ ๋ณ€์ˆ˜์ž…๋‹ˆ๋‹ค. switch (token) { // ๋ณตํ•ฉ๋ฌธ ํ† ํฐ case '{': // ๋ณตํ•ฉ๋ฌธ์„ ๋ถ„์„ํ•˜๊ณ  ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. var compoundStmtInfo = getCompoundStatementInfo(buffer); stmtInfo = new StatementInfo(compoundStmtInfo); break; case '}': // ๋ณตํ•ฉ๋ฌธ์˜ ๋งˆ์ง€๋ง‰์„ ๋ฐœ๊ฒฌํ•˜๋ฉด null์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. stmtInfo = null; break; // ์„ ํƒ๋ฌธ ํ† ํฐ case 'if': case 'switch': var selectionStmtInfo = getSelectionStatementInfo(buffer); stmtInfo = new StatementInfo(selectionStmtInfo); break; // ๋ฐ˜๋ณต๋ฌธ ํ† ํฐ case 'while': case 'do': case 'for': var iterationStmtInfo = getIterationStatementInfo(buffer); stmtInfo = new StatementInfo(iterationStmtInfo); break; // ์ ํ”„๋ฌธ ํ† ํฐ case 'goto': case 'continue': case 'break': case 'return': var jumpStmtInfo = getJumpStatementInfo(buffer); stmtInfo = new StatementInfo(jumpStmtInfo); break; // ๋ ˆ์ด๋ธ”๋ฌธ ํ† ํฐ case 'case': case 'default': var labelStmtInfo = getLabeledStatementInfo(buffer); stmtInfo = new StatementInfo(labelStmtInfo); break; // ๊ทธ ์™ธ์˜ ๊ฒฝ์šฐ default: buffer.get_ctoken(); if (buffer.get_ctoken() == ':') { // ๋ ˆ์ด๋ธ” ๋ฌธ์ด๋ผ๋ฉด buffer.idx = prevIndex; // ๋ฒ„ํผ ํฌ์ธํ„ฐ๋ฅผ ๋˜๋Œ๋ฆฐ ํ›„ ๋ถ„์„ํ•ฉ๋‹ˆ๋‹ค. var labelStmtInfo = getLabeledStatementInfo(buffer); stmtInfo = new StatementInfo(labelStmtInfo); } else { // ๋ ˆ์ด๋ธ” ๋ฌธ์ด ์•„๋‹ˆ๋ผ๋ฉด ์ˆ˜์‹๋ฌธ์œผ๋กœ ๊ฐ„์ฃผํ•ฉ๋‹ˆ๋‹ค. buffer.idx = prevIndex; // ๋ฒ„ํผ ํฌ์ธํ„ฐ๋ฅผ ๋˜๋Œ๋ฆฐ ํ›„ ๋ถ„์„ํ•ฉ๋‹ˆ๋‹ค. var exprStmtInfo = getExpressionStatementInfo(buffer); stmtInfo = new StatementInfo(exprStmtInfo); } } // ์ƒ์„ฑํ•œ ํ† ํฐ์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. return stmtInfo; } /** ์ˆ˜์‹๋ฌธ์„ ๋ถ„์„ํ•ฉ๋‹ˆ๋‹ค. @param {StringBuffer} buffer */ function getExpressionStatementInfo(buffer) { var Expr = Program.Compiler.Expression; // ์ˆ˜์‹์„ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. var exprInfo = Expr.getExpressionInfo(buffer); // ๋‹ค์Œ ํ† ํฐ์˜ ์‹œ์ž‘ ์ง€์ ์œผ๋กœ ๋ฒ„ํผ ํฌ์ธํ„ฐ๋ฅผ ๋งž์ถฅ๋‹ˆ๋‹ค. buffer.trim(); // ์„ธ๋ฏธ์ฝœ๋ก ์„ ๋ฐœ๊ฒฌํ•  ์ˆ˜ ์—†์œผ๋ฉด ๋ช…๋ฐฑํ•œ ๋ฌธ๋ฒ• ์œ„๋ฐ˜์ž…๋‹ˆ๋‹ค. if (buffer.peekc() != ';') throw new CompilerException('cannot find end of expression', buffer.peekc()); // ํ™•์ธํ•œ ์„ธ๋ฏธ์ฝœ๋ก ์„ ์ง€๋‚˜๊ฐ‘๋‹ˆ๋‹ค. buffer.getc(); // ํš๋“ํ•œ ์ •๋ณด๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๊ณ  ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. var exprStmt = new ExpressionStatementInfo(exprInfo); return exprStmt; } /** ๋ณตํ•ฉ๋ฌธ์„ ๋ถ„์„ํ•ฉ๋‹ˆ๋‹ค. @param {StringBuffer} buffer */ function getCompoundStatementInfo(buffer) { buffer.trim(); // ๋‹ค์Œ ํ† ํฐ์˜ ์‹œ์ž‘ ์ง€์ ์œผ๋กœ ๋ฒ„ํผ ํฌ์ธํ„ฐ๋ฅผ ๋งž์ถฅ๋‹ˆ๋‹ค. if (buffer.peekc() != '{') throw new CompilerException ('cannot find start of compound statement', buffer.str); buffer.getc(); // ์—ฌ๋Š” ์ค‘๊ด„ํ˜ธ๋ฅผ ์ง€๋‚˜๊ฐ‘๋‹ˆ๋‹ค. var Decl = Program.Compiler.Declaration; // ์„ ์–ธ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. var decl_list = []; while (buffer.is_empty() == false) { // ๋ฒ„ํผ์— ๋ฐ์ดํ„ฐ๊ฐ€ ๋‚จ์•„์žˆ๋Š” ๋™์•ˆ var declInfo = Decl.getDeclarationInfo(buffer); // ์„ ์–ธ ์ •๋ณด๋ฅผ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. if (declInfo == null) // ์„ ์–ธ ํš๋“ ์‹คํŒจ ์‹œ ์ดํ›„๋ฅผ ๋ฌธ์žฅ์œผ๋กœ ๊ฐ„์ฃผํ•ฉ๋‹ˆ๋‹ค. break; decl_list.push(declInfo); // ์„ ์–ธ ๋ฆฌ์ŠคํŠธ์— ์„ ์–ธ ์ •๋ณด๋ฅผ ๋„ฃ์Šต๋‹ˆ๋‹ค. } // ๋ฌธ์žฅ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. var stmt_list = []; while (buffer.is_empty() == false) { // ๋ฒ„ํผ์— ๋ฐ์ดํ„ฐ๊ฐ€ ๋‚จ์•„์žˆ๋Š” ๋™์•ˆ var stmtInfo = getStatementInfo(buffer); // ๋ฌธ์žฅ ์ •๋ณด๋ฅผ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. if (stmtInfo == null) // ๋ฌธ์žฅ ํš๋“ ์‹คํŒจ ์‹œ ์ข…๋ฃŒํ•ฉ๋‹ˆ๋‹ค. break; stmt_list.push(stmtInfo); // ๋ฌธ์žฅ ๋ฆฌ์ŠคํŠธ์— ๋ฌธ์žฅ ์ •๋ณด๋ฅผ ๋„ฃ์Šต๋‹ˆ๋‹ค. } buffer.trim(); // ๋‹ค์Œ ํ† ํฐ์˜ ์‹œ์ž‘ ์ง€์ ์œผ๋กœ ๋ฒ„ํผ ํฌ์ธํ„ฐ๋ฅผ ๋งž์ถฅ๋‹ˆ๋‹ค. if (buffer.peekc() != '}') throw new CompilerException ('cannot find end of compound statement', buffer); buffer.getc(); // ๋‹ซ๋Š” ์ค‘๊ด„ํ˜ธ๋ฅผ ์ง€๋‚˜๊ฐ‘๋‹ˆ๋‹ค. // ํš๋“ํ•œ ์ •๋ณด๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๊ณ  ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. var compoundInfo = new CompoundStatementInfo(decl_list, stmt_list); return compoundInfo; } /** ์„ ํƒ๋ฌธ์„ ๋ถ„์„ํ•ฉ๋‹ˆ๋‹ค. @param {StringBuffer} buffer @return {SelectionStatementInfo} */ function getSelectionStatementInfo(buffer) { var Expr = Program.Compiler.Expression; var selectionStmt = null; // ์„ ํƒ๋ฌธ ๊ฐ์ฒด์— ๋Œ€ํ•œ ๋ณ€์ˆ˜์ž…๋‹ˆ๋‹ค. var token = buffer.get_ctoken(); // ์ฒซ ํ† ํฐ์„ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. if (token == 'if') { // if ๋ฌธ์ž์—ด์ธ ๊ฒฝ์šฐ var selectionType = token; // ์„ ํƒ๋ฌธ์˜ ํ˜•์‹์€ if์ž…๋‹ˆ๋‹ค. // ์—ฌ๋Š” ์†Œ๊ด„ํ˜ธ๋ฅผ ๋ฐœ๊ฒฌํ•˜์ง€ ๋ชปํ•˜๋ฉด ์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. if (buffer.get_ctoken() != '(') throw new CompilerException('cannot find start of conditional expression'); // ์กฐ๊ฑด์‹์„ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. var condExpr = Expr.getExpressionInfo(buffer); if (condExpr == null) throw new CompilerException('cannot find expression'); // ๋‹ซ๋Š” ์†Œ๊ด„ํ˜ธ๋ฅผ ๋ฐœ๊ฒฌํ•˜์ง€ ๋ชปํ•˜๋ฉด ์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. if (buffer.get_ctoken() != ')') throw new CompilerException('cannot find end of conditional expression'); // ์กฐ๊ฑด์‹ ์ดํ›„์— ๋‚˜ํƒ€๋‚˜๋Š” ๋ฌธ์žฅ์„ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. var trueStmt = getStatementInfo(buffer); if (trueStmt == null) throw new CompilerException('cannot find true case statement'); // else ๊ตฌ๋ฌธ์ด ์กด์žฌํ•˜๋Š”์ง€ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค. var falseStmt = null; var prevIndex = buffer.idx; // ๋ฒ„ํผ ํฌ์ธํ„ฐ๋ฅผ ์ž„์‹œ๋กœ ๋ณด๊ด€ํ•ฉ๋‹ˆ๋‹ค. token = buffer.get_ctoken(); // ํ† ํฐ ํš๋“์„ ์‹œ๋„ํ•ฉ๋‹ˆ๋‹ค. if (token == 'else') { // else์ธ ๊ฒฝ์šฐ์˜ ์ฒ˜๋ฆฌ์ž…๋‹ˆ๋‹ค. // ๊ฑฐ์ง“์ธ ๊ฒฝ์šฐ์˜ ๋ฌธ์žฅ์„ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. falseStmt = getStatementInfo(buffer); if (falseStmt == null) throw new CompilerException('cannot find false case statement'); } else { // else๊ฐ€ ์•„๋‹ˆ๋ฉด ๋ฒ„ํผ ํฌ์ธํ„ฐ๋ฅผ ๋˜๋Œ๋ฆฝ๋‹ˆ๋‹ค. buffer.idx = prevIndex; } // ํš๋“ํ•œ ์ •๋ณด๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. selectionStmt = new SelectionStatementInfo (selectionType, condExpr, trueStmt, falseStmt); } else if (token == 'switch') { // switch ๋ฌธ์ž์—ด์ธ ๊ฒฝ์šฐ var selectionType = token; // ์„ ํƒ๋ฌธ์˜ ํ˜•์‹์€ switch์ž…๋‹ˆ๋‹ค. // ์—ฌ๋Š” ์†Œ๊ด„ํ˜ธ๋ฅผ ๋ฐœ๊ฒฌํ•˜์ง€ ๋ชปํ•˜๋ฉด ์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. if (buffer.get_ctoken() != '(') throw new CompilerException('cannot find start of conditional expression'); // ์กฐ๊ฑด์‹์„ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. var condExpr = Expr.getExpressionInfo(buffer); if (condExpr == null) throw new CompilerException('cannot find expression'); // ๋‹ซ๋Š” ์†Œ๊ด„ํ˜ธ๋ฅผ ๋ฐœ๊ฒฌํ•˜์ง€ ๋ชปํ•˜๋ฉด ์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. if (buffer.get_ctoken() != ')') throw new CompilerException('cannot find end of conditional expression'); // ์กฐ๊ฑด์‹ ์ดํ›„์— ๋‚˜ํƒ€๋‚˜๋Š” ๋ฌธ์žฅ์„ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. var trueStmt = getStatementInfo(buffer); if (trueStmt == null) throw new CompilerException('cannot find true case statement'); // ํš๋“ํ•œ ์ •๋ณด๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. selectionStmt = new SelectionStatementInfo (selectionType, condExpr, trueStmt); } else { // ๊ทธ ์™ธ์˜ ๊ฒฝ์šฐ ์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. throw new CompilerException ('invalid selection statement token', token); } // ์ƒ์„ฑํ•œ ๊ฐ์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. return selectionStmt; } /** ๋ฐ˜๋ณต๋ฌธ์„ ๋ถ„์„ํ•ฉ๋‹ˆ๋‹ค. @param {StringBuffer} buffer @return {IterationStatementInfo} */ function getIterationStatementInfo(buffer) { var Expr = Program.Compiler.Expression; var iterStmt = null; // ๋ฐ˜๋ณต๋ฌธ ๊ฐ์ฒด์— ๋Œ€ํ•œ ๋ณ€์ˆ˜์ž…๋‹ˆ๋‹ค. var token = buffer.get_ctoken(); // ์ฒซ ํ† ํฐ์„ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. if (token == 'while') { // while ๋ฌธ์ž์—ด์ธ ๊ฒฝ์šฐ var iterationType = token; // ๋ฐ˜๋ณต๋ฌธ์˜ ํ˜•์‹์€ while์ž…๋‹ˆ๋‹ค. // ์—ฌ๋Š” ์†Œ๊ด„ํ˜ธ๋ฅผ ๋ฐœ๊ฒฌํ•˜์ง€ ๋ชปํ•˜๋ฉด ์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. if (buffer.get_ctoken() != '(') throw new CompilerException('cannot find start of conditional expression'); // ์กฐ๊ฑด์‹์„ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. var condExpr = Expr.getExpressionInfo(buffer); if (condExpr == null) throw new CompilerException('cannot find expression'); // ๋‹ซ๋Š” ์†Œ๊ด„ํ˜ธ๋ฅผ ๋ฐœ๊ฒฌํ•˜์ง€ ๋ชปํ•˜๋ฉด ์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. if (buffer.get_ctoken() != ')') throw new CompilerException('cannot find end of conditional expression'); // ์กฐ๊ฑด์‹ ์ดํ›„์— ๋‚˜ํƒ€๋‚˜๋Š” ๋ฌธ์žฅ์„ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. var trueStmt = getStatementInfo(buffer); if (trueStmt == null) throw new CompilerException('cannot find true case statement'); // ํš๋“ํ•œ ์ •๋ณด๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. iterStmt = new IterationStatementInfo(iterationType, condExpr, trueStmt); } else if (token == 'do') { var iterationType = token; // ๋ฐ˜๋ณต๋ฌธ์˜ ํ˜•์‹์€ do์ž…๋‹ˆ๋‹ค. // ์กฐ๊ฑด์‹ ์ดํ›„์— ๋‚˜ํƒ€๋‚˜๋Š” ๋ฌธ์žฅ์„ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. var trueStmt = getStatementInfo(buffer); if (trueStmt == null) throw new CompilerException('cannot find true case statement'); // while ๋ฌธ์ž์—ด์„ ๋ฐœ๊ฒฌํ•˜์ง€ ๋ชปํ•˜๋ฉด ์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. if (buffer.get_ctoken() != 'while') throw new CompilerException ('cannot find keyword \'while\' in do-while statement'); // ์—ฌ๋Š” ์†Œ๊ด„ํ˜ธ๋ฅผ ๋ฐœ๊ฒฌํ•˜์ง€ ๋ชปํ•˜๋ฉด ์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. if (buffer.get_ctoken() != '(') throw new CompilerException('cannot find start of conditional expression'); // ์กฐ๊ฑด์‹์„ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. var condExpr = Expr.getExpressionInfo(buffer); if (condExpr == null) throw new CompilerException('cannot find expression'); // ๋‹ซ๋Š” ์†Œ๊ด„ํ˜ธ๋ฅผ ๋ฐœ๊ฒฌํ•˜์ง€ ๋ชปํ•˜๋ฉด ์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. if (buffer.get_ctoken() != ')') throw new CompilerException('cannot find end of conditional expression'); // ์„ธ๋ฏธ์ฝœ๋ก ์„ ๋ฐœ๊ฒฌํ•˜์ง€ ๋ชปํ•˜๋ฉด ์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. // ๋‹ซ๋Š” ์†Œ๊ด„ํ˜ธ๋ฅผ ๋ฐœ๊ฒฌํ•˜์ง€ ๋ชปํ•˜๋ฉด ์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. if (buffer.get_ctoken() != ';') throw new CompilerException('cannot find end of do-while statement'); // ํš๋“ํ•œ ์ •๋ณด๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. iterStmt = new IterationStatementInfo(iterationType, condExpr, trueStmt); } else if (token == 'for') { // ๋ฐ˜๋ณต๋ฌธ์˜ ํ˜•์‹์€ for์ž…๋‹ˆ๋‹ค. var iterationType = token; // ์—ฌ๋Š” ์†Œ๊ด„ํ˜ธ๋ฅผ ๋ฐœ๊ฒฌํ•˜์ง€ ๋ชปํ•˜๋ฉด ์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. if (buffer.get_ctoken() != '(') throw new CompilerException('cannot find start of conditional expression'); // ์ดˆ๊ธฐ์‹์„ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. var initExpr = Expr.getExpressionInfo(buffer); if (buffer.get_ctoken() != ';') // ์„ธ๋ฏธ์ฝœ๋ก ์„ ๋ฐœ๊ฒฌํ•˜์ง€ ๋ชปํ•˜๋ฉด ์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. throw new CompilerException('cannot find end of initializer'); // ์กฐ๊ฑด์‹์„ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. var condExpr = Expr.getExpressionInfo(buffer); if (buffer.get_ctoken() != ';') // ์„ธ๋ฏธ์ฝœ๋ก ์„ ๋ฐœ๊ฒฌํ•˜์ง€ ๋ชปํ•˜๋ฉด ์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. throw new CompilerException('cannot find end of condition'); // ์ฆ๊ฐ์‹์„ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. var iterExpr = Expr.getExpressionInfo(buffer); if (buffer.get_ctoken() != ')') // ๋‹ซ๋Š” ์†Œ๊ด„ํ˜ธ๋ฅผ ๋ฐœ๊ฒฌํ•˜์ง€ ๋ชปํ•˜๋ฉด ์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. throw new CompilerException('cannot find end of iterator'); // ์กฐ๊ฑด์‹ ์ดํ›„์— ๋‚˜ํƒ€๋‚˜๋Š” ๋ฌธ์žฅ์„ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. var trueStmt = getStatementInfo(buffer); if (trueStmt == null) throw new CompilerException('cannot find true case statement'); // ํš๋“ํ•œ ์ •๋ณด๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. iterStmt = new IterationStatementInfo (iterationType, condExpr, trueStmt, initExpr, iterExpr); } else { // ๊ทธ ์™ธ์˜ ๊ฒฝ์šฐ ์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. throw new CompilerException ('invalid iteration statement token', token); } return iterStmt; } /** ์ ํ”„๋ฌธ์„ ๋ถ„์„ํ•ฉ๋‹ˆ๋‹ค. @param {StringBuffer} buffer @return {JumpStatementInfo} */ function getJumpStatementInfo(buffer) { var Expr = Program.Compiler.Expression; var jumpStmt = null; // ๋ฐ˜๋ณต๋ฌธ ๊ฐ์ฒด์— ๋Œ€ํ•œ ๋ณ€์ˆ˜์ž…๋‹ˆ๋‹ค. var token = buffer.get_ctoken(); // ์ฒซ ํ† ํฐ์„ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. if (token == 'goto') { // goto ๋ฌธ์ž์—ด์ธ ๊ฒฝ์šฐ var jumpType = token; // ์ ํ”„๋ฌธ์˜ ํ˜•์‹์€ goto์ž…๋‹ˆ๋‹ค. var identifier = buffer.get_ctoken(); // ์‹๋ณ„์ž๋ฅผ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. if (identifier == null) // ์‹๋ณ„์ž ํš๋“์— ์‹คํŒจํ•œ ๊ฒฝ์šฐ ์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. throw new CompilerException ('cannot find identifier after goto'); // ์„ธ๋ฏธ์ฝœ๋ก ์„ ๋ฐœ๊ฒฌํ•˜์ง€ ๋ชปํ•˜๋ฉด ์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. if (buffer.get_ctoken() != ';') throw new CompilerException('cannot find start of conditional expression'); // ํš๋“ํ•œ ์ •๋ณด๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. jumpStmt = new JumpStatementInfo(jumpType, identifier); } else if (token == 'continue' || token == 'break') { var jumpType = token; // ์ ํ”„๋ฌธ์˜ ํ˜•์‹์€ ํš๋“ํ•œ ํ† ํฐ์ž…๋‹ˆ๋‹ค. if (buffer.get_ctoken() != ';') // ์„ธ๋ฏธ์ฝœ๋ก ์„ ๋ฐœ๊ฒฌํ•˜์ง€ ๋ชปํ•˜๋ฉด ์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. throw new CompilerException('cannot find start of conditional expression'); // ํš๋“ํ•œ ์ •๋ณด๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. jumpStmt = new JumpStatementInfo(jumpType); } else if (token == 'return') { var jumpType = token; // ์ ํ”„๋ฌธ์˜ ํ˜•์‹์€ ํš๋“ํ•œ ํ† ํฐ์ž…๋‹ˆ๋‹ค. // ์ˆ˜์‹์„ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. var expression = Expr.getExpressionInfo(buffer); if (buffer.get_ctoken() != ';') // ์„ธ๋ฏธ์ฝœ๋ก ์„ ๋ฐœ๊ฒฌํ•˜์ง€ ๋ชปํ•˜๋ฉด ์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. throw new CompilerException('cannot find start of conditional expression'); // ํš๋“ํ•œ ์ •๋ณด๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. jumpStmt = new JumpStatementInfo(jumpType, expression); } // ์ƒ์„ฑํ•œ ์ ํ”„๋ฌธ ๊ฐ์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. return jumpStmt; } /** ๋ ˆ์ด๋ธ” ๋ฌธ์„ ๋ถ„์„ํ•ฉ๋‹ˆ๋‹ค. @param {StringBuffer} buffer @return {LabeledStatementInfo} */ function getLabeledStatementInfo(buffer) { var Expr = Program.Compiler.Expression; var labelStmt = null; // ๋ฐ˜๋ณต๋ฌธ ๊ฐ์ฒด์— ๋Œ€ํ•œ ๋ณ€์ˆ˜์ž…๋‹ˆ๋‹ค. var token = buffer.get_ctoken(); // ์ฒซ ํ† ํฐ์„ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. if (token == 'case') { // case ๋ฌธ์ž์—ด์ธ ๊ฒฝ์šฐ var labelType = token; // ์ ํ”„๋ฌธ์˜ ํ˜•์‹์€ case์ž…๋‹ˆ๋‹ค. // ์ˆ˜์‹์„ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. var value = Expr.getExpressionInfo(buffer); if (value == null) throw new CompilerException ('cannot find expression after keyword case'); // ์ฝœ๋ก ์„ ๋ฐœ๊ฒฌํ•˜์ง€ ๋ชปํ•˜๋ฉด ์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. if (buffer.get_ctoken() != ':') throw new CompilerException('cannot find start of conditional expression'); // ๋ฌธ์žฅ์„ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. var statement = getStatementInfo(buffer); // ํš๋“ํ•œ ์ •๋ณด๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. labelStmt = new LabeledStatementInfo(labelType, value, statement); } else if (token == 'default') { // default ๋ฌธ์ž์—ด์ธ ๊ฒฝ์šฐ var labelType = token; // ์ ํ”„๋ฌธ์˜ ํ˜•์‹์€ default์ž…๋‹ˆ๋‹ค. // ์ฝœ๋ก ์„ ๋ฐœ๊ฒฌํ•˜์ง€ ๋ชปํ•˜๋ฉด ์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. if (buffer.get_ctoken() != ':') throw new CompilerException('cannot find start of conditional expression'); // ๋ฌธ์žฅ์„ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. var statement = getStatementInfo(buffer); // ํš๋“ํ•œ ์ •๋ณด๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. labelStmt = new LabeledStatementInfo(labelType, null, statement); } else if (is_fnamch(token.charAt(0)) == false) { throw new CompilerException('invalid label found', token); } else { var labelName = token; // ํš๋“ํ•œ ํ† ํฐ์€ ๋ ˆ์ด๋ธ”์˜ ์ด๋ฆ„์ž…๋‹ˆ๋‹ค. // ์ฝœ๋ก ์„ ๋ฐœ๊ฒฌํ•˜์ง€ ๋ชปํ•˜๋ฉด ์˜ˆ์™ธ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. if (buffer.get_ctoken() != ':') throw new CompilerException('cannot find start of conditional expression'); var statement = getStatementInfo(buffer); // ๋ฌธ์žฅ์„ ํš๋“ํ•ฉ๋‹ˆ๋‹ค. // ํš๋“ํ•œ ์ •๋ณด๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. labelStmt = new LabeledStatementInfo(null, labelName, statement); } // ์ƒ์„ฑํ•œ ๊ฐ์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. return labelStmt; } // ๋“ฑ๋ก _Statement.StatementInfo = StatementInfo; _Statement.ExpressionStatementInfo = ExpressionStatementInfo; _Statement.LabeledStatementInfo = LabeledStatementInfo; _Statement.IterationStatementInfo = IterationStatementInfo; _Statement.CompoundStatementInfo = CompoundStatementInfo; _Statement.JumpStatementInfo = JumpStatementInfo; _Statement.getCompoundStatementInfo = getCompoundStatementInfo; _Statement.getStatementInfo = getStatementInfo; compiler.Statement = _Statement; }
"use strict"; var jsx = require('jsx-runtime'); var hasOwn = Object.prototype.hasOwnProperty; var emptyTags = require('empty-tags').reduce(function(map, tag) { map[tag] = true; return map; }, Object.create(null)); var SVG_NS = 'http://www.w3.org/2000/svg'; var HTML_NS = 'http://www.w3.org/1999/xhtml'; var renderer = jsx.register('DOM', { before: function(element) { this.scope.namespaces = []; return element; }, tags: { '*': { enter: function(tag, props) { var namespaces = this.scope.namespaces; if (tag === 'svg') { namespaces.unshift(SVG_NS); } else if (tag === 'foreignObject') { namespaces.unshift(HTML_NS); } var element; if (namespaces.length) { element = document.createElementNS(namespaces[0], tag); } else { element = document.createElement(tag); } applyProps(element, props); return element; }, leave: function(parent, tag) { if ( tag === 'svg' && this.scope.namespaces[0] === SVG_NS || tag === 'foreignObject' && this.scope.namespaces[0] === HTML_NS ) { this.scope.namespaces.shift(); } return parent; }, child: function(child, parent) { if (child instanceof Element) { // do nothing } else { child = document.createTextNode(child + ''); } parent.appendChild(child); return parent; }, children: function(children, parent, tag) { if (typeof emptyTags[tag.toLowerCase()] !== 'undefined') { throw new Error('Tag <' + tag + ' /> cannot have children'); } return children; } } } }); module.exports = renderer; function applyStyle(element, style) { if (typeof style === 'string') { element.setAttribute('style', style); return; } var elementStyle = element.style; for (var key in style) { if (!hasOwn.call(style, key)) continue; elementStyle[key] = style[key]; } } function applyProps(element, props) { for (var key in props) { if (!hasOwn.call(props, key)) continue; var val = props[key]; switch (key) { case 'style': applyStyle(element, val); break; case 'class': element.className = val; break; case 'for': element.cssFor = val; break; case 'innerHTML': case 'outerHTML': case 'textContent': case 'innerText': case 'text': console.warn('Direct manipulation of tags content is not allowed'); break; default: { if (key.indexOf('-') !== -1) { element.setAttribute(key, val); } else { element[key] = val; } } } } }
(function(){ 'use strict'; /** * @ngdoc directive * @name mdtCell * @restrict E * @requires mdtTable * @requires mdtRow * * @description * Representing a cell which should be placed inside `mdt-row` element directive. * * @param {boolean=} htmlContent if set to true, then html content can be placed into the content of the directive. * @param {string=} editableField if set, then content can be editable. * * Available modes are: * * - "smallEditDialog" - A simple, one-field edit dialog on click * - "largeEditDialog" - A complex, flexible edit edit dialog on click * * @param {string=} editableFieldTitle if set, then it sets the title of the dialog. (only for `largeEditDialog`) * @param {number=} editableFieldMaxLength if set, then it sets the maximum length of the field. * * * @example * <pre> * <mdt-table> * <mdt-header-row> * <mdt-column>Product name</mdt-column> * <mdt-column>Price</mdt-column> * <mdt-column>Details</mdt-column> * </mdt-header-row> * * <mdt-row ng-repeat="product in ctrl.products"> * <mdt-cell>{{product.name}}</mdt-cell> * <mdt-cell>{{product.price}}</mdt-cell> * <mdt-cell html-content="true"> * <a href="productdetails/{{product.id}}">more details</a> * </mdt-cell> * </mdt-row> * </mdt-table> * </pre> */ function mdtCellDirective($interpolate){ return { restrict: 'E', replace: true, transclude: true, require: '^mdtRow', link: function($scope, element, attr, mdtRowCtrl, transclude){ var attributes = { htmlContent: attr.htmlContent ? attr.htmlContent : false, editableField: attr.editableField ? attr.editableField : false, editableFieldTitle: attr.editableFieldTitle ? attr.editableFieldTitle : false, editableFieldMaxLength: attr.editableFieldMaxLength ? attr.editableFieldMaxLength : false }; transclude(function (clone) { if(attr.htmlContent){ mdtRowCtrl.addToRowDataStorage(clone, attributes); }else{ //TODO: better idea? var cellValue = $interpolate(clone.html())($scope.$parent); mdtRowCtrl.addToRowDataStorage(cellValue, attributes); } }); } }; } angular .module('mdDataTable') .directive('mdtCell', mdtCellDirective); }());
var util = require("util"); var request = require("request"); var BaseTrigger = require("./baseTrigger.js").BaseTrigger; var TinyCache = require( "tinycache" ); var cache1 = new TinyCache(); var cache2 = new TinyCache(); /* Trigger that automatically looks up users on reddit when they join. options: cacheJoinedTime - If the user joined the chat previously within this many ms, trigger will not fire. Defaults to 1 hour. cacheDataTime - data will be cached for this long to reduce wait for obtaining data. Defaults to 1 hour. */ var RedditOnJoinTrigger = function() { RedditOnJoinTrigger.super_.apply(this, arguments); }; util.inherits(RedditOnJoinTrigger, BaseTrigger); var type = "RedditOnJoinTrigger"; exports.triggerType = type; exports.create = function(name, chatBot, options) { var trigger = new RedditOnJoinTrigger(type, name, chatBot, options); trigger.respectsMute = false; trigger.options.cacheJoinedTime = trigger.options.cacheTime || 1 * 60 * 60 * 1000; trigger.options.cacheDataTime = trigger.options.cacheTime || 1 * 60 * 60 * 1000; trigger.allowMessageTriggerAfterResponse = true; return trigger; }; RedditOnJoinTrigger.prototype._respondToEnteredMessage = function(roomId, userId) { if(cache1.get(userId)===null) { cache1.put(userId,"sent",this.options.cacheJoinedTime); return this._respond(roomId,userId); } else { return false; } } RedditOnJoinTrigger.prototype._respond = function(roomId,userToCheck) { if(!this.options.redditapiurl) { this.winston.error(this.chatBot.name+"/"+this.name+": Reddit API Url not defined! Cannot look up user!"); return false; } var steamid = ""+userToCheck+""; if (steamid) { var that = this; var cachedResult=cache2.get(steamid); if(cachedResult===null) { that.winston.info(that.chatBot.name+"/"+that.name+": Checking reddit for " + steamid); request.get({method:"GET",encoding:"utf8",uri:that.options.redditapiurl+"steamid/"+steamid,json:true,followAllRedirects:true}, function(error, response, body) { if (error) { try { that.winston.warn(that.chatBot.name+"/"+that.name+": Code " + response.statusCode + " from redditapi for steamid " + steamid); } catch (err) { that.winston.error(that.chatBot.name+"/"+that.name,err.stack) } return; } var redditinfo = body; redditinfo.steamid = redditinfo.steamid.replace("https://steamcommunity.com/profiles/",""); var result = that._getParsedResultForJoin(redditinfo, steamid); if (result) { that._sendMessageAfterDelay(roomId, result); cache2.put(steamid,result,that.options.cacheDataTime); } }); } else { that._sendMessageAfterDelay(toId, cachedResult); } return true; } return false; } RedditOnJoinTrigger.prototype._displayName = function(steamid) { if(this.chatBot.steamFriends.personaStates && steamid in this.chatBot.steamFriends.personaStates) { return this.chatBot.steamFriends.personaStates[steamid].player_name + "/"+steamid; } else { return steamid; } } RedditOnJoinTrigger.prototype._getParsedResultForJoin = function(redditinput, steamid) { if (redditinput && redditinput.success) { var message=""; if(redditinput.success && redditinput.banstatus) { message = this._displayName(steamid) + " has been BANNED from /r/SGS." + (redditinput.reddit ? ("\nReddit profile: https://www.reddit.com/user/"+redditinput.reddit) : "") + "\nSteam Profile: https://steamcommunity.com/profiles/"+steamid + "\nSteamrep: https://steamrep.com/profiles/" + steamid + (redditinput.banreason ? ("\nReddit Ban Reason: " + redditinput.banreason) : ""); } else if(redditinput.success && redditinput.flair && redditinput.flair.substr(0,3) === "mod") { message = "Welcome, " + this._displayName(steamid) + " AKA /u/" + redditinput.reddit + ", moderator(?) of /r/SGS! Your (raw) flair is " + redditinput.flair; } else if(redditinput.success) { var flair = ". Your current flair level is "; if(redditinput.flair==="tier0") { flair+= "White, with no recorded trades in /r/SGS."; } else if(redditinput.flair==="tier1") { flair+= "Gray, with 1+ SGS trades."; } else if(redditinput.flair==="tier2") { flair+= "Blue, with 5+ SGS trades."; } else if(redditinput.flair==="tier3") { flair+= "Red, with 10+ SGS trades."; } else if(redditinput.flair==="tier4") { flair+= "Green, with 20+ SGS trades."; } else if(redditinput.flair==="tier5") { flair+= "Purple, with 50+ SGS trades."; } else if(redditinput.flair==="white") { flair+= "White, with no recorded trades in /r/SGS."; } else if(redditinput.flair==="gray") { flair+= "Gray, with 1+ SGS trades."; } else if(redditinput.flair==="blue") { flair+= "Blue, with 5+ SGS trades."; } else if(redditinput.flair==="red") { flair+= "Red, with 10+ SGS trades."; } else if(redditinput.flair==="green") { flair+= "Green, with 20+ SGS trades."; } else if(redditinput.flair==="purple") { flair+= "Purple, with 50+ SGS trades."; } else { flair += "not a level I understand. The raw data I got was '"+redditinput.flair+"'."; } message = "Welcome, " + this._displayName(steamid) + " AKA /u/" + redditinput.reddit + flair; } return message; } return null; }
import {} from 'moogose';
/** * api ๆŽฅๅฃ่ฏทๆฑ‚ */ C.api = function(url,get,post,callback,errorback){ //gost_loading.show(); if(post!=null){ var geturl = ''; for(var p in get){ geturl += p+'='+get[p]+'&'; } url += '?' + geturl.substring(0,geturl.length-1);//ๅŽปๆމๆœซๅฐพ็š„ & ๅญ—็ฌฆ C.ajax.post(url,post,function(err,DATA){ if(err){ return errorback?errorback():0; } dealBackData(DATA,callback,errorback); },'html'); }else{ //ๆฒกๆœ‰postๅ‚ๆ•ฐ C.ajax.get(url,get,function(err,DATA){ if(err){ return errorback?errorback():0; } dealBackData(DATA,callback,errorback); },'html'); } //ๅค„็†ๆŽฅๅฃ่ฟ”ๅ›ž็š„ๆ•ฐๆฎ function dealBackData(DATA,callback,errorback){ eval(' var JsonOb = '+DATA+';'); //{"code":"","msg":"","data":[]} if(JsonOb.code==200){ callback?callback(JsonOb):0;//ๆญฃๅธธ็Šถๆ€่ฐƒ็”จๅ›ž่ฐƒ }else{ errorback?errorback(JsonOb):0; //้”™่ฏฏๅค„็† } } };
'use strict'; /* eslint-disable global-require */ require('../bin/pixi'); describe('PIXI', function () { it('should exist as a global object', function () { expect(PIXI).to.be.an('object'); }); require('./core'); require('./interaction'); });
'use babel'; import CallStackEntry from './call-stack-entry'; import {DELIMITER, ASSIGN_SYMBOL} from '../messaging/message-utils'; export default function callStackFromString(string) { const callStack = []; if (string) { const splitted = string.split(DELIMITER); for (const elem of splitted) { const innerSplitted = elem.split(ASSIGN_SYMBOL); const entry = new CallStackEntry(innerSplitted[0], innerSplitted[1]); callStack.unshift(entry); } } return callStack; }
var gulp = require('gulp'), jshintStylish = require('jshint-stylish'), gutil = require('gulp-util'),// Currently unused, but gulp strongly suggested I install... jshint = require('gulp-jshint'), jsHintOptions = { "trailing": true, "nonbsp": true, "noarg": true, "latedef": true, "sub": true, "smarttabs": true, "evil": true, "esnext": true, "node": true, "eqeqeq": false, "globals": { "fs": false, "Config": false, "ResourceMonitor": false, "toId": false, "toUserid": false, "toName": false, "sanitize": false, "string": false, "clampIntRange": false, "LoginServer": false, "Users": false, "Rooms": false, "Verifier": false, "CommandParser": false, "Simulator": false, "Tournaments": false, "Dnsbl": false, "Cidr": false, "Sockets": false, "Tools": false, "TeamValidator": false } }; gulp.task('lint', function() { var directories = ['./*.js', './data/*.js', './mods/*.js', './config/*.js']; console.log("\n\n*** Linting JavaScript Files ***\n\n"); gulp.src(directories) .pipe(jshint(jsHintOptions)) .pipe(jshint.reporter(jshintStylish)); }); gulp.task('default', ['lint']);
'use strict'; import Model from './lib/Model'; export default Model;
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- // Verifies TypedArray builtin properties if (this.WScript && this.WScript.LoadScriptFile) { // Check for running in ch this.WScript.LoadScriptFile("..\\UnitTestFramework\\UnitTestFramework.js"); } var TypedArrayCtors = [ 'Int8Array', 'Uint8Array', 'Uint8ClampedArray', 'Int16Array', 'Uint16Array', 'Int32Array', 'Uint32Array', 'Float32Array', 'Float64Array' ]; function mangle(u8) { u8.length = -2; u8.byteLength = 2000; u8.byteOffset = 45; u8.buffer = 25; u8.BYTES_PER_ELEMENT = 4; } var tests = [ { name: "TypedArray builtin properties can't be overwritten, but writing to them does not throw an error", body: function () { var arr = new ArrayBuffer(100); var u8 = new Uint8Array(arr, 90); for (var i = 0; i < u8.length; i++) { u8[i] = i; } mangle(u8); assert.areEqual(10, u8.length, "Writing to length has no effect"); assert.areEqual(10, u8.byteLength, "Writing to byteLength has no effect"); assert.areEqual(90, u8.byteOffset, "Writing to byteOffset has no effect"); assert.areEqual(1, u8.BYTES_PER_ELEMENT, "Writing to BYTES_PER_ELEMENT has no effect"); assert.isTrue(arr === u8.buffer, "Writing to buffer has no effect"); assert.throws(function() { Array.prototype.splice.call(u8, 4, 3, 1, 2, 3, 4, 5); }, TypeError, "Array.prototype.splice tries to set the length property of the TypedArray object which will throw", "Cannot define property: object is not extensible"); assert.areEqual(10, u8.length, "Array.prototype.splice throws when it tries to set the length property"); assert.areEqual(10, u8.byteLength, "The byteLength property should not be changed"); assert.areEqual([0,1,2,3,1,2,3,4,5,7], u8, "After splice, array has correct values - NOTE: last two values are gone from the array"); assert.throws(function() { Array.prototype.push.call(u8, 100); }, TypeError, "Array.prototype.push tries to set the length property of the TypedArray object which will throw", "Cannot define property: object is not extensible"); assert.areEqual([0,1,2,3,1,2,3,4,5,7], u8, "Array.prototype.push doesn't modify the TypedArray"); } }, { name: "TypedArray constructors treat explicit undefined/null first argument as zero", body: function () { for (let taCtor of TypedArrayCtors) { let ta = new this[taCtor](undefined); assert.areEqual(0, ta.length, "new " + taCtor + "(undefined) yields an array with zero length"); ta = new this[taCtor](undefined, undefined, undefined); assert.areEqual(0, ta.length, "new " + taCtor + "(undefined, undefined, undefined) yields an array with zero length"); ta = new this[taCtor](null); assert.areEqual(0, ta.length, "new " + taCtor + "(null) yields an array with zero length"); ta = new this[taCtor](null, null, null); assert.areEqual(0, ta.length, "new " + taCtor + "(null, null, null) yields an array with zero length"); } } }, { name: "TypedArray constructors treat bool true and false first argument as 1 and 0 respectively", body: function () { for (let taCtor of TypedArrayCtors) { let ta = new this[taCtor](true); assert.areEqual(1, ta.length, "new " + taCtor + "(true) yields an array with length one"); ta = new this[taCtor](false); assert.areEqual(0, ta.length, "new " + taCtor + "(false) yields an array with length zero"); } } }, { name: "TypedArray constructors treat string first argument using conversion to index via ToIndex", body: function () { for (let taCtor of TypedArrayCtors) { let ta = new this[taCtor]("0"); assert.areEqual(0, ta.length, "new " + taCtor + "('0') yields an array with length zero"); ta = new this[taCtor]("25"); assert.areEqual(25, ta.length, "new " + taCtor + "('25') yields an array with length 25"); ta = new this[taCtor]("abc"); assert.areEqual(0, ta.length, "new " + taCtor + "('abc') yields an array with length zero because NaN converts to zero"); } } }, { name: "TypedArray constructors throw TypeError when first argument is a symbol", body: function () { for (let taCtor of TypedArrayCtors) { assert.throws(function () { new this[taCtor](Symbol()); }, TypeError, "new " + taCtor + "(<symbol>) throws TypeError", "Number expected"); } } }, { name: "TypedArray constructors treat object first argument as array-like (unless iterable) (and therefore do not pass them through ToIndex)", body: function () { let objEmpty = { }; let objWithLength = { length: 2 }; let objWithToString = { toString() { return 3; } }; let objWithValueOf = { valueOf() { return 4; } }; let objWithToPrimitive = { [Symbol.toPrimitive]() { return 5; } }; for (let taCtor of TypedArrayCtors) { let ta = new this[taCtor](objEmpty); assert.areEqual(0, ta.length, "new " + taCtor + "(<empty object>) yields an array with length zero"); ta = new this[taCtor](objWithLength); assert.areEqual(2, ta.length, "new " + taCtor + "(<object with 'length: 2' property>) yields an array with length two"); ta = new this[taCtor](objWithToString); assert.areEqual(0, ta.length, "new " + taCtor + "(<object with toString method>) yields an array with length zero"); ta = new this[taCtor](objWithValueOf); assert.areEqual(0, ta.length, "new " + taCtor + "(<object with valueOf method>) yields an array with length zero"); ta = new this[taCtor](objWithToPrimitive); assert.areEqual(0, ta.length, "new " + taCtor + "(<object with @@toPrimitive method>) yields an array with length zero"); } } }, { name: "TypedArray constructors create array from iterable object", body: function () { let objIterable = { [Symbol.iterator]() { let i = 0; return { next() { return { done: i == 3, value: i++ }; } }; } }; for (let taCtor of TypedArrayCtors) { let ta = new this[taCtor](objIterable); assert.areEqual(3, ta.length, "new " + taCtor + "(<iterable object with three elements>) yields an array with length three"); assert.areEqual(0, ta[0], "[" + taCtor + "]: first element is zero"); assert.areEqual(1, ta[1], "[" + taCtor + "]: second element is one"); assert.areEqual(2, ta[2], "[" + taCtor + "]: third element is two"); } } }, { name: "TypedArray constructors and .from cache next method when creating array from iterable object", body: function () { let objIterable = { [Symbol.iterator]() { let i = 0; return { next() { this.next = function (){ throw new Error ("Next should have been cached so this should not be called") }; return { done: i == 3, value: i++ }; } }; } }; for (let taCtor of TypedArrayCtors) { let ta = new this[taCtor](objIterable); assert.areEqual(3, ta.length, "new " + taCtor + "(<iterable object with three elements>) yields an array with length three"); assert.areEqual(0, ta[0], "[" + taCtor + "]: first element is zero"); assert.areEqual(1, ta[1], "[" + taCtor + "]: second element is one"); assert.areEqual(2, ta[2], "[" + taCtor + "]: third element is two"); } for (let taCtor of TypedArrayCtors) { let ta = this[taCtor].from(objIterable); assert.areEqual(3, ta.length, "new " + taCtor + "(<iterable object with three elements>) yields an array with length three"); assert.areEqual(0, ta[0], "[" + taCtor + "]: first element is zero"); assert.areEqual(1, ta[1], "[" + taCtor + "]: second element is one"); assert.areEqual(2, ta[2], "[" + taCtor + "]: third element is two"); } } }, { name: "TypedArray constructed out of an iterable object", body: function () { function getIterableObj (array) { return { [Symbol.iterator]: ()=> { return { next: () => { return { value: array.shift(), done: array.length == 0 }; } }; } }; } function getIterableObjNextDesc (array) { return { get: function () { array.shift(); // side effect return function () { return { value: array.shift(), done: array.length == 0 }; }; } }; } for(var t of TypedArrayCtors) { var arr = new this[t](getIterableObj([1,2,3,4])); assert.areEqual(3, arr.length, "TypedArray " + t + " created from iterable has length == 3"); assert.areEqual(1, arr[0], "TypedArray " + t + " created from iterable has element #0 == 1"); assert.areEqual(2, arr[1], "TypedArray " + t + " created from iterable has element #1 == 2"); assert.areEqual(3, arr[2], "TypedArray " + t + " created from iterable has element #2 == 3"); } // change array's iterator (function() { for(var t of TypedArrayCtors) { var a = [1,2,3,4]; a[Symbol.iterator] = getIterableObj([99,0])[Symbol.iterator]; var arr = new this[t](a); assert.areEqual(1, arr.length, "TypedArray " + t + " created from array with user-defined iterator has length == 1"); assert.areEqual(99, arr[0], "TypedArray " + t + " created from array with user-defined iterator has element #0 == 99"); } })(); // helpers for testing all typed arrays when built-in array iterator is changed function testTypedArrayConstructorWithIterableArray(inputarray, t, func, text) { func(); var arr = new this[t](inputarray); assert.areEqual(1, arr.length, "TypedArray " + t + " created from array with " + text + " has length == 1"); assert.areEqual(99, arr[0], "TypedArray " + t + " created from array with "+ text + " has element #0 == 99"); } function testAllTypedArrayConstructorsWithIterableArray(inputarray, func, text) { testTypedArrayConstructorWithIterableArray(inputarray, 'Int8Array', func, text); testTypedArrayConstructorWithIterableArray(inputarray, 'Uint8Array', func, text); testTypedArrayConstructorWithIterableArray(inputarray, 'Uint8ClampedArray', func, text); testTypedArrayConstructorWithIterableArray(inputarray, 'Int16Array', func, text); testTypedArrayConstructorWithIterableArray(inputarray, 'Uint16Array', func, text); testTypedArrayConstructorWithIterableArray(inputarray, 'Int32Array', func, text); testTypedArrayConstructorWithIterableArray(inputarray, 'Uint32Array', func, text); testTypedArrayConstructorWithIterableArray(inputarray, 'Float32Array', func, text); testTypedArrayConstructorWithIterableArray(inputarray, 'Float64Array', func, text); } // change built-in Array prototype's iterator (function() { var builtinArrayPrototypeIteratorDesc = Object.getOwnPropertyDescriptor(Array.prototype, Symbol.iterator); var a = [1,2,3,4]; Object.defineProperty(Array.prototype, Symbol.iterator, {enumerable: false, configurable: true, writable: true}); var overrideBuiltinArrayPrototypeIterator = function() { Array.prototype[Symbol.iterator] = getIterableObj([99,0])[Symbol.iterator]; }; testAllTypedArrayConstructorsWithIterableArray(a, overrideBuiltinArrayPrototypeIterator, "Array.prototype overridden"); Object.defineProperty(Array.prototype, Symbol.iterator, builtinArrayPrototypeIteratorDesc); })(); // change built-in array iterator's next function (function() { var arrayIteratorProto = Object.getPrototypeOf([][Symbol.iterator]()); var builtinArrayPrototypeIteratorNext = arrayIteratorProto.next; var overrideBuiltinArrayIteratorNext = function() { arrayIteratorProto.next = getIterableObj([99,0])[Symbol.iterator]().next; } var a = [1,2,3,4]; testAllTypedArrayConstructorsWithIterableArray(a, overrideBuiltinArrayIteratorNext, "%ArrayIteratorPrototype%.next overridden"); arrayIteratorProto.next = builtinArrayPrototypeIteratorNext; })(); // change built-in array iterator's next getter function (function() { var arrayIteratorProto = Object.getPrototypeOf([][Symbol.iterator]()); var builtinArrayPrototypeIteratorNextDesc = Object.getOwnPropertyDescriptor(arrayIteratorProto, "next"); var overrideBuiltinArrayIteratorNext = function() { Object.defineProperty(arrayIteratorProto, "next", getIterableObjNextDesc([0,99,0])); } var a = [1,2,3,4]; testAllTypedArrayConstructorsWithIterableArray(a, overrideBuiltinArrayIteratorNext, "%ArrayIteratorPrototype%.next overridden by getter"); Object.defineProperty(arrayIteratorProto, "next", builtinArrayPrototypeIteratorNextDesc); })(); } }, { name: "TypedArray constructor and TypedArray.from don't get @@iterator twice", body: function () { let count = 0; new Uint8Array({ get [Symbol.iterator]() { count++; return [][Symbol.iterator]; } }); assert.areEqual(count, 1, "TypedArray constructor calls @@iterator getter once"); count = 0; new Uint8Array(new Proxy({}, { get(target, property) { if (property === Symbol.iterator) { count++; return [][Symbol.iterator]; } return Reflect.get(target, property); } })); assert.areEqual(count, 1, "TypedArray constructor calls proxy's getter with @@iterator as parameter only once"); count = 0; Uint8Array.from({ get [Symbol.iterator]() { count++; return [][Symbol.iterator]; } }); assert.areEqual(count, 1, "TypedArray.from calls @@iterator getter once"); count = 0; Uint8Array.from(new Proxy({}, { get(target, property) { if (property === Symbol.iterator) { count++; return [][Symbol.iterator]; } return Reflect.get(target, property); } })); assert.areEqual(count, 1, "TypedArray.from calls proxy's getter with @@iterator as parameter only once"); } }, { name: "ISSUE1896: TypedArray : toLocaleString should use length from internal slot", body: function () { var test = function(taCtor) { var o = new this[taCtor](2); o[1] = 31; Object.defineProperty(o, 'length', {value : 4}); result = o.toLocaleString(); // On OSX and Linux the values are printed as 0 instead 0.00. This is a valid workaround as we have still validated the toLocaleString behavior is correct. if (result == "0,31") { result = "0.00,31.00"; } assert.areEqual("0.00,31.00", result, "TypedArray" + helpers.getTypeOf(o) + ".toLocaleString should use length from internal slot."); return result; }; for (let taCtor of TypedArrayCtors) { test(taCtor); } } }, { name: "TypedArray : Error cases for constructor TypedArray( buffer, byteOffset, length )", body: function () { var sourceArrayBuffer1 = new ArrayBuffer(10); // offset > byteLength function TestOffsetBeyondSourceArrayBufferLength() { new Int16Array(sourceArrayBuffer1, 12); } assert.throws( TestOffsetBeyondSourceArrayBufferLength, RangeError, "TypedArray: Expected the function to throw RangeError as (offset > byteLength).", "Invalid offset/length when creating typed array") // offset % elementSize != 0 function TestIncorrectOffset() { new Int16Array(sourceArrayBuffer1, 7, 1); } assert.throws( TestIncorrectOffset, RangeError, "TypedArray: Expected the function to throw RangeError as (offset % elementSize) != 0.", "Invalid offset/length when creating typed array") // (Length * elementSize + offset) beyond array buffer length. function TestLengthBeyondSourceArrayBufferLength() { new Int16Array(sourceArrayBuffer1, 6, 4); } assert.throws( TestLengthBeyondSourceArrayBufferLength, RangeError, "TypedArray: Expected the function to throw RangeError as ((Length * elementSize + offset)) != byteLength.", "Invalid offset/length when creating typed array") // (byteLength - offset) % elementSize != 0 function TestOffsetPlusElementSizeBeyondSourceArrayBufferLength() { new Int32Array(sourceArrayBuffer1, 4); } assert.throws( TestOffsetPlusElementSizeBeyondSourceArrayBufferLength, RangeError, "TypedArray: Expected the function to throw RangeError as (byteLength - offset) % elementSize != 0.", "Invalid offset/length when creating typed array") } } ]; testRunner.runTests(tests, { verbose: WScript.Arguments[0] != "summary" });
const { Container, Help, commands } = require('../../index.js'); const Commit = require('./commit'); const Fetch = require('./fetch'); const Pull = require('./pull'); const Remote = require('./remote'); const Submodule = require('./submodule'); class Git extends Container {} Git.define({ title: 'git', help: 'the simple content tracker', commands: { '?': 'help', help: Help, commit: Commit, fetch: Fetch, pull: Pull, remote: Remote, submodule: Submodule, version: commands.Version }, logo: true }); module.exports = Git;
/** * @license * Video.js 5.19.2 <http://videojs.com/> * Copyright Brightcove, Inc. <https://www.brightcove.com/> * Available under Apache License Version 2.0 * <https://github.com/videojs/video.js/blob/master/LICENSE> * * Includes vtt.js <https://github.com/mozilla/vtt.js> * Available under Apache License Version 2.0 * <https://github.com/mozilla/vtt.js/blob/master/LICENSE> */ (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.videojs = 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(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _button = _dereq_(2); var _button2 = _interopRequireDefault(_button); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file big-play-button.js */ /** * The initial play button that shows before the video has played. The hiding of the * `BigPlayButton` get done via CSS and `Player` states. * * @extends Button */ var BigPlayButton = function (_Button) { _inherits(BigPlayButton, _Button); function BigPlayButton() { _classCallCheck(this, BigPlayButton); return _possibleConstructorReturn(this, _Button.apply(this, arguments)); } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. Always returns 'vjs-big-play-button'. */ BigPlayButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-big-play-button'; }; /** * This gets called when a `BigPlayButton` "clicked". See {@link ClickableComponent} * for more detailed information on what a click can be. * * @param {EventTarget~Event} event * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ BigPlayButton.prototype.handleClick = function handleClick(event) { this.player_.play(); var cb = this.player_.getChild('controlBar'); var playToggle = cb && cb.getChild('playToggle'); if (!playToggle) { this.player_.focus(); return; } this.setTimeout(function () { playToggle.focus(); }, 1); }; return BigPlayButton; }(_button2['default']); /** * The text that should display over the `BigPlayButton`s controls. Added to for localization. * * @type {string} * @private */ BigPlayButton.prototype.controlText_ = 'Play Video'; _component2['default'].registerComponent('BigPlayButton', BigPlayButton); exports['default'] = BigPlayButton; },{"2":2,"5":5}],2:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _clickableComponent = _dereq_(3); var _clickableComponent2 = _interopRequireDefault(_clickableComponent); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _log = _dereq_(86); var _log2 = _interopRequireDefault(_log); var _obj = _dereq_(88); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file button.js */ /** * Base class for all buttons. * * @extends ClickableComponent */ var Button = function (_ClickableComponent) { _inherits(Button, _ClickableComponent); function Button() { _classCallCheck(this, Button); return _possibleConstructorReturn(this, _ClickableComponent.apply(this, arguments)); } /** * Create the `Button`s DOM element. * * @param {string} [tag=button] * Element's node type. e.g. 'button' * * @param {Object} [props={}] * An object of properties that should be set on the element. * * @param {Object} [attributes={}] * An object of attributes that should be set on the element. * * @return {Element} * The element that gets created. */ Button.prototype.createEl = function createEl() { var tag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'button'; var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var attributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; props = (0, _obj.assign)({ className: this.buildCSSClass() }, props); if (tag !== 'button') { _log2['default'].warn('Creating a Button with an HTML element of ' + tag + ' is deprecated; use ClickableComponent instead.'); // Add properties for clickable element which is not a native HTML button props = (0, _obj.assign)({ tabIndex: 0 }, props); // Add ARIA attributes for clickable element which is not a native HTML button attributes = (0, _obj.assign)({ role: 'button' }, attributes); } // Add attributes for button element attributes = (0, _obj.assign)({ // Necessary since the default button type is "submit" 'type': 'button', // let the screen reader user know that the text of the button may change 'aria-live': 'polite' }, attributes); var el = _component2['default'].prototype.createEl.call(this, tag, props, attributes); this.createControlTextEl(el); return el; }; /** * Add a child `Component` inside of this `Button`. * * @param {string|Component} child * The name or instance of a child to add. * * @param {Object} [options={}] * The key/value store of options that will get passed to children of * the child. * * @return {Component} * The `Component` that gets added as a child. When using a string the * `Component` will get created by this process. * * @deprecated since version 5 */ Button.prototype.addChild = function addChild(child) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var className = this.constructor.name; _log2['default'].warn('Adding an actionable (user controllable) child to a Button (' + className + ') is not supported; use a ClickableComponent instead.'); // Avoid the error message generated by ClickableComponent's addChild method return _component2['default'].prototype.addChild.call(this, child, options); }; /** * Enable the `Button` element so that it can be activated or clicked. Use this with * {@link Button#disable}. */ Button.prototype.enable = function enable() { _ClickableComponent.prototype.enable.call(this); this.el_.removeAttribute('disabled'); }; /** * Enable the `Button` element so that it cannot be activated or clicked. Use this with * {@link Button#enable}. */ Button.prototype.disable = function disable() { _ClickableComponent.prototype.disable.call(this); this.el_.setAttribute('disabled', 'disabled'); }; /** * This gets called when a `Button` has focus and `keydown` is triggered via a key * press. * * @param {EventTarget~Event} event * The event that caused this function to get called. * * @listens keydown */ Button.prototype.handleKeyPress = function handleKeyPress(event) { // Ignore Space (32) or Enter (13) key operation, which is handled by the browser for a button. if (event.which === 32 || event.which === 13) { return; } // Pass keypress handling up for unsupported keys _ClickableComponent.prototype.handleKeyPress.call(this, event); }; return Button; }(_clickableComponent2['default']); _component2['default'].registerComponent('Button', Button); exports['default'] = Button; },{"3":3,"5":5,"86":86,"88":88}],3:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(81); var Dom = _interopRequireWildcard(_dom); var _events = _dereq_(82); var Events = _interopRequireWildcard(_events); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); var _log = _dereq_(86); var _log2 = _interopRequireDefault(_log); var _document = _dereq_(94); var _document2 = _interopRequireDefault(_document); var _obj = _dereq_(88); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file button.js */ /** * Clickable Component which is clickable or keyboard actionable, * but is not a native HTML button. * * @extends Component */ var ClickableComponent = function (_Component) { _inherits(ClickableComponent, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function ClickableComponent(player, options) { _classCallCheck(this, ClickableComponent); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.emitTapEvents(); _this.enable(); return _this; } /** * Create the `Component`s DOM element. * * @param {string} [tag=div] * The element's node type. * * @param {Object} [props={}] * An object of properties that should be set on the element. * * @param {Object} [attributes={}] * An object of attributes that should be set on the element. * * @return {Element} * The element that gets created. */ ClickableComponent.prototype.createEl = function createEl() { var tag = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'div'; var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var attributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; props = (0, _obj.assign)({ className: this.buildCSSClass(), tabIndex: 0 }, props); if (tag === 'button') { _log2['default'].error('Creating a ClickableComponent with an HTML element of ' + tag + ' is not supported; use a Button instead.'); } // Add ARIA attributes for clickable element which is not a native HTML button attributes = (0, _obj.assign)({ 'role': 'button', // let the screen reader user know that the text of the element may change 'aria-live': 'polite' }, attributes); this.tabIndex_ = props.tabIndex; var el = _Component.prototype.createEl.call(this, tag, props, attributes); this.createControlTextEl(el); return el; }; /** * Create a control text element on this `Component` * * @param {Element} [el] * Parent element for the control text. * * @return {Element} * The control text element that gets created. */ ClickableComponent.prototype.createControlTextEl = function createControlTextEl(el) { this.controlTextEl_ = Dom.createEl('span', { className: 'vjs-control-text' }); if (el) { el.appendChild(this.controlTextEl_); } this.controlText(this.controlText_, el); return this.controlTextEl_; }; /** * Get or set the localize text to use for the controls on the `Component`. * * @param {string} [text] * Control text for element. * * @param {Element} [el=this.el()] * Element to set the title on. * * @return {string|ClickableComponent} * - The control text when getting * - Returns itself when setting; method can be chained. */ ClickableComponent.prototype.controlText = function controlText(text) { var el = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.el(); if (!text) { return this.controlText_ || 'Need Text'; } var localizedText = this.localize(text); this.controlText_ = text; this.controlTextEl_.innerHTML = localizedText; if (!this.nonIconControl) { // Set title attribute if only an icon is shown el.setAttribute('title', localizedText); } return this; }; /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ ClickableComponent.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-control vjs-button ' + _Component.prototype.buildCSSClass.call(this); }; /** * Enable this `Component`s element. * * @return {ClickableComponent} * Returns itself; method can be chained. */ ClickableComponent.prototype.enable = function enable() { this.removeClass('vjs-disabled'); this.el_.setAttribute('aria-disabled', 'false'); if (typeof this.tabIndex_ !== 'undefined') { this.el_.setAttribute('tabIndex', this.tabIndex_); } this.on('tap', this.handleClick); this.on('click', this.handleClick); this.on('focus', this.handleFocus); this.on('blur', this.handleBlur); return this; }; /** * Disable this `Component`s element. * * @return {ClickableComponent} * Returns itself; method can be chained. */ ClickableComponent.prototype.disable = function disable() { this.addClass('vjs-disabled'); this.el_.setAttribute('aria-disabled', 'true'); if (typeof this.tabIndex_ !== 'undefined') { this.el_.removeAttribute('tabIndex'); } this.off('tap', this.handleClick); this.off('click', this.handleClick); this.off('focus', this.handleFocus); this.off('blur', this.handleBlur); return this; }; /** * This gets called when a `ClickableComponent` gets: * - Clicked (via the `click` event, listening starts in the constructor) * - Tapped (via the `tap` event, listening starts in the constructor) * - The following things happen in order: * 1. {@link ClickableComponent#handleFocus} is called via a `focus` event on the * `ClickableComponent`. * 2. {@link ClickableComponent#handleFocus} adds a listener for `keydown` on using * {@link ClickableComponent#handleKeyPress}. * 3. `ClickableComponent` has not had a `blur` event (`blur` means that focus was lost). The user presses * the space or enter key. * 4. {@link ClickableComponent#handleKeyPress} calls this function with the `keydown` * event as a parameter. * * @param {EventTarget~Event} event * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click * @abstract */ ClickableComponent.prototype.handleClick = function handleClick(event) {}; /** * This gets called when a `ClickableComponent` gains focus via a `focus` event. * Turns on listening for `keydown` events. When they happen it * calls `this.handleKeyPress`. * * @param {EventTarget~Event} event * The `focus` event that caused this function to be called. * * @listens focus */ ClickableComponent.prototype.handleFocus = function handleFocus(event) { Events.on(_document2['default'], 'keydown', Fn.bind(this, this.handleKeyPress)); }; /** * Called when this ClickableComponent has focus and a key gets pressed down. By * default it will call `this.handleClick` when the key is space or enter. * * @param {EventTarget~Event} event * The `keydown` event that caused this function to be called. * * @listens keydown */ ClickableComponent.prototype.handleKeyPress = function handleKeyPress(event) { // Support Space (32) or Enter (13) key operation to fire a click event if (event.which === 32 || event.which === 13) { event.preventDefault(); this.handleClick(event); } else if (_Component.prototype.handleKeyPress) { // Pass keypress handling up for unsupported keys _Component.prototype.handleKeyPress.call(this, event); } }; /** * Called when a `ClickableComponent` loses focus. Turns off the listener for * `keydown` events. Which Stops `this.handleKeyPress` from getting called. * * @param {EventTarget~Event} event * The `blur` event that caused this function to be called. * * @listens blur */ ClickableComponent.prototype.handleBlur = function handleBlur(event) { Events.off(_document2['default'], 'keydown', Fn.bind(this, this.handleKeyPress)); }; return ClickableComponent; }(_component2['default']); _component2['default'].registerComponent('ClickableComponent', ClickableComponent); exports['default'] = ClickableComponent; },{"5":5,"81":81,"82":82,"83":83,"86":86,"88":88,"94":94}],4:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _button = _dereq_(2); var _button2 = _interopRequireDefault(_button); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file close-button.js */ /** * The `CloseButton` is a `{@link Button}` that fires a `close` event when * it gets clicked. * * @extends Button */ var CloseButton = function (_Button) { _inherits(CloseButton, _Button); /** * Creates an instance of the this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function CloseButton(player, options) { _classCallCheck(this, CloseButton); var _this = _possibleConstructorReturn(this, _Button.call(this, player, options)); _this.controlText(options && options.controlText || _this.localize('Close')); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ CloseButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-close-button ' + _Button.prototype.buildCSSClass.call(this); }; /** * This gets called when a `CloseButton` gets clicked. See * {@link ClickableComponent#handleClick} for more information on when this will be * triggered * * @param {EventTarget~Event} event * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click * @fires CloseButton#close */ CloseButton.prototype.handleClick = function handleClick(event) { /** * Triggered when the a `CloseButton` is clicked. * * @event CloseButton#close * @type {EventTarget~Event} * * @property {boolean} [bubbles=false] * set to false so that the close event does not * bubble up to parents if there is no listener */ this.trigger({ type: 'close', bubbles: false }); }; return CloseButton; }(_button2['default']); _component2['default'].registerComponent('CloseButton', CloseButton); exports['default'] = CloseButton; },{"2":2,"5":5}],5:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _window = _dereq_(95); var _window2 = _interopRequireDefault(_window); var _dom = _dereq_(81); var Dom = _interopRequireWildcard(_dom); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); var _guid = _dereq_(85); var Guid = _interopRequireWildcard(_guid); var _events = _dereq_(82); var Events = _interopRequireWildcard(_events); var _log = _dereq_(86); var _log2 = _interopRequireDefault(_log); var _toTitleCase = _dereq_(91); var _toTitleCase2 = _interopRequireDefault(_toTitleCase); var _mergeOptions = _dereq_(87); var _mergeOptions2 = _interopRequireDefault(_mergeOptions); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Player Component - Base class for all UI objects * * @file component.js */ /** * Base class for all UI Components. * Components are UI objects which represent both a javascript object and an element * in the DOM. They can be children of other components, and can have * children themselves. * * Components can also use methods from {@link EventTarget} */ var Component = function () { /** * A callback that is called when a component is ready. Does not have any * paramters and any callback value will be ignored. * * @callback Component~ReadyCallback * @this Component */ /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. # * @param {Object[]} [options.children] * An array of children objects to intialize this component with. Children objects have * a name property that will be used if more than one component of the same type needs to be * added. * * @param {Component~ReadyCallback} [ready] * Function that gets called when the `Component` is ready. */ function Component(player, options, ready) { _classCallCheck(this, Component); // The component might be the player itself and we can't pass `this` to super if (!player && this.play) { this.player_ = player = this; // eslint-disable-line } else { this.player_ = player; } // Make a copy of prototype.options_ to protect against overriding defaults this.options_ = (0, _mergeOptions2['default'])({}, this.options_); // Updated options with supplied options options = this.options_ = (0, _mergeOptions2['default'])(this.options_, options); // Get ID from options or options element if one is supplied this.id_ = options.id || options.el && options.el.id; // If there was no ID from the options, generate one if (!this.id_) { // Don't require the player ID function in the case of mock players var id = player && player.id && player.id() || 'no_player'; this.id_ = id + '_component_' + Guid.newGUID(); } this.name_ = options.name || null; // Create element if one wasn't provided in options if (options.el) { this.el_ = options.el; } else if (options.createEl !== false) { this.el_ = this.createEl(); } this.children_ = []; this.childIndex_ = {}; this.childNameIndex_ = {}; // Add any child components in options if (options.initChildren !== false) { this.initChildren(); } this.ready(ready); // Don't want to trigger ready here or it will before init is actually // finished for all children that run this constructor if (options.reportTouchActivity !== false) { this.enableTouchActivity(); } } /** * Dispose of the `Component` and all child components. * * @fires Component#dispose */ Component.prototype.dispose = function dispose() { /** * Triggered when a `Component` is disposed. * * @event Component#dispose * @type {EventTarget~Event} * * @property {boolean} [bubbles=false] * set to false so that the close event does not * bubble up */ this.trigger({ type: 'dispose', bubbles: false }); // Dispose all children. if (this.children_) { for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i].dispose) { this.children_[i].dispose(); } } } // Delete child references this.children_ = null; this.childIndex_ = null; this.childNameIndex_ = null; // Remove all event listeners. this.off(); // Remove element from DOM if (this.el_.parentNode) { this.el_.parentNode.removeChild(this.el_); } Dom.removeElData(this.el_); this.el_ = null; }; /** * Return the {@link Player} that the `Component` has attached to. * * @return {Player} * The player that this `Component` has attached to. */ Component.prototype.player = function player() { return this.player_; }; /** * Deep merge of options objects with new options. * > Note: When both `obj` and `options` contain properties whose values are objects. * The two properties get merged using {@link module:mergeOptions} * * @param {Object} obj * The object that contains new options. * * @return {Object} * A new object of `this.options_` and `obj` merged together. * * @deprecated since version 5 */ Component.prototype.options = function options(obj) { _log2['default'].warn('this.options() has been deprecated and will be moved to the constructor in 6.0'); if (!obj) { return this.options_; } this.options_ = (0, _mergeOptions2['default'])(this.options_, obj); return this.options_; }; /** * Get the `Component`s DOM element * * @return {Element} * The DOM element for this `Component`. */ Component.prototype.el = function el() { return this.el_; }; /** * Create the `Component`s DOM element. * * @param {string} [tagName] * Element's DOM node type. e.g. 'div' * * @param {Object} [properties] * An object of properties that should be set. * * @param {Object} [attributes] * An object of attributes that should be set. * * @return {Element} * The element that gets created. */ Component.prototype.createEl = function createEl(tagName, properties, attributes) { return Dom.createEl(tagName, properties, attributes); }; /** * Localize a string given the string in english. * * @param {string} string * The string to localize. * * @return {string} * The localized string or if no localization exists the english string. */ Component.prototype.localize = function localize(string) { var code = this.player_.language && this.player_.language(); var languages = this.player_.languages && this.player_.languages(); if (!code || !languages) { return string; } var language = languages[code]; if (language && language[string]) { return language[string]; } var primaryCode = code.split('-')[0]; var primaryLang = languages[primaryCode]; if (primaryLang && primaryLang[string]) { return primaryLang[string]; } return string; }; /** * Return the `Component`s DOM element. This is where children get inserted. * This will usually be the the same as the element returned in {@link Component#el}. * * @return {Element} * The content element for this `Component`. */ Component.prototype.contentEl = function contentEl() { return this.contentEl_ || this.el_; }; /** * Get this `Component`s ID * * @return {string} * The id of this `Component` */ Component.prototype.id = function id() { return this.id_; }; /** * Get the `Component`s name. The name gets used to reference the `Component` * and is set during registration. * * @return {string} * The name of this `Component`. */ Component.prototype.name = function name() { return this.name_; }; /** * Get an array of all child components * * @return {Array} * The children */ Component.prototype.children = function children() { return this.children_; }; /** * Returns the child `Component` with the given `id`. * * @param {string} id * The id of the child `Component` to get. * * @return {Component|undefined} * The child `Component` with the given `id` or undefined. */ Component.prototype.getChildById = function getChildById(id) { return this.childIndex_[id]; }; /** * Returns the child `Component` with the given `name`. * * @param {string} name * The name of the child `Component` to get. * * @return {Component|undefined} * The child `Component` with the given `name` or undefined. */ Component.prototype.getChild = function getChild(name) { if (!name) { return; } name = (0, _toTitleCase2['default'])(name); return this.childNameIndex_[name]; }; /** * Add a child `Component` inside the current `Component`. * * * @param {string|Component} child * The name or instance of a child to add. * * @param {Object} [options={}] * The key/value store of options that will get passed to children of * the child. * * @param {number} [index=this.children_.length] * The index to attempt to add a child into. * * @return {Component} * The `Component` that gets added as a child. When using a string the * `Component` will get created by this process. */ Component.prototype.addChild = function addChild(child) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var index = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.children_.length; var component = void 0; var componentName = void 0; // If child is a string, create component with options if (typeof child === 'string') { componentName = (0, _toTitleCase2['default'])(child); // Options can also be specified as a boolean, // so convert to an empty object if false. if (!options) { options = {}; } // Same as above, but true is deprecated so show a warning. if (options === true) { _log2['default'].warn('Initializing a child component with `true` is deprecated.' + 'Children should be defined in an array when possible, ' + 'but if necessary use an object instead of `true`.'); options = {}; } var componentClassName = options.componentClass || componentName; // Set name through options options.name = componentName; // Create a new object & element for this controls set // If there's no .player_, this is a player var ComponentClass = Component.getComponent(componentClassName); if (!ComponentClass) { throw new Error('Component ' + componentClassName + ' does not exist'); } // data stored directly on the videojs object may be // misidentified as a component to retain // backwards-compatibility with 4.x. check to make sure the // component class can be instantiated. if (typeof ComponentClass !== 'function') { return null; } component = new ComponentClass(this.player_ || this, options); // child is a component instance } else { component = child; } this.children_.splice(index, 0, component); if (typeof component.id === 'function') { this.childIndex_[component.id()] = component; } // If a name wasn't used to create the component, check if we can use the // name function of the component componentName = componentName || component.name && (0, _toTitleCase2['default'])(component.name()); if (componentName) { this.childNameIndex_[componentName] = component; } // Add the UI object's element to the container div (box) // Having an element is not required if (typeof component.el === 'function' && component.el()) { var childNodes = this.contentEl().children; var refNode = childNodes[index] || null; this.contentEl().insertBefore(component.el(), refNode); } // Return so it can stored on parent object if desired. return component; }; /** * Remove a child `Component` from this `Component`s list of children. Also removes * the child `Component`s element from this `Component`s element. * * @param {Component} component * The child `Component` to remove. */ Component.prototype.removeChild = function removeChild(component) { if (typeof component === 'string') { component = this.getChild(component); } if (!component || !this.children_) { return; } var childFound = false; for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i] === component) { childFound = true; this.children_.splice(i, 1); break; } } if (!childFound) { return; } this.childIndex_[component.id()] = null; this.childNameIndex_[component.name()] = null; var compEl = component.el(); if (compEl && compEl.parentNode === this.contentEl()) { this.contentEl().removeChild(component.el()); } }; /** * Add and initialize default child `Component`s based upon options. */ Component.prototype.initChildren = function initChildren() { var _this = this; var children = this.options_.children; if (children) { // `this` is `parent` var parentOptions = this.options_; var handleAdd = function handleAdd(child) { var name = child.name; var opts = child.opts; // Allow options for children to be set at the parent options // e.g. videojs(id, { controlBar: false }); // instead of videojs(id, { children: { controlBar: false }); if (parentOptions[name] !== undefined) { opts = parentOptions[name]; } // Allow for disabling default components // e.g. options['children']['posterImage'] = false if (opts === false) { return; } // Allow options to be passed as a simple boolean if no configuration // is necessary. if (opts === true) { opts = {}; } // We also want to pass the original player options // to each component as well so they don't need to // reach back into the player for options later. opts.playerOptions = _this.options_.playerOptions; // Create and add the child component. // Add a direct reference to the child by name on the parent instance. // If two of the same component are used, different names should be supplied // for each var newChild = _this.addChild(name, opts); if (newChild) { _this[name] = newChild; } }; // Allow for an array of children details to passed in the options var workingChildren = void 0; var Tech = Component.getComponent('Tech'); if (Array.isArray(children)) { workingChildren = children; } else { workingChildren = Object.keys(children); } workingChildren // children that are in this.options_ but also in workingChildren would // give us extra children we do not want. So, we want to filter them out. .concat(Object.keys(this.options_).filter(function (child) { return !workingChildren.some(function (wchild) { if (typeof wchild === 'string') { return child === wchild; } return child === wchild.name; }); })).map(function (child) { var name = void 0; var opts = void 0; if (typeof child === 'string') { name = child; opts = children[name] || _this.options_[name] || {}; } else { name = child.name; opts = child; } return { name: name, opts: opts }; }).filter(function (child) { // we have to make sure that child.name isn't in the techOrder since // techs are registerd as Components but can't aren't compatible // See https://github.com/videojs/video.js/issues/2772 var c = Component.getComponent(child.opts.componentClass || (0, _toTitleCase2['default'])(child.name)); return c && !Tech.isTech(c); }).forEach(handleAdd); } }; /** * Builds the default DOM class name. Should be overriden by sub-components. * * @return {string} * The DOM class name for this object. * * @abstract */ Component.prototype.buildCSSClass = function buildCSSClass() { // Child classes can include a function that does: // return 'CLASS NAME' + this._super(); return ''; }; /** * Add an `event listener` to this `Component`s element. * * The benefit of using this over the following: * - `VjsEvents.on(otherElement, 'eventName', myFunc)` * - `otherComponent.on('eventName', myFunc)` * * 1. Is that the listeners will get cleaned up when either component gets disposed. * 1. It will also bind `myComponent` as the context of `myFunc`. * > NOTE: If you remove the element from the DOM that has used `on` you need to * clean up references using: `myComponent.trigger(el, 'dispose')` * This will also allow the browser to garbage collect it. In special * cases such as with `window` and `document`, which are both permanent, * this is not necessary. * * @param {string|Component|string[]} [first] * The event name, and array of event names, or another `Component`. * * @param {EventTarget~EventListener|string|string[]} [second] * The listener function, an event name, or an Array of events names. * * @param {EventTarget~EventListener} [third] * The event handler if `first` is a `Component` and `second` is an event name * or an Array of event names. * * @return {Component} * Returns itself; method can be chained. * * @listens Component#dispose */ Component.prototype.on = function on(first, second, third) { var _this2 = this; if (typeof first === 'string' || Array.isArray(first)) { Events.on(this.el_, first, Fn.bind(this, second)); // Targeting another component or element } else { var target = first; var type = second; var fn = Fn.bind(this, third); // When this component is disposed, remove the listener from the other component var removeOnDispose = function removeOnDispose() { return _this2.off(target, type, fn); }; // Use the same function ID so we can remove it later it using the ID // of the original listener removeOnDispose.guid = fn.guid; this.on('dispose', removeOnDispose); // If the other component is disposed first we need to clean the reference // to the other component in this component's removeOnDispose listener // Otherwise we create a memory leak. var cleanRemover = function cleanRemover() { return _this2.off('dispose', removeOnDispose); }; // Add the same function ID so we can easily remove it later cleanRemover.guid = fn.guid; // Check if this is a DOM node if (first.nodeName) { // Add the listener to the other element Events.on(target, type, fn); Events.on(target, 'dispose', cleanRemover); // Should be a component // Not using `instanceof Component` because it makes mock players difficult } else if (typeof first.on === 'function') { // Add the listener to the other component target.on(type, fn); target.on('dispose', cleanRemover); } } return this; }; /** * Remove an event listener from this `Component`s element. If the second argument is * exluded all listeners for the type passed in as the first argument will be removed. * * @param {string|Component|string[]} [first] * The event name, and array of event names, or another `Component`. * * @param {EventTarget~EventListener|string|string[]} [second] * The listener function, an event name, or an Array of events names. * * @param {EventTarget~EventListener} [third] * The event handler if `first` is a `Component` and `second` is an event name * or an Array of event names. * * @return {Component} * Returns itself; method can be chained. */ Component.prototype.off = function off(first, second, third) { if (!first || typeof first === 'string' || Array.isArray(first)) { Events.off(this.el_, first, second); } else { var target = first; var type = second; // Ensure there's at least a guid, even if the function hasn't been used var fn = Fn.bind(this, third); // Remove the dispose listener on this component, // which was given the same guid as the event listener this.off('dispose', fn); if (first.nodeName) { // Remove the listener Events.off(target, type, fn); // Remove the listener for cleaning the dispose listener Events.off(target, 'dispose', fn); } else { target.off(type, fn); target.off('dispose', fn); } } return this; }; /** * Add an event listener that gets triggered only once and then gets removed. * * @param {string|Component|string[]} [first] * The event name, and array of event names, or another `Component`. * * @param {EventTarget~EventListener|string|string[]} [second] * The listener function, an event name, or an Array of events names. * * @param {EventTarget~EventListener} [third] * The event handler if `first` is a `Component` and `second` is an event name * or an Array of event names. * * @return {Component} * Returns itself; method can be chained. */ Component.prototype.one = function one(first, second, third) { var _this3 = this, _arguments = arguments; if (typeof first === 'string' || Array.isArray(first)) { Events.one(this.el_, first, Fn.bind(this, second)); } else { var target = first; var type = second; var fn = Fn.bind(this, third); var newFunc = function newFunc() { _this3.off(target, type, newFunc); fn.apply(null, _arguments); }; // Keep the same function ID so we can remove it later newFunc.guid = fn.guid; this.on(target, type, newFunc); } return this; }; /** * Trigger an event on an element. * * @param {EventTarget~Event|Object|string} event * The event name, and Event, or an event-like object with a type attribute * set to the event name. * * @param {Object} [hash] * Data hash to pass along with the event * * @return {Component} * Returns itself; method can be chained. */ Component.prototype.trigger = function trigger(event, hash) { Events.trigger(this.el_, event, hash); return this; }; /** * Bind a listener to the component's ready state. If the ready event has already * happened it will trigger the function immediately. * * @param {Component~ReadyCallback} fn * A function to call when ready is triggered. * * @param {boolean} [sync=false] * Execute the listener synchronously if `Component` is ready. * * @return {Component} * Returns itself; method can be chained. */ Component.prototype.ready = function ready(fn) { var sync = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (fn) { if (this.isReady_) { if (sync) { fn.call(this); } else { // Call the function asynchronously by default for consistency this.setTimeout(fn, 1); } } else { this.readyQueue_ = this.readyQueue_ || []; this.readyQueue_.push(fn); } } return this; }; /** * Trigger all the ready listeners for this `Component`. * * @fires Component#ready */ Component.prototype.triggerReady = function triggerReady() { this.isReady_ = true; // Ensure ready is triggerd asynchronously this.setTimeout(function () { var readyQueue = this.readyQueue_; // Reset Ready Queue this.readyQueue_ = []; if (readyQueue && readyQueue.length > 0) { readyQueue.forEach(function (fn) { fn.call(this); }, this); } // Allow for using event listeners also /** * Triggered when a `Component` is ready. * * @event Component#ready * @type {EventTarget~Event} */ this.trigger('ready'); }, 1); }; /** * Find a single DOM element matching a `selector`. This can be within the `Component`s * `contentEl()` or another custom context. * * @param {string} selector * A valid CSS selector, which will be passed to `querySelector`. * * @param {Element|string} [context=this.contentEl()] * A DOM element within which to query. Can also be a selector string in * which case the first matching element will get used as context. If * missing `this.contentEl()` gets used. If `this.contentEl()` returns * nothing it falls back to `document`. * * @return {Element|null} * the dom element that was found, or null * * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors) */ Component.prototype.$ = function $(selector, context) { return Dom.$(selector, context || this.contentEl()); }; /** * Finds all DOM element matching a `selector`. This can be within the `Component`s * `contentEl()` or another custom context. * * @param {string} selector * A valid CSS selector, which will be passed to `querySelectorAll`. * * @param {Element|string} [context=this.contentEl()] * A DOM element within which to query. Can also be a selector string in * which case the first matching element will get used as context. If * missing `this.contentEl()` gets used. If `this.contentEl()` returns * nothing it falls back to `document`. * * @return {NodeList} * a list of dom elements that were found * * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors) */ Component.prototype.$$ = function $$(selector, context) { return Dom.$$(selector, context || this.contentEl()); }; /** * Check if a component's element has a CSS class name. * * @param {string} classToCheck * CSS class name to check. * * @return {boolean} * - True if the `Component` has the class. * - False if the `Component` does not have the class` */ Component.prototype.hasClass = function hasClass(classToCheck) { return Dom.hasElClass(this.el_, classToCheck); }; /** * Add a CSS class name to the `Component`s element. * * @param {string} classToAdd * CSS class name to add * * @return {Component} * Returns itself; method can be chained. */ Component.prototype.addClass = function addClass(classToAdd) { Dom.addElClass(this.el_, classToAdd); return this; }; /** * Remove a CSS class name from the `Component`s element. * * @param {string} classToRemove * CSS class name to remove * * @return {Component} * Returns itself; method can be chained. */ Component.prototype.removeClass = function removeClass(classToRemove) { Dom.removeElClass(this.el_, classToRemove); return this; }; /** * Add or remove a CSS class name from the component's element. * - `classToToggle` gets added when {@link Component#hasClass} would return false. * - `classToToggle` gets removed when {@link Component#hasClass} would return true. * * @param {string} classToToggle * The class to add or remove based on (@link Component#hasClass} * * @param {boolean|Dom~predicate} [predicate] * An {@link Dom~predicate} function or a boolean * * @return {Component} * Returns itself; method can be chained. */ Component.prototype.toggleClass = function toggleClass(classToToggle, predicate) { Dom.toggleElClass(this.el_, classToToggle, predicate); return this; }; /** * Show the `Component`s element if it is hidden by removing the * 'vjs-hidden' class name from it. * * @return {Component} * Returns itself; method can be chained. */ Component.prototype.show = function show() { this.removeClass('vjs-hidden'); return this; }; /** * Hide the `Component`s element if it is currently showing by adding the * 'vjs-hidden` class name to it. * * @return {Component} * Returns itself; method can be chained. */ Component.prototype.hide = function hide() { this.addClass('vjs-hidden'); return this; }; /** * Lock a `Component`s element in its visible state by adding the 'vjs-lock-showing' * class name to it. Used during fadeIn/fadeOut. * * @return {Component} * Returns itself; method can be chained. * * @private */ Component.prototype.lockShowing = function lockShowing() { this.addClass('vjs-lock-showing'); return this; }; /** * Unlock a `Component`s element from its visible state by removing the 'vjs-lock-showing' * class name from it. Used during fadeIn/fadeOut. * * @return {Component} * Returns itself; method can be chained. * * @private */ Component.prototype.unlockShowing = function unlockShowing() { this.removeClass('vjs-lock-showing'); return this; }; /** * Get the value of an attribute on the `Component`s element. * * @param {string} attribute * Name of the attribute to get the value from. * * @return {string|null} * - The value of the attribute that was asked for. * - Can be an empty string on some browsers if the attribute does not exist * or has no value * - Most browsers will return null if the attibute does not exist or has * no value. * * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute} */ Component.prototype.getAttribute = function getAttribute(attribute) { return Dom.getAttribute(this.el_, attribute); }; /** * Set the value of an attribute on the `Component`'s element * * @param {string} attribute * Name of the attribute to set. * * @param {string} value * Value to set the attribute to. * * @return {Component} * Returns itself; method can be chained. * * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute} */ Component.prototype.setAttribute = function setAttribute(attribute, value) { Dom.setAttribute(this.el_, attribute, value); return this; }; /** * Remove an attribute from the `Component`s element. * * @param {string} attribute * Name of the attribute to remove. * * @return {Component} * Returns itself; method can be chained. * * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute} */ Component.prototype.removeAttribute = function removeAttribute(attribute) { Dom.removeAttribute(this.el_, attribute); return this; }; /** * Get or set the width of the component based upon the CSS styles. * See {@link Component#dimension} for more detailed information. * * @param {number|string} [num] * The width that you want to set postfixed with '%', 'px' or nothing. * * @param {boolean} [skipListeners] * Skip the resize event trigger * * @return {Component|number|string} * - The width when getting, zero if there is no width. Can be a string * postpixed with '%' or 'px'. * - Returns itself when setting; method can be chained. */ Component.prototype.width = function width(num, skipListeners) { return this.dimension('width', num, skipListeners); }; /** * Get or set the height of the component based upon the CSS styles. * See {@link Component#dimension} for more detailed information. * * @param {number|string} [num] * The height that you want to set postfixed with '%', 'px' or nothing. * * @param {boolean} [skipListeners] * Skip the resize event trigger * * @return {Component|number|string} * - The width when getting, zero if there is no width. Can be a string * postpixed with '%' or 'px'. * - Returns itself when setting; method can be chained. */ Component.prototype.height = function height(num, skipListeners) { return this.dimension('height', num, skipListeners); }; /** * Set both the width and height of the `Component` element at the same time. * * @param {number|string} width * Width to set the `Component`s element to. * * @param {number|string} height * Height to set the `Component`s element to. * * @return {Component} * Returns itself; method can be chained. */ Component.prototype.dimensions = function dimensions(width, height) { // Skip resize listeners on width for optimization return this.width(width, true).height(height); }; /** * Get or set width or height of the `Component` element. This is the shared code * for the {@link Component#width} and {@link Component#height}. * * Things to know: * - If the width or height in an number this will return the number postfixed with 'px'. * - If the width/height is a percent this will return the percent postfixed with '%' * - Hidden elements have a width of 0 with `window.getComputedStyle`. This function * defaults to the `Component`s `style.width` and falls back to `window.getComputedStyle`. * See [this]{@link http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/} * for more information * - If you want the computed style of the component, use {@link Component#currentWidth} * and {@link {Component#currentHeight} * * @fires Component#resize * * @param {string} widthOrHeight 8 'width' or 'height' * * @param {number|string} [num] 8 New dimension * * @param {boolean} [skipListeners] * Skip resize event trigger * * @return {Component} * - the dimension when getting or 0 if unset * - Returns itself when setting; method can be chained. */ Component.prototype.dimension = function dimension(widthOrHeight, num, skipListeners) { if (num !== undefined) { // Set to zero if null or literally NaN (NaN !== NaN) if (num === null || num !== num) { num = 0; } // Check if using css width/height (% or px) and adjust if (('' + num).indexOf('%') !== -1 || ('' + num).indexOf('px') !== -1) { this.el_.style[widthOrHeight] = num; } else if (num === 'auto') { this.el_.style[widthOrHeight] = ''; } else { this.el_.style[widthOrHeight] = num + 'px'; } // skipListeners allows us to avoid triggering the resize event when setting both width and height if (!skipListeners) { /** * Triggered when a component is resized. * * @event Component#resize * @type {EventTarget~Event} */ this.trigger('resize'); } // Return component return this; } // Not setting a value, so getting it // Make sure element exists if (!this.el_) { return 0; } // Get dimension value from style var val = this.el_.style[widthOrHeight]; var pxIndex = val.indexOf('px'); if (pxIndex !== -1) { // Return the pixel value with no 'px' return parseInt(val.slice(0, pxIndex), 10); } // No px so using % or no style was set, so falling back to offsetWidth/height // If component has display:none, offset will return 0 // TODO: handle display:none and no dimension style using px return parseInt(this.el_['offset' + (0, _toTitleCase2['default'])(widthOrHeight)], 10); }; /** * Get the width or the height of the `Component` elements computed style. Uses * `window.getComputedStyle`. * * @param {string} widthOrHeight * A string containing 'width' or 'height'. Whichever one you want to get. * * @return {number} * The dimension that gets asked for or 0 if nothing was set * for that dimension. */ Component.prototype.currentDimension = function currentDimension(widthOrHeight) { var computedWidthOrHeight = 0; if (widthOrHeight !== 'width' && widthOrHeight !== 'height') { throw new Error('currentDimension only accepts width or height value'); } if (typeof _window2['default'].getComputedStyle === 'function') { var computedStyle = _window2['default'].getComputedStyle(this.el_); computedWidthOrHeight = computedStyle.getPropertyValue(widthOrHeight) || computedStyle[widthOrHeight]; } // remove 'px' from variable and parse as integer computedWidthOrHeight = parseFloat(computedWidthOrHeight); // if the computed value is still 0, it's possible that the browser is lying // and we want to check the offset values. // This code also runs on IE8 and wherever getComputedStyle doesn't exist. if (computedWidthOrHeight === 0) { var rule = 'offset' + (0, _toTitleCase2['default'])(widthOrHeight); computedWidthOrHeight = this.el_[rule]; } return computedWidthOrHeight; }; /** * An object that contains width and height values of the `Component`s * computed style. Uses `window.getComputedStyle`. * * @typedef {Object} Component~DimensionObject * * @property {number} width * The width of the `Component`s computed style. * * @property {number} height * The height of the `Component`s computed style. */ /** * Get an object that contains width and height values of the `Component`s * computed style. * * @return {Component~DimensionObject} * The dimensions of the components element */ Component.prototype.currentDimensions = function currentDimensions() { return { width: this.currentDimension('width'), height: this.currentDimension('height') }; }; /** * Get the width of the `Component`s computed style. Uses `window.getComputedStyle`. * * @return {number} width * The width of the `Component`s computed style. */ Component.prototype.currentWidth = function currentWidth() { return this.currentDimension('width'); }; /** * Get the height of the `Component`s computed style. Uses `window.getComputedStyle`. * * @return {number} height * The height of the `Component`s computed style. */ Component.prototype.currentHeight = function currentHeight() { return this.currentDimension('height'); }; /** * Set the focus to this component */ Component.prototype.focus = function focus() { this.el_.focus(); }; /** * Remove the focus from this component */ Component.prototype.blur = function blur() { this.el_.blur(); }; /** * Emit a 'tap' events when touch event support gets detected. This gets used to * support toggling the controls through a tap on the video. They get enabled * because every sub-component would have extra overhead otherwise. * * @private * @fires Component#tap * @listens Component#touchstart * @listens Component#touchmove * @listens Component#touchleave * @listens Component#touchcancel * @listens Component#touchend */ Component.prototype.emitTapEvents = function emitTapEvents() { // Track the start time so we can determine how long the touch lasted var touchStart = 0; var firstTouch = null; // Maximum movement allowed during a touch event to still be considered a tap // Other popular libs use anywhere from 2 (hammer.js) to 15, // so 10 seems like a nice, round number. var tapMovementThreshold = 10; // The maximum length a touch can be while still being considered a tap var touchTimeThreshold = 200; var couldBeTap = void 0; this.on('touchstart', function (event) { // If more than one finger, don't consider treating this as a click if (event.touches.length === 1) { // Copy pageX/pageY from the object firstTouch = { pageX: event.touches[0].pageX, pageY: event.touches[0].pageY }; // Record start time so we can detect a tap vs. "touch and hold" touchStart = new Date().getTime(); // Reset couldBeTap tracking couldBeTap = true; } }); this.on('touchmove', function (event) { // If more than one finger, don't consider treating this as a click if (event.touches.length > 1) { couldBeTap = false; } else if (firstTouch) { // Some devices will throw touchmoves for all but the slightest of taps. // So, if we moved only a small distance, this could still be a tap var xdiff = event.touches[0].pageX - firstTouch.pageX; var ydiff = event.touches[0].pageY - firstTouch.pageY; var touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff); if (touchDistance > tapMovementThreshold) { couldBeTap = false; } } }); var noTap = function noTap() { couldBeTap = false; }; // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s this.on('touchleave', noTap); this.on('touchcancel', noTap); // When the touch ends, measure how long it took and trigger the appropriate // event this.on('touchend', function (event) { firstTouch = null; // Proceed only if the touchmove/leave/cancel event didn't happen if (couldBeTap === true) { // Measure how long the touch lasted var touchTime = new Date().getTime() - touchStart; // Make sure the touch was less than the threshold to be considered a tap if (touchTime < touchTimeThreshold) { // Don't let browser turn this into a click event.preventDefault(); /** * Triggered when a `Component` is tapped. * * @event Component#tap * @type {EventTarget~Event} */ this.trigger('tap'); // It may be good to copy the touchend event object and change the // type to tap, if the other event properties aren't exact after // Events.fixEvent runs (e.g. event.target) } } }); }; /** * This function reports user activity whenever touch events happen. This can get * turned off by any sub-components that wants touch events to act another way. * * Report user touch activity when touch events occur. User activity gets used to * determine when controls should show/hide. It is simple when it comes to mouse * events, because any mouse event should show the controls. So we capture mouse * events that bubble up to the player and report activity when that happens. * With touch events it isn't as easy as `touchstart` and `touchend` toggle player * controls. So touch events can't help us at the player level either. * * User activity gets checked asynchronously. So what could happen is a tap event * on the video turns the controls off. Then the `touchend` event bubbles up to * the player. Which, if it reported user activity, would turn the controls right * back on. We also don't want to completely block touch events from bubbling up. * Furthermore a `touchmove` event and anything other than a tap, should not turn * controls back on. * * @listens Component#touchstart * @listens Component#touchmove * @listens Component#touchend * @listens Component#touchcancel */ Component.prototype.enableTouchActivity = function enableTouchActivity() { // Don't continue if the root player doesn't support reporting user activity if (!this.player() || !this.player().reportUserActivity) { return; } // listener for reporting that the user is active var report = Fn.bind(this.player(), this.player().reportUserActivity); var touchHolding = void 0; this.on('touchstart', function () { report(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(touchHolding); // report at the same interval as activityCheck touchHolding = this.setInterval(report, 250); }); var touchEnd = function touchEnd(event) { report(); // stop the interval that maintains activity if the touch is holding this.clearInterval(touchHolding); }; this.on('touchmove', report); this.on('touchend', touchEnd); this.on('touchcancel', touchEnd); }; /** * A callback that has no parameters and is bound into `Component`s context. * * @callback Component~GenericCallback * @this Component */ /** * Creates a function that runs after an `x` millisecond timeout. This function is a * wrapper around `window.setTimeout`. There are a few reasons to use this one * instead though: * 1. It gets cleared via {@link Component#clearTimeout} when * {@link Component#dispose} gets called. * 2. The function callback will gets turned into a {@link Component~GenericCallback} * * > Note: You can use `window.clearTimeout` on the id returned by this function. This * will cause its dispose listener not to get cleaned up! Please use * {@link Component#clearTimeout} or {@link Component#dispose}. * * @param {Component~GenericCallback} fn * The function that will be run after `timeout`. * * @param {number} timeout * Timeout in milliseconds to delay before executing the specified function. * * @return {number} * Returns a timeout ID that gets used to identify the timeout. It can also * get used in {@link Component#clearTimeout} to clear the timeout that * was set. * * @listens Component#dispose * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout} */ Component.prototype.setTimeout = function setTimeout(fn, timeout) { fn = Fn.bind(this, fn); var timeoutId = _window2['default'].setTimeout(fn, timeout); var disposeFn = function disposeFn() { this.clearTimeout(timeoutId); }; disposeFn.guid = 'vjs-timeout-' + timeoutId; this.on('dispose', disposeFn); return timeoutId; }; /** * Clears a timeout that gets created via `window.setTimeout` or * {@link Component#setTimeout}. If you set a timeout via {@link Component#setTimeout} * use this function instead of `window.clearTimout`. If you don't your dispose * listener will not get cleaned up until {@link Component#dispose}! * * @param {number} timeoutId * The id of the timeout to clear. The return value of * {@link Component#setTimeout} or `window.setTimeout`. * * @return {number} * Returns the timeout id that was cleared. * * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearTimeout} */ Component.prototype.clearTimeout = function clearTimeout(timeoutId) { _window2['default'].clearTimeout(timeoutId); var disposeFn = function disposeFn() {}; disposeFn.guid = 'vjs-timeout-' + timeoutId; this.off('dispose', disposeFn); return timeoutId; }; /** * Creates a function that gets run every `x` milliseconds. This function is a wrapper * around `window.setInterval`. There are a few reasons to use this one instead though. * 1. It gets cleared via {@link Component#clearInterval} when * {@link Component#dispose} gets called. * 2. The function callback will be a {@link Component~GenericCallback} * * @param {Component~GenericCallback} fn * The function to run every `x` seconds. * * @param {number} interval * Execute the specified function every `x` milliseconds. * * @return {number} * Returns an id that can be used to identify the interval. It can also be be used in * {@link Component#clearInterval} to clear the interval. * * @listens Component#dispose * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval} */ Component.prototype.setInterval = function setInterval(fn, interval) { fn = Fn.bind(this, fn); var intervalId = _window2['default'].setInterval(fn, interval); var disposeFn = function disposeFn() { this.clearInterval(intervalId); }; disposeFn.guid = 'vjs-interval-' + intervalId; this.on('dispose', disposeFn); return intervalId; }; /** * Clears an interval that gets created via `window.setInterval` or * {@link Component#setInterval}. If you set an inteval via {@link Component#setInterval} * use this function instead of `window.clearInterval`. If you don't your dispose * listener will not get cleaned up until {@link Component#dispose}! * * @param {number} intervalId * The id of the interval to clear. The return value of * {@link Component#setInterval} or `window.setInterval`. * * @return {number} * Returns the interval id that was cleared. * * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval} */ Component.prototype.clearInterval = function clearInterval(intervalId) { _window2['default'].clearInterval(intervalId); var disposeFn = function disposeFn() {}; disposeFn.guid = 'vjs-interval-' + intervalId; this.off('dispose', disposeFn); return intervalId; }; /** * Register a `Component` with `videojs` given the name and the component. * * > NOTE: {@link Tech}s should not be registered as a `Component`. {@link Tech}s * should be registered using {@link Tech.registerTech} or * {@link videojs:videojs.registerTech}. * * > NOTE: This function can also be seen on videojs as * {@link videojs:videojs.registerComponent}. * * @param {string} name * The name of the `Component` to register. * * @param {Component} comp * The `Component` class to register. * * @return {Component} * The `Component` that was registered. */ Component.registerComponent = function registerComponent(name, comp) { if (!name) { return; } name = (0, _toTitleCase2['default'])(name); if (!Component.components_) { Component.components_ = {}; } if (name === 'Player' && Component.components_[name]) { var Player = Component.components_[name]; // If we have players that were disposed, then their name will still be // in Players.players. So, we must loop through and verify that the value // for each item is not null. This allows registration of the Player component // after all players have been disposed or before any were created. if (Player.players && Object.keys(Player.players).length > 0 && Object.keys(Player.players).map(function (playerName) { return Player.players[playerName]; }).every(Boolean)) { throw new Error('Can not register Player component after player has been created'); } } Component.components_[name] = comp; return comp; }; /** * Get a `Component` based on the name it was registered with. * * @param {string} name * The Name of the component to get. * * @return {Component} * The `Component` that got registered under the given name. * * @deprecated In `videojs` 6 this will not return `Component`s that were not * registered using {@link Component.registerComponent}. Currently we * check the global `videojs` object for a `Component` name and * return that if it exists. */ Component.getComponent = function getComponent(name) { if (!name) { return; } name = (0, _toTitleCase2['default'])(name); if (Component.components_ && Component.components_[name]) { return Component.components_[name]; } if (_window2['default'] && _window2['default'].videojs && _window2['default'].videojs[name]) { _log2['default'].warn('The ' + name + ' component was added to the videojs object when it should be registered using videojs.registerComponent(name, component)'); return _window2['default'].videojs[name]; } }; /** * Sets up the constructor using the supplied init method or uses the init of the * parent object. * * @param {Object} [props={}] * An object of properties. * * @return {Object} * the extended object. * * @deprecated since version 5 */ Component.extend = function extend(props) { props = props || {}; _log2['default'].warn('Component.extend({}) has been deprecated, ' + ' use videojs.extend(Component, {}) instead'); // Set up the constructor using the supplied init method // or using the init of the parent object // Make sure to check the unobfuscated version for external libs var init = props.init || props.init || this.prototype.init || this.prototype.init || function () {}; // In Resig's simple class inheritance (previously used) the constructor // is a function that calls `this.init.apply(arguments)` // However that would prevent us from using `ParentObject.call(this);` // in a Child constructor because the `this` in `this.init` // would still refer to the Child and cause an infinite loop. // We would instead have to do // `ParentObject.prototype.init.apply(this, arguments);` // Bleh. We're not creating a _super() function, so it's good to keep // the parent constructor reference simple. var subObj = function subObj() { init.apply(this, arguments); }; // Inherit from this object's prototype subObj.prototype = Object.create(this.prototype); // Reset the constructor property for subObj otherwise // instances of subObj would have the constructor of the parent Object subObj.prototype.constructor = subObj; // Make the class extendable subObj.extend = Component.extend; // Extend subObj's prototype with functions and other properties from props for (var name in props) { if (props.hasOwnProperty(name)) { subObj.prototype[name] = props[name]; } } return subObj; }; return Component; }(); Component.registerComponent('Component', Component); exports['default'] = Component; },{"81":81,"82":82,"83":83,"85":85,"86":86,"87":87,"91":91,"95":95}],6:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _trackButton = _dereq_(36); var _trackButton2 = _interopRequireDefault(_trackButton); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _audioTrackMenuItem = _dereq_(7); var _audioTrackMenuItem2 = _interopRequireDefault(_audioTrackMenuItem); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file audio-track-button.js */ /** * The base class for buttons that toggle specific {@link AudioTrack} types. * * @extends TrackButton */ var AudioTrackButton = function (_TrackButton) { _inherits(AudioTrackButton, _TrackButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options={}] * The key/value store of player options. */ function AudioTrackButton(player) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; _classCallCheck(this, AudioTrackButton); options.tracks = player.audioTracks && player.audioTracks(); var _this = _possibleConstructorReturn(this, _TrackButton.call(this, player, options)); _this.el_.setAttribute('aria-label', 'Audio Menu'); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ AudioTrackButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-audio-button ' + _TrackButton.prototype.buildCSSClass.call(this); }; /** * Create a menu item for each audio track * * @param {AudioTrackMenuItem[]} [items=[]] * An array of existing menu items to use. * * @return {AudioTrackMenuItem[]} * An array of menu items */ AudioTrackButton.prototype.createItems = function createItems() { var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; // if there's only one audio track, there no point in showing it this.hideThreshold_ = 1; var tracks = this.player_.audioTracks && this.player_.audioTracks(); if (!tracks) { return items; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; items.push(new _audioTrackMenuItem2['default'](this.player_, { track: track, // MenuItem is selectable selectable: true })); } return items; }; return AudioTrackButton; }(_trackButton2['default']); /** * The text that should display over the `AudioTrackButton`s controls. Added for localization. * * @type {string} * @private */ AudioTrackButton.prototype.controlText_ = 'Audio Track'; _component2['default'].registerComponent('AudioTrackButton', AudioTrackButton); exports['default'] = AudioTrackButton; },{"36":36,"5":5,"7":7}],7:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _menuItem = _dereq_(48); var _menuItem2 = _interopRequireDefault(_menuItem); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file audio-track-menu-item.js */ /** * An {@link AudioTrack} {@link MenuItem} * * @extends MenuItem */ var AudioTrackMenuItem = function (_MenuItem) { _inherits(AudioTrackMenuItem, _MenuItem); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function AudioTrackMenuItem(player, options) { _classCallCheck(this, AudioTrackMenuItem); var track = options.track; var tracks = player.audioTracks(); // Modify options for parent MenuItem class's init. options.label = track.label || track.language || 'Unknown'; options.selected = track.enabled; var _this = _possibleConstructorReturn(this, _MenuItem.call(this, player, options)); _this.track = track; if (tracks) { var changeHandler = Fn.bind(_this, _this.handleTracksChange); tracks.addEventListener('change', changeHandler); _this.on('dispose', function () { tracks.removeEventListener('change', changeHandler); }); } return _this; } /** * This gets called when an `AudioTrackMenuItem is "clicked". See {@link ClickableComponent} * for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ AudioTrackMenuItem.prototype.handleClick = function handleClick(event) { var tracks = this.player_.audioTracks(); _MenuItem.prototype.handleClick.call(this, event); if (!tracks) { return; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; track.enabled = track === this.track; } }; /** * Handle any {@link AudioTrack} change. * * @param {EventTarget~Event} [event] * The {@link AudioTrackList#change} event that caused this to run. * * @listens AudioTrackList#change */ AudioTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) { this.selected(this.track.enabled); }; return AudioTrackMenuItem; }(_menuItem2['default']); _component2['default'].registerComponent('AudioTrackMenuItem', AudioTrackMenuItem); exports['default'] = AudioTrackMenuItem; },{"48":48,"5":5,"83":83}],8:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); _dereq_(12); _dereq_(32); _dereq_(33); _dereq_(35); _dereq_(34); _dereq_(10); _dereq_(18); _dereq_(9); _dereq_(38); _dereq_(40); _dereq_(11); _dereq_(25); _dereq_(27); _dereq_(29); _dereq_(24); _dereq_(6); _dereq_(13); _dereq_(21); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file control-bar.js */ // Required children /** * Container of main controls. * * @extends Component */ var ControlBar = function (_Component) { _inherits(ControlBar, _Component); function ControlBar() { _classCallCheck(this, ControlBar); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ ControlBar.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-control-bar', dir: 'ltr' }, { // The control bar is a group, so it can contain menuitems role: 'group' }); }; return ControlBar; }(_component2['default']); /** * Default options for `ControlBar` * * @type {Object} * @private */ ControlBar.prototype.options_ = { children: ['playToggle', 'volumeMenuButton', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'chaptersButton', 'descriptionsButton', 'subtitlesButton', 'captionsButton', 'audioTrackButton', 'fullscreenToggle'] }; _component2['default'].registerComponent('ControlBar', ControlBar); exports['default'] = ControlBar; },{"10":10,"11":11,"12":12,"13":13,"18":18,"21":21,"24":24,"25":25,"27":27,"29":29,"32":32,"33":33,"34":34,"35":35,"38":38,"40":40,"5":5,"6":6,"9":9}],9:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _button = _dereq_(2); var _button2 = _interopRequireDefault(_button); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file fullscreen-toggle.js */ /** * Toggle fullscreen video * * @extends Button */ var FullscreenToggle = function (_Button) { _inherits(FullscreenToggle, _Button); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function FullscreenToggle(player, options) { _classCallCheck(this, FullscreenToggle); var _this = _possibleConstructorReturn(this, _Button.call(this, player, options)); _this.on(player, 'fullscreenchange', _this.handleFullscreenChange); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ FullscreenToggle.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-fullscreen-control ' + _Button.prototype.buildCSSClass.call(this); }; /** * Handles fullscreenchange on the player and change control text accordingly. * * @param {EventTarget~Event} [event] * The {@link Player#fullscreenchange} event that caused this function to be * called. * * @listens Player#fullscreenchange */ FullscreenToggle.prototype.handleFullscreenChange = function handleFullscreenChange(event) { if (this.player_.isFullscreen()) { this.controlText('Non-Fullscreen'); } else { this.controlText('Fullscreen'); } }; /** * This gets called when an `FullscreenToggle` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ FullscreenToggle.prototype.handleClick = function handleClick(event) { if (!this.player_.isFullscreen()) { this.player_.requestFullscreen(); } else { this.player_.exitFullscreen(); } }; return FullscreenToggle; }(_button2['default']); /** * The text that should display over the `FullscreenToggle`s controls. Added for localization. * * @type {string} * @private */ FullscreenToggle.prototype.controlText_ = 'Fullscreen'; _component2['default'].registerComponent('FullscreenToggle', FullscreenToggle); exports['default'] = FullscreenToggle; },{"2":2,"5":5}],10:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(81); var Dom = _interopRequireWildcard(_dom); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file live-display.js */ // TODO - Future make it click to snap to live /** * Displays the live indicator when duration is Infinity. * * @extends Component */ var LiveDisplay = function (_Component) { _inherits(LiveDisplay, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function LiveDisplay(player, options) { _classCallCheck(this, LiveDisplay); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.updateShowing(); _this.on(_this.player(), 'durationchange', _this.updateShowing); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ LiveDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-live-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-live-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Stream Type') + '</span>' + this.localize('LIVE') }, { 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; }; /** * Check the duration to see if the LiveDisplay should be showing or not. Then show/hide * it accordingly * * @param {EventTarget~Event} [event] * The {@link Player#durationchange} event that caused this function to run. * * @listens Player#durationchange */ LiveDisplay.prototype.updateShowing = function updateShowing(event) { if (this.player().duration() === Infinity) { this.show(); } else { this.hide(); } }; return LiveDisplay; }(_component2['default']); _component2['default'].registerComponent('LiveDisplay', LiveDisplay); exports['default'] = LiveDisplay; },{"5":5,"81":81}],11:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _button = _dereq_(2); var _button2 = _interopRequireDefault(_button); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(81); var Dom = _interopRequireWildcard(_dom); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file mute-toggle.js */ /** * A button component for muting the audio. * * @extends Button */ var MuteToggle = function (_Button) { _inherits(MuteToggle, _Button); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function MuteToggle(player, options) { _classCallCheck(this, MuteToggle); var _this = _possibleConstructorReturn(this, _Button.call(this, player, options)); _this.on(player, 'volumechange', _this.update); // hide mute toggle if the current tech doesn't support volume control if (player.tech_ && player.tech_.featuresVolumeControl === false) { _this.addClass('vjs-hidden'); } _this.on(player, 'loadstart', function () { // We need to update the button to account for a default muted state. this.update(); if (player.tech_.featuresVolumeControl === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ MuteToggle.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-mute-control ' + _Button.prototype.buildCSSClass.call(this); }; /** * This gets called when an `MuteToggle` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ MuteToggle.prototype.handleClick = function handleClick(event) { this.player_.muted(this.player_.muted() ? false : true); }; /** * Update the state of volume. * * @param {EventTarget~Event} [event] * The {@link Player#loadstart} event if this function was called through an * event. * * @listens Player#loadstart */ MuteToggle.prototype.update = function update(event) { var vol = this.player_.volume(); var level = 3; if (vol === 0 || this.player_.muted()) { level = 0; } else if (vol < 0.33) { level = 1; } else if (vol < 0.67) { level = 2; } // Don't rewrite the button text if the actual text doesn't change. // This causes unnecessary and confusing information for screen reader users. // This check is needed because this function gets called every time the volume level is changed. var toMute = this.player_.muted() ? 'Unmute' : 'Mute'; if (this.controlText() !== toMute) { this.controlText(toMute); } // TODO improve muted icon classes for (var i = 0; i < 4; i++) { Dom.removeElClass(this.el_, 'vjs-vol-' + i); } Dom.addElClass(this.el_, 'vjs-vol-' + level); }; return MuteToggle; }(_button2['default']); /** * The text that should display over the `MuteToggle`s controls. Added for localization. * * @type {string} * @private */ MuteToggle.prototype.controlText_ = 'Mute'; _component2['default'].registerComponent('MuteToggle', MuteToggle); exports['default'] = MuteToggle; },{"2":2,"5":5,"81":81}],12:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _button = _dereq_(2); var _button2 = _interopRequireDefault(_button); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file play-toggle.js */ /** * Button to toggle between play and pause. * * @extends Button */ var PlayToggle = function (_Button) { _inherits(PlayToggle, _Button); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function PlayToggle(player, options) { _classCallCheck(this, PlayToggle); var _this = _possibleConstructorReturn(this, _Button.call(this, player, options)); _this.on(player, 'play', _this.handlePlay); _this.on(player, 'pause', _this.handlePause); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ PlayToggle.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-play-control ' + _Button.prototype.buildCSSClass.call(this); }; /** * This gets called when an `PlayToggle` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ PlayToggle.prototype.handleClick = function handleClick(event) { if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } }; /** * Add the vjs-playing class to the element so it can change appearance. * * @param {EventTarget~Event} [event] * The event that caused this function to run. * * @listens Player#play */ PlayToggle.prototype.handlePlay = function handlePlay(event) { this.removeClass('vjs-paused'); this.addClass('vjs-playing'); // change the button text to "Pause" this.controlText('Pause'); }; /** * Add the vjs-paused class to the element so it can change appearance. * * @param {EventTarget~Event} [event] * The event that caused this function to run. * * @listens Player#pause */ PlayToggle.prototype.handlePause = function handlePause(event) { this.removeClass('vjs-playing'); this.addClass('vjs-paused'); // change the button text to "Play" this.controlText('Play'); }; return PlayToggle; }(_button2['default']); /** * The text that should display over the `PlayToggle`s controls. Added for localization. * * @type {string} * @private */ PlayToggle.prototype.controlText_ = 'Play'; _component2['default'].registerComponent('PlayToggle', PlayToggle); exports['default'] = PlayToggle; },{"2":2,"5":5}],13:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _menuButton = _dereq_(47); var _menuButton2 = _interopRequireDefault(_menuButton); var _menu = _dereq_(49); var _menu2 = _interopRequireDefault(_menu); var _playbackRateMenuItem = _dereq_(14); var _playbackRateMenuItem2 = _interopRequireDefault(_playbackRateMenuItem); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(81); var Dom = _interopRequireWildcard(_dom); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file playback-rate-menu-button.js */ /** * The component for controlling the playback rate. * * @extends MenuButton */ var PlaybackRateMenuButton = function (_MenuButton) { _inherits(PlaybackRateMenuButton, _MenuButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function PlaybackRateMenuButton(player, options) { _classCallCheck(this, PlaybackRateMenuButton); var _this = _possibleConstructorReturn(this, _MenuButton.call(this, player, options)); _this.updateVisibility(); _this.updateLabel(); _this.on(player, 'loadstart', _this.updateVisibility); _this.on(player, 'ratechange', _this.updateLabel); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ PlaybackRateMenuButton.prototype.createEl = function createEl() { var el = _MenuButton.prototype.createEl.call(this); this.labelEl_ = Dom.createEl('div', { className: 'vjs-playback-rate-value', innerHTML: 1.0 }); el.appendChild(this.labelEl_); return el; }; /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ PlaybackRateMenuButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-playback-rate ' + _MenuButton.prototype.buildCSSClass.call(this); }; /** * Create the playback rate menu * * @return {Menu} * Menu object populated with {@link PlaybackRateMenuItem}s */ PlaybackRateMenuButton.prototype.createMenu = function createMenu() { var menu = new _menu2['default'](this.player()); var rates = this.playbackRates(); if (rates) { for (var i = rates.length - 1; i >= 0; i--) { menu.addChild(new _playbackRateMenuItem2['default'](this.player(), { rate: rates[i] + 'x' })); } } return menu; }; /** * Updates ARIA accessibility attributes */ PlaybackRateMenuButton.prototype.updateARIAAttributes = function updateARIAAttributes() { // Current playback rate this.el().setAttribute('aria-valuenow', this.player().playbackRate()); }; /** * This gets called when an `PlaybackRateMenuButton` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ PlaybackRateMenuButton.prototype.handleClick = function handleClick(event) { // select next rate option var currentRate = this.player().playbackRate(); var rates = this.playbackRates(); // this will select first one if the last one currently selected var newRate = rates[0]; for (var i = 0; i < rates.length; i++) { if (rates[i] > currentRate) { newRate = rates[i]; break; } } this.player().playbackRate(newRate); }; /** * Get possible playback rates * * @return {Array} * All possible playback rates */ PlaybackRateMenuButton.prototype.playbackRates = function playbackRates() { return this.options_.playbackRates || this.options_.playerOptions && this.options_.playerOptions.playbackRates; }; /** * Get whether playback rates is supported by the tech * and an array of playback rates exists * * @return {boolean} * Whether changing playback rate is supported */ PlaybackRateMenuButton.prototype.playbackRateSupported = function playbackRateSupported() { return this.player().tech_ && this.player().tech_.featuresPlaybackRate && this.playbackRates() && this.playbackRates().length > 0; }; /** * Hide playback rate controls when they're no playback rate options to select * * @param {EventTarget~Event} [event] * The event that caused this function to run. * * @listens Player#loadstart */ PlaybackRateMenuButton.prototype.updateVisibility = function updateVisibility(event) { if (this.playbackRateSupported()) { this.removeClass('vjs-hidden'); } else { this.addClass('vjs-hidden'); } }; /** * Update button label when rate changed * * @param {EventTarget~Event} [event] * The event that caused this function to run. * * @listens Player#ratechange */ PlaybackRateMenuButton.prototype.updateLabel = function updateLabel(event) { if (this.playbackRateSupported()) { this.labelEl_.innerHTML = this.player().playbackRate() + 'x'; } }; return PlaybackRateMenuButton; }(_menuButton2['default']); /** * The text that should display over the `FullscreenToggle`s controls. Added for localization. * * @type {string} * @private */ PlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate'; _component2['default'].registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton); exports['default'] = PlaybackRateMenuButton; },{"14":14,"47":47,"49":49,"5":5,"81":81}],14:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _menuItem = _dereq_(48); var _menuItem2 = _interopRequireDefault(_menuItem); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file playback-rate-menu-item.js */ /** * The specific menu item type for selecting a playback rate. * * @extends MenuItem */ var PlaybackRateMenuItem = function (_MenuItem) { _inherits(PlaybackRateMenuItem, _MenuItem); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function PlaybackRateMenuItem(player, options) { _classCallCheck(this, PlaybackRateMenuItem); var label = options.rate; var rate = parseFloat(label, 10); // Modify options for parent MenuItem class's init. options.label = label; options.selected = rate === 1; options.selectable = true; var _this = _possibleConstructorReturn(this, _MenuItem.call(this, player, options)); _this.label = label; _this.rate = rate; _this.on(player, 'ratechange', _this.update); return _this; } /** * This gets called when an `PlaybackRateMenuItem` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ PlaybackRateMenuItem.prototype.handleClick = function handleClick(event) { _MenuItem.prototype.handleClick.call(this); this.player().playbackRate(this.rate); }; /** * Update the PlaybackRateMenuItem when the playbackrate changes. * * @param {EventTarget~Event} [event] * The `ratechange` event that caused this function to run. * * @listens Player#ratechange */ PlaybackRateMenuItem.prototype.update = function update(event) { this.selected(this.player().playbackRate() === this.rate); }; return PlaybackRateMenuItem; }(_menuItem2['default']); /** * The text that should display over the `PlaybackRateMenuItem`s controls. Added for localization. * * @type {string} * @private */ PlaybackRateMenuItem.prototype.contentElType = 'button'; _component2['default'].registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem); exports['default'] = PlaybackRateMenuItem; },{"48":48,"5":5}],15:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(81); var Dom = _interopRequireWildcard(_dom); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file load-progress-bar.js */ /** * Shows loading progress * * @extends Component */ var LoadProgressBar = function (_Component) { _inherits(LoadProgressBar, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function LoadProgressBar(player, options) { _classCallCheck(this, LoadProgressBar); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.partEls_ = []; _this.on(player, 'progress', _this.update); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ LoadProgressBar.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-load-progress', innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Loaded') + '</span>: 0%</span>' }); }; /** * Update progress bar * * @param {EventTarget~Event} [event] * The `progress` event that caused this function to run. * * @listens Player#progress */ LoadProgressBar.prototype.update = function update(event) { var buffered = this.player_.buffered(); var duration = this.player_.duration(); var bufferedEnd = this.player_.bufferedEnd(); var children = this.partEls_; // get the percent width of a time compared to the total end var percentify = function percentify(time, end) { // no NaN var percent = time / end || 0; return (percent >= 1 ? 1 : percent) * 100 + '%'; }; // update the width of the progress bar this.el_.style.width = percentify(bufferedEnd, duration); // add child elements to represent the individual buffered time ranges for (var i = 0; i < buffered.length; i++) { var start = buffered.start(i); var end = buffered.end(i); var part = children[i]; if (!part) { part = this.el_.appendChild(Dom.createEl()); children[i] = part; } // set the percent based on the width of the progress bar (bufferedEnd) part.style.left = percentify(start, bufferedEnd); part.style.width = percentify(end - start, bufferedEnd); } // remove unused buffered range elements for (var _i = children.length; _i > buffered.length; _i--) { this.el_.removeChild(children[_i - 1]); } children.length = buffered.length; }; return LoadProgressBar; }(_component2['default']); _component2['default'].registerComponent('LoadProgressBar', LoadProgressBar); exports['default'] = LoadProgressBar; },{"5":5,"81":81}],16:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(81); var Dom = _interopRequireWildcard(_dom); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); var _formatTime = _dereq_(84); var _formatTime2 = _interopRequireDefault(_formatTime); var _computedStyle = _dereq_(80); var _computedStyle2 = _interopRequireDefault(_computedStyle); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file mouse-time-display.js */ /** * The Mouse Time Display component shows the time you will seek to * when hovering over the progress bar * * @extends Component */ var MouseTimeDisplay = function (_Component) { _inherits(MouseTimeDisplay, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function MouseTimeDisplay(player, options) { _classCallCheck(this, MouseTimeDisplay); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); if (options.playerOptions && options.playerOptions.controlBar && options.playerOptions.controlBar.progressControl && options.playerOptions.controlBar.progressControl.keepTooltipsInside) { _this.keepTooltipsInside = options.playerOptions.controlBar.progressControl.keepTooltipsInside; } if (_this.keepTooltipsInside) { _this.tooltip = Dom.createEl('div', { className: 'vjs-time-tooltip' }); _this.el().appendChild(_this.tooltip); _this.addClass('vjs-keep-tooltips-inside'); } _this.update(0, 0); player.on('ready', function () { _this.on(player.controlBar.progressControl.el(), 'mousemove', Fn.throttle(Fn.bind(_this, _this.handleMouseMove), 25)); }); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ MouseTimeDisplay.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-mouse-display' }); }; /** * Handle the mouse move event on the `MouseTimeDisplay`. * * @param {EventTarget~Event} event * The `mousemove` event that caused this to event to run. * * @listen mousemove */ MouseTimeDisplay.prototype.handleMouseMove = function handleMouseMove(event) { var duration = this.player_.duration(); var newTime = this.calculateDistance(event) * duration; var position = event.pageX - Dom.findElPosition(this.el().parentNode).left; this.update(newTime, position); }; /** * Update the time and posistion of the `MouseTimeDisplay`. * * @param {number} newTime * Time to change the `MouseTimeDisplay` to. * * @param {nubmer} position * Postion from the left of the in pixels. */ MouseTimeDisplay.prototype.update = function update(newTime, position) { var time = (0, _formatTime2['default'])(newTime, this.player_.duration()); this.el().style.left = position + 'px'; this.el().setAttribute('data-current-time', time); if (this.keepTooltipsInside) { var clampedPosition = this.clampPosition_(position); var difference = position - clampedPosition + 1; var tooltipWidth = parseFloat((0, _computedStyle2['default'])(this.tooltip, 'width')); var tooltipWidthHalf = tooltipWidth / 2; this.tooltip.innerHTML = time; this.tooltip.style.right = '-' + (tooltipWidthHalf - difference) + 'px'; } }; /** * Get the mouse pointers x coordinate in pixels. * * @param {EventTarget~Event} [event] * The `mousemove` event that was passed to this function by * {@link MouseTimeDisplay#handleMouseMove} * * @return {number} * THe x position in pixels of the mouse pointer. */ MouseTimeDisplay.prototype.calculateDistance = function calculateDistance(event) { return Dom.getPointerPosition(this.el().parentNode, event).x; }; /** * This takes in a horizontal position for the bar and returns a clamped position. * Clamped position means that it will keep the position greater than half the width * of the tooltip and smaller than the player width minus half the width o the tooltip. * It will only clamp the position if `keepTooltipsInside` option is set. * * @param {number} position * The position the bar wants to be * * @return {number} * The (potentially) new clamped position. * * @private */ MouseTimeDisplay.prototype.clampPosition_ = function clampPosition_(position) { if (!this.keepTooltipsInside) { return position; } var playerWidth = parseFloat((0, _computedStyle2['default'])(this.player().el(), 'width')); var tooltipWidth = parseFloat((0, _computedStyle2['default'])(this.tooltip, 'width')); var tooltipWidthHalf = tooltipWidth / 2; var actualPosition = position; if (position < tooltipWidthHalf) { actualPosition = Math.ceil(tooltipWidthHalf); } else if (position > playerWidth - tooltipWidthHalf) { actualPosition = Math.floor(playerWidth - tooltipWidthHalf); } return actualPosition; }; return MouseTimeDisplay; }(_component2['default']); _component2['default'].registerComponent('MouseTimeDisplay', MouseTimeDisplay); exports['default'] = MouseTimeDisplay; },{"5":5,"80":80,"81":81,"83":83,"84":84}],17:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); var _formatTime = _dereq_(84); var _formatTime2 = _interopRequireDefault(_formatTime); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file play-progress-bar.js */ /** * Shows play progress * * @extends Component */ var PlayProgressBar = function (_Component) { _inherits(PlayProgressBar, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function PlayProgressBar(player, options) { _classCallCheck(this, PlayProgressBar); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.updateDataAttr(); _this.on(player, 'timeupdate', _this.updateDataAttr); player.ready(Fn.bind(_this, _this.updateDataAttr)); if (options.playerOptions && options.playerOptions.controlBar && options.playerOptions.controlBar.progressControl && options.playerOptions.controlBar.progressControl.keepTooltipsInside) { _this.keepTooltipsInside = options.playerOptions.controlBar.progressControl.keepTooltipsInside; } if (_this.keepTooltipsInside) { _this.addClass('vjs-keep-tooltips-inside'); } return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ PlayProgressBar.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-play-progress vjs-slider-bar', innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Progress') + '</span>: 0%</span>' }); }; /** * Update the data-current-time attribute on the `PlayProgressBar`. * * @param {EventTarget~Event} [event] * The `timeupdate` event that caused this to run. * * @listens Player#timeupdate */ PlayProgressBar.prototype.updateDataAttr = function updateDataAttr(event) { var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); this.el_.setAttribute('data-current-time', (0, _formatTime2['default'])(time, this.player_.duration())); }; return PlayProgressBar; }(_component2['default']); _component2['default'].registerComponent('PlayProgressBar', PlayProgressBar); exports['default'] = PlayProgressBar; },{"5":5,"83":83,"84":84}],18:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); _dereq_(19); _dereq_(16); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file progress-control.js */ /** * The Progress Control component contains the seek bar, load progress, * and play progress. * * @extends Component */ var ProgressControl = function (_Component) { _inherits(ProgressControl, _Component); function ProgressControl() { _classCallCheck(this, ProgressControl); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ ProgressControl.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-progress-control vjs-control' }); }; return ProgressControl; }(_component2['default']); /** * Default options for `ProgressControl` * * @type {Object} * @private */ ProgressControl.prototype.options_ = { children: ['seekBar'] }; _component2['default'].registerComponent('ProgressControl', ProgressControl); exports['default'] = ProgressControl; },{"16":16,"19":19,"5":5}],19:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _slider = _dereq_(57); var _slider2 = _interopRequireDefault(_slider); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); var _formatTime = _dereq_(84); var _formatTime2 = _interopRequireDefault(_formatTime); var _computedStyle = _dereq_(80); var _computedStyle2 = _interopRequireDefault(_computedStyle); _dereq_(15); _dereq_(17); _dereq_(20); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file seek-bar.js */ /** * Seek Bar and holder for the progress bars * * @extends Slider */ var SeekBar = function (_Slider) { _inherits(SeekBar, _Slider); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function SeekBar(player, options) { _classCallCheck(this, SeekBar); var _this = _possibleConstructorReturn(this, _Slider.call(this, player, options)); _this.on(player, 'timeupdate', _this.updateProgress); _this.on(player, 'ended', _this.updateProgress); player.ready(Fn.bind(_this, _this.updateProgress)); if (options.playerOptions && options.playerOptions.controlBar && options.playerOptions.controlBar.progressControl && options.playerOptions.controlBar.progressControl.keepTooltipsInside) { _this.keepTooltipsInside = options.playerOptions.controlBar.progressControl.keepTooltipsInside; } if (_this.keepTooltipsInside) { _this.tooltipProgressBar = _this.addChild('TooltipProgressBar'); } return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ SeekBar.prototype.createEl = function createEl() { return _Slider.prototype.createEl.call(this, 'div', { className: 'vjs-progress-holder' }, { 'aria-label': 'progress bar' }); }; /** * Update the seek bars tooltip and width. * * @param {EventTarget~Event} [event] * The `timeupdate` or `ended` event that caused this to run. * * @listens Player#timeupdate * @listens Player#ended */ SeekBar.prototype.updateProgress = function updateProgress(event) { this.updateAriaAttributes(this.el_); if (this.keepTooltipsInside) { this.updateAriaAttributes(this.tooltipProgressBar.el_); this.tooltipProgressBar.el_.style.width = this.bar.el_.style.width; var playerWidth = parseFloat((0, _computedStyle2['default'])(this.player().el(), 'width')); var tooltipWidth = parseFloat((0, _computedStyle2['default'])(this.tooltipProgressBar.tooltip, 'width')); var tooltipStyle = this.tooltipProgressBar.el().style; tooltipStyle.maxWidth = Math.floor(playerWidth - tooltipWidth / 2) + 'px'; tooltipStyle.minWidth = Math.ceil(tooltipWidth / 2) + 'px'; tooltipStyle.right = '-' + tooltipWidth / 2 + 'px'; } }; /** * Update ARIA accessibility attributes * * @param {Element} el * The element to update with aria accessibility attributes. */ SeekBar.prototype.updateAriaAttributes = function updateAriaAttributes(el) { // Allows for smooth scrubbing, when player can't keep up. var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); // machine readable value of progress bar (percentage complete) el.setAttribute('aria-valuenow', (this.getPercent() * 100).toFixed(2)); // human readable value of progress bar (time complete) el.setAttribute('aria-valuetext', (0, _formatTime2['default'])(time, this.player_.duration())); }; /** * Get percentage of video played * * @return {number} * The percentage played */ SeekBar.prototype.getPercent = function getPercent() { var percent = this.player_.currentTime() / this.player_.duration(); return percent >= 1 ? 1 : percent; }; /** * Handle mouse down on seek bar * * @param {EventTarget~Event} event * The `mousedown` event that caused this to run. * * @listens mousedown */ SeekBar.prototype.handleMouseDown = function handleMouseDown(event) { this.player_.scrubbing(true); this.videoWasPlaying = !this.player_.paused(); this.player_.pause(); _Slider.prototype.handleMouseDown.call(this, event); }; /** * Handle mouse move on seek bar * * @param {EventTarget~Event} event * The `mousemove` event that caused this to run. * * @listens mousemove */ SeekBar.prototype.handleMouseMove = function handleMouseMove(event) { var newTime = this.calculateDistance(event) * this.player_.duration(); // Don't let video end while scrubbing. if (newTime === this.player_.duration()) { newTime = newTime - 0.1; } // Set new time (tell player to seek to new time) this.player_.currentTime(newTime); }; /** * Handle mouse up on seek bar * * @param {EventTarget~Event} event * The `mouseup` event that caused this to run. * * @listens mouseup */ SeekBar.prototype.handleMouseUp = function handleMouseUp(event) { _Slider.prototype.handleMouseUp.call(this, event); this.player_.scrubbing(false); if (this.videoWasPlaying) { this.player_.play(); } }; /** * Move more quickly fast forward for keyboard-only users */ SeekBar.prototype.stepForward = function stepForward() { // more quickly fast forward for keyboard-only users this.player_.currentTime(this.player_.currentTime() + 5); }; /** * Move more quickly rewind for keyboard-only users */ SeekBar.prototype.stepBack = function stepBack() { // more quickly rewind for keyboard-only users this.player_.currentTime(this.player_.currentTime() - 5); }; return SeekBar; }(_slider2['default']); /** * Default options for the `SeekBar` * * @type {Object} * @private */ SeekBar.prototype.options_ = { children: ['loadProgressBar', 'mouseTimeDisplay', 'playProgressBar'], barName: 'playProgressBar' }; /** * Call the update event for this Slider when this event happens on the player. * * @type {string} */ SeekBar.prototype.playerEvent = 'timeupdate'; _component2['default'].registerComponent('SeekBar', SeekBar); exports['default'] = SeekBar; },{"15":15,"17":17,"20":20,"5":5,"57":57,"80":80,"83":83,"84":84}],20:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); var _formatTime = _dereq_(84); var _formatTime2 = _interopRequireDefault(_formatTime); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file play-progress-bar.js */ /** * Shows play progress * * @extends Component */ var TooltipProgressBar = function (_Component) { _inherits(TooltipProgressBar, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function TooltipProgressBar(player, options) { _classCallCheck(this, TooltipProgressBar); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.updateDataAttr(); _this.on(player, 'timeupdate', _this.updateDataAttr); player.ready(Fn.bind(_this, _this.updateDataAttr)); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ TooltipProgressBar.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-tooltip-progress-bar vjs-slider-bar', innerHTML: '<div class="vjs-time-tooltip"></div>\n <span class="vjs-control-text"><span>' + this.localize('Progress') + '</span>: 0%</span>' }); this.tooltip = el.querySelector('.vjs-time-tooltip'); return el; }; /** * Updatet the data-current-time attribute for TooltipProgressBar * * @param {EventTarget~Event} [event] * The `timeupdate` event that caused this function to run. * * @listens Player#timeupdate */ TooltipProgressBar.prototype.updateDataAttr = function updateDataAttr(event) { var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); var formattedTime = (0, _formatTime2['default'])(time, this.player_.duration()); this.el_.setAttribute('data-current-time', formattedTime); this.tooltip.innerHTML = formattedTime; }; return TooltipProgressBar; }(_component2['default']); _component2['default'].registerComponent('TooltipProgressBar', TooltipProgressBar); exports['default'] = TooltipProgressBar; },{"5":5,"83":83,"84":84}],21:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _spacer = _dereq_(22); var _spacer2 = _interopRequireDefault(_spacer); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file custom-control-spacer.js */ /** * Spacer specifically meant to be used as an insertion point for new plugins, etc. * * @extends Spacer */ var CustomControlSpacer = function (_Spacer) { _inherits(CustomControlSpacer, _Spacer); function CustomControlSpacer() { _classCallCheck(this, CustomControlSpacer); return _possibleConstructorReturn(this, _Spacer.apply(this, arguments)); } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ CustomControlSpacer.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-custom-control-spacer ' + _Spacer.prototype.buildCSSClass.call(this); }; /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ CustomControlSpacer.prototype.createEl = function createEl() { var el = _Spacer.prototype.createEl.call(this, { className: this.buildCSSClass() }); // No-flex/table-cell mode requires there be some content // in the cell to fill the remaining space of the table. el.innerHTML = '&nbsp;'; return el; }; return CustomControlSpacer; }(_spacer2['default']); _component2['default'].registerComponent('CustomControlSpacer', CustomControlSpacer); exports['default'] = CustomControlSpacer; },{"22":22,"5":5}],22:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file spacer.js */ /** * Just an empty spacer element that can be used as an append point for plugins, etc. * Also can be used to create space between elements when necessary. * * @extends Component */ var Spacer = function (_Component) { _inherits(Spacer, _Component); function Spacer() { _classCallCheck(this, Spacer); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ Spacer.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-spacer ' + _Component.prototype.buildCSSClass.call(this); }; /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ Spacer.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: this.buildCSSClass() }); }; return Spacer; }(_component2['default']); _component2['default'].registerComponent('Spacer', Spacer); exports['default'] = Spacer; },{"5":5}],23:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _textTrackMenuItem = _dereq_(31); var _textTrackMenuItem2 = _interopRequireDefault(_textTrackMenuItem); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file caption-settings-menu-item.js */ /** * The menu item for caption track settings menu * * @extends TextTrackMenuItem */ var CaptionSettingsMenuItem = function (_TextTrackMenuItem) { _inherits(CaptionSettingsMenuItem, _TextTrackMenuItem); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function CaptionSettingsMenuItem(player, options) { _classCallCheck(this, CaptionSettingsMenuItem); options.track = { player: player, kind: options.kind, label: options.kind + ' settings', selectable: false, 'default': false, mode: 'disabled' }; // CaptionSettingsMenuItem has no concept of 'selected' options.selectable = false; var _this = _possibleConstructorReturn(this, _TextTrackMenuItem.call(this, player, options)); _this.addClass('vjs-texttrack-settings'); _this.controlText(', opens ' + options.kind + ' settings dialog'); return _this; } /** * This gets called when an `CaptionSettingsMenuItem` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ CaptionSettingsMenuItem.prototype.handleClick = function handleClick(event) { this.player().getChild('textTrackSettings').show(); this.player().getChild('textTrackSettings').el_.focus(); }; return CaptionSettingsMenuItem; }(_textTrackMenuItem2['default']); _component2['default'].registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem); exports['default'] = CaptionSettingsMenuItem; },{"31":31,"5":5}],24:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _textTrackButton = _dereq_(30); var _textTrackButton2 = _interopRequireDefault(_textTrackButton); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _captionSettingsMenuItem = _dereq_(23); var _captionSettingsMenuItem2 = _interopRequireDefault(_captionSettingsMenuItem); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file captions-button.js */ /** * The button component for toggling and selecting captions * * @extends TextTrackButton */ var CaptionsButton = function (_TextTrackButton) { _inherits(CaptionsButton, _TextTrackButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} [ready] * The function to call when this component is ready. */ function CaptionsButton(player, options, ready) { _classCallCheck(this, CaptionsButton); var _this = _possibleConstructorReturn(this, _TextTrackButton.call(this, player, options, ready)); _this.el_.setAttribute('aria-label', 'Captions Menu'); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ CaptionsButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-captions-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; /** * Create caption menu items * * @return {CaptionSettingsMenuItem[]} * The array of current menu items. */ CaptionsButton.prototype.createItems = function createItems() { var items = []; if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks)) { items.push(new _captionSettingsMenuItem2['default'](this.player_, { kind: this.kind_ })); this.hideThreshold_ += 1; } return _TextTrackButton.prototype.createItems.call(this, items); }; return CaptionsButton; }(_textTrackButton2['default']); /** * `kind` of TextTrack to look for to associate it with this menu. * * @type {string} * @private */ CaptionsButton.prototype.kind_ = 'captions'; /** * The text that should display over the `CaptionsButton`s controls. Added for localization. * * @type {string} * @private */ CaptionsButton.prototype.controlText_ = 'Captions'; _component2['default'].registerComponent('CaptionsButton', CaptionsButton); exports['default'] = CaptionsButton; },{"23":23,"30":30,"5":5}],25:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _textTrackButton = _dereq_(30); var _textTrackButton2 = _interopRequireDefault(_textTrackButton); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _chaptersTrackMenuItem = _dereq_(26); var _chaptersTrackMenuItem2 = _interopRequireDefault(_chaptersTrackMenuItem); var _toTitleCase = _dereq_(91); var _toTitleCase2 = _interopRequireDefault(_toTitleCase); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file chapters-button.js */ /** * The button component for toggling and selecting chapters * Chapters act much differently than other text tracks * Cues are navigation vs. other tracks of alternative languages * * @extends TextTrackButton */ var ChaptersButton = function (_TextTrackButton) { _inherits(ChaptersButton, _TextTrackButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} [ready] * The function to call when this function is ready. */ function ChaptersButton(player, options, ready) { _classCallCheck(this, ChaptersButton); var _this = _possibleConstructorReturn(this, _TextTrackButton.call(this, player, options, ready)); _this.el_.setAttribute('aria-label', 'Chapters Menu'); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ ChaptersButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-chapters-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; /** * Update the menu based on the current state of its items. * * @param {EventTarget~Event} [event] * An event that triggered this function to run. * * @listens TextTrackList#addtrack * @listens TextTrackList#removetrack * @listens TextTrackList#change */ ChaptersButton.prototype.update = function update(event) { if (!this.track_ || event && (event.type === 'addtrack' || event.type === 'removetrack')) { this.setTrack(this.findChaptersTrack()); } _TextTrackButton.prototype.update.call(this); }; /** * Set the currently selected track for the chapters button. * * @param {TextTrack} track * The new track to select. Nothing will change if this is the currently selected * track. */ ChaptersButton.prototype.setTrack = function setTrack(track) { if (this.track_ === track) { return; } if (!this.updateHandler_) { this.updateHandler_ = this.update.bind(this); } // here this.track_ refers to the old track instance if (this.track_) { var remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_); if (remoteTextTrackEl) { remoteTextTrackEl.removeEventListener('load', this.updateHandler_); } this.track_ = null; } this.track_ = track; // here this.track_ refers to the new track instance if (this.track_) { this.track_.mode = 'hidden'; var _remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_); if (_remoteTextTrackEl) { _remoteTextTrackEl.addEventListener('load', this.updateHandler_); } } }; /** * Find the track object that is currently in use by this ChaptersButton * * @return {TextTrack|undefined} * The current track or undefined if none was found. */ ChaptersButton.prototype.findChaptersTrack = function findChaptersTrack() { var tracks = this.player_.textTracks() || []; for (var i = tracks.length - 1; i >= 0; i--) { // We will always choose the last track as our chaptersTrack var track = tracks[i]; if (track.kind === this.kind_) { return track; } } }; /** * Get the caption for the ChaptersButton based on the track label. This will also * use the current tracks localized kind as a fallback if a label does not exist. * * @return {string} * The tracks current label or the localized track kind. */ ChaptersButton.prototype.getMenuCaption = function getMenuCaption() { if (this.track_ && this.track_.label) { return this.track_.label; } return this.localize((0, _toTitleCase2['default'])(this.kind_)); }; /** * Create menu from chapter track * * @return {Menu} * New menu for the chapter buttons */ ChaptersButton.prototype.createMenu = function createMenu() { this.options_.title = this.getMenuCaption(); return _TextTrackButton.prototype.createMenu.call(this); }; /** * Create a menu item for each text track * * @return {TextTrackMenuItem[]} * Array of menu items */ ChaptersButton.prototype.createItems = function createItems() { var items = []; if (!this.track_) { return items; } var cues = this.track_.cues; if (!cues) { return items; } for (var i = 0, l = cues.length; i < l; i++) { var cue = cues[i]; var mi = new _chaptersTrackMenuItem2['default'](this.player_, { track: this.track_, cue: cue }); items.push(mi); } return items; }; return ChaptersButton; }(_textTrackButton2['default']); /** * `kind` of TextTrack to look for to associate it with this menu. * * @type {string} * @private */ ChaptersButton.prototype.kind_ = 'chapters'; /** * The text that should display over the `ChaptersButton`s controls. Added for localization. * * @type {string} * @private */ ChaptersButton.prototype.controlText_ = 'Chapters'; _component2['default'].registerComponent('ChaptersButton', ChaptersButton); exports['default'] = ChaptersButton; },{"26":26,"30":30,"5":5,"91":91}],26:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _menuItem = _dereq_(48); var _menuItem2 = _interopRequireDefault(_menuItem); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file chapters-track-menu-item.js */ /** * The chapter track menu item * * @extends MenuItem */ var ChaptersTrackMenuItem = function (_MenuItem) { _inherits(ChaptersTrackMenuItem, _MenuItem); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function ChaptersTrackMenuItem(player, options) { _classCallCheck(this, ChaptersTrackMenuItem); var track = options.track; var cue = options.cue; var currentTime = player.currentTime(); // Modify options for parent MenuItem class's init. options.selectable = true; options.label = cue.text; options.selected = cue.startTime <= currentTime && currentTime < cue.endTime; var _this = _possibleConstructorReturn(this, _MenuItem.call(this, player, options)); _this.track = track; _this.cue = cue; track.addEventListener('cuechange', Fn.bind(_this, _this.update)); return _this; } /** * This gets called when an `ChaptersTrackMenuItem` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ ChaptersTrackMenuItem.prototype.handleClick = function handleClick(event) { _MenuItem.prototype.handleClick.call(this); this.player_.currentTime(this.cue.startTime); this.update(this.cue.startTime); }; /** * Update chapter menu item * * @param {EventTarget~Event} [event] * The `cuechange` event that caused this function to run. * * @listens TextTrack#cuechange */ ChaptersTrackMenuItem.prototype.update = function update(event) { var cue = this.cue; var currentTime = this.player_.currentTime(); // vjs.log(currentTime, cue.startTime); this.selected(cue.startTime <= currentTime && currentTime < cue.endTime); }; return ChaptersTrackMenuItem; }(_menuItem2['default']); _component2['default'].registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem); exports['default'] = ChaptersTrackMenuItem; },{"48":48,"5":5,"83":83}],27:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _textTrackButton = _dereq_(30); var _textTrackButton2 = _interopRequireDefault(_textTrackButton); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file descriptions-button.js */ /** * The button component for toggling and selecting descriptions * * @extends TextTrackButton */ var DescriptionsButton = function (_TextTrackButton) { _inherits(DescriptionsButton, _TextTrackButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} [ready] * The function to call when this component is ready. */ function DescriptionsButton(player, options, ready) { _classCallCheck(this, DescriptionsButton); var _this = _possibleConstructorReturn(this, _TextTrackButton.call(this, player, options, ready)); _this.el_.setAttribute('aria-label', 'Descriptions Menu'); var tracks = player.textTracks(); if (tracks) { var changeHandler = Fn.bind(_this, _this.handleTracksChange); tracks.addEventListener('change', changeHandler); _this.on('dispose', function () { tracks.removeEventListener('change', changeHandler); }); } return _this; } /** * Handle text track change * * @param {EventTarget~Event} event * The event that caused this function to run * * @listens TextTrackList#change */ DescriptionsButton.prototype.handleTracksChange = function handleTracksChange(event) { var tracks = this.player().textTracks(); var disabled = false; // Check whether a track of a different kind is showing for (var i = 0, l = tracks.length; i < l; i++) { var track = tracks[i]; if (track.kind !== this.kind_ && track.mode === 'showing') { disabled = true; break; } } // If another track is showing, disable this menu button if (disabled) { this.disable(); } else { this.enable(); } }; /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ DescriptionsButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-descriptions-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; return DescriptionsButton; }(_textTrackButton2['default']); /** * `kind` of TextTrack to look for to associate it with this menu. * * @type {string} * @private */ DescriptionsButton.prototype.kind_ = 'descriptions'; /** * The text that should display over the `DescriptionsButton`s controls. Added for localization. * * @type {string} * @private */ DescriptionsButton.prototype.controlText_ = 'Descriptions'; _component2['default'].registerComponent('DescriptionsButton', DescriptionsButton); exports['default'] = DescriptionsButton; },{"30":30,"5":5,"83":83}],28:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _textTrackMenuItem = _dereq_(31); var _textTrackMenuItem2 = _interopRequireDefault(_textTrackMenuItem); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file off-text-track-menu-item.js */ /** * A special menu item for turning of a specific type of text track * * @extends TextTrackMenuItem */ var OffTextTrackMenuItem = function (_TextTrackMenuItem) { _inherits(OffTextTrackMenuItem, _TextTrackMenuItem); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function OffTextTrackMenuItem(player, options) { _classCallCheck(this, OffTextTrackMenuItem); // Create pseudo track info // Requires options['kind'] options.track = { player: player, kind: options.kind, label: options.kind + ' off', 'default': false, mode: 'disabled' }; // MenuItem is selectable options.selectable = true; var _this = _possibleConstructorReturn(this, _TextTrackMenuItem.call(this, player, options)); _this.selected(true); return _this; } /** * Handle text track change * * @param {EventTarget~Event} event * The event that caused this function to run */ OffTextTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) { var tracks = this.player().textTracks(); var selected = true; for (var i = 0, l = tracks.length; i < l; i++) { var track = tracks[i]; if (track.kind === this.track.kind && track.mode === 'showing') { selected = false; break; } } this.selected(selected); }; return OffTextTrackMenuItem; }(_textTrackMenuItem2['default']); _component2['default'].registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem); exports['default'] = OffTextTrackMenuItem; },{"31":31,"5":5}],29:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _textTrackButton = _dereq_(30); var _textTrackButton2 = _interopRequireDefault(_textTrackButton); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file subtitles-button.js */ /** * The button component for toggling and selecting subtitles * * @extends TextTrackButton */ var SubtitlesButton = function (_TextTrackButton) { _inherits(SubtitlesButton, _TextTrackButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} [ready] * The function to call when this component is ready. */ function SubtitlesButton(player, options, ready) { _classCallCheck(this, SubtitlesButton); var _this = _possibleConstructorReturn(this, _TextTrackButton.call(this, player, options, ready)); _this.el_.setAttribute('aria-label', 'Subtitles Menu'); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ SubtitlesButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-subtitles-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; return SubtitlesButton; }(_textTrackButton2['default']); /** * `kind` of TextTrack to look for to associate it with this menu. * * @type {string} * @private */ SubtitlesButton.prototype.kind_ = 'subtitles'; /** * The text that should display over the `SubtitlesButton`s controls. Added for localization. * * @type {string} * @private */ SubtitlesButton.prototype.controlText_ = 'Subtitles'; _component2['default'].registerComponent('SubtitlesButton', SubtitlesButton); exports['default'] = SubtitlesButton; },{"30":30,"5":5}],30:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _trackButton = _dereq_(36); var _trackButton2 = _interopRequireDefault(_trackButton); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _textTrackMenuItem = _dereq_(31); var _textTrackMenuItem2 = _interopRequireDefault(_textTrackMenuItem); var _offTextTrackMenuItem = _dereq_(28); var _offTextTrackMenuItem2 = _interopRequireDefault(_offTextTrackMenuItem); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file text-track-button.js */ /** * The base class for buttons that toggle specific text track types (e.g. subtitles) * * @extends MenuButton */ var TextTrackButton = function (_TrackButton) { _inherits(TextTrackButton, _TrackButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options={}] * The key/value store of player options. */ function TextTrackButton(player) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; _classCallCheck(this, TextTrackButton); options.tracks = player.textTracks(); return _possibleConstructorReturn(this, _TrackButton.call(this, player, options)); } /** * Create a menu item for each text track * * @param {TextTrackMenuItem[]} [items=[]] * Existing array of items to use during creation * * @return {TextTrackMenuItem[]} * Array of menu items that were created */ TextTrackButton.prototype.createItems = function createItems() { var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; // Add an OFF menu item to turn all tracks off items.push(new _offTextTrackMenuItem2['default'](this.player_, { kind: this.kind_ })); this.hideThreshold_ += 1; var tracks = this.player_.textTracks(); if (!tracks) { return items; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; // only add tracks that are of the appropriate kind and have a label if (track.kind === this.kind_) { items.push(new _textTrackMenuItem2['default'](this.player_, { track: track, // MenuItem is selectable selectable: true })); } } return items; }; return TextTrackButton; }(_trackButton2['default']); _component2['default'].registerComponent('TextTrackButton', TextTrackButton); exports['default'] = TextTrackButton; },{"28":28,"31":31,"36":36,"5":5}],31:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _menuItem = _dereq_(48); var _menuItem2 = _interopRequireDefault(_menuItem); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); var _window = _dereq_(95); var _window2 = _interopRequireDefault(_window); var _document = _dereq_(94); var _document2 = _interopRequireDefault(_document); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file text-track-menu-item.js */ /** * The specific menu item type for selecting a language within a text track kind * * @extends MenuItem */ var TextTrackMenuItem = function (_MenuItem) { _inherits(TextTrackMenuItem, _MenuItem); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function TextTrackMenuItem(player, options) { _classCallCheck(this, TextTrackMenuItem); var track = options.track; var tracks = player.textTracks(); // Modify options for parent MenuItem class's init. options.label = track.label || track.language || 'Unknown'; options.selected = track['default'] || track.mode === 'showing'; var _this = _possibleConstructorReturn(this, _MenuItem.call(this, player, options)); _this.track = track; if (tracks) { var changeHandler = Fn.bind(_this, _this.handleTracksChange); player.on(['loadstart', 'texttrackchange'], changeHandler); tracks.addEventListener('change', changeHandler); _this.on('dispose', function () { tracks.removeEventListener('change', changeHandler); }); } // iOS7 doesn't dispatch change events to TextTrackLists when an // associated track's mode changes. Without something like // Object.observe() (also not present on iOS7), it's not // possible to detect changes to the mode attribute and polyfill // the change event. As a poor substitute, we manually dispatch // change events whenever the controls modify the mode. if (tracks && tracks.onchange === undefined) { var event = void 0; _this.on(['tap', 'click'], function () { if (_typeof(_window2['default'].Event) !== 'object') { // Android 2.3 throws an Illegal Constructor error for window.Event try { event = new _window2['default'].Event('change'); } catch (err) { // continue regardless of error } } if (!event) { event = _document2['default'].createEvent('Event'); event.initEvent('change', true, true); } tracks.dispatchEvent(event); }); } return _this; } /** * This gets called when an `TextTrackMenuItem` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} event * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ TextTrackMenuItem.prototype.handleClick = function handleClick(event) { var kind = this.track.kind; var tracks = this.player_.textTracks(); _MenuItem.prototype.handleClick.call(this, event); if (!tracks) { return; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; if (track.kind !== kind) { continue; } if (track === this.track) { track.mode = 'showing'; } else { track.mode = 'disabled'; } } }; /** * Handle text track list change * * @param {EventTarget~Event} event * The `change` event that caused this function to be called. * * @listens TextTrackList#change */ TextTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) { this.selected(this.track.mode === 'showing'); }; return TextTrackMenuItem; }(_menuItem2['default']); _component2['default'].registerComponent('TextTrackMenuItem', TextTrackMenuItem); exports['default'] = TextTrackMenuItem; },{"48":48,"5":5,"83":83,"94":94,"95":95}],32:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(81); var Dom = _interopRequireWildcard(_dom); var _formatTime = _dereq_(84); var _formatTime2 = _interopRequireDefault(_formatTime); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file current-time-display.js */ /** * Displays the current time * * @extends Component */ var CurrentTimeDisplay = function (_Component) { _inherits(CurrentTimeDisplay, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function CurrentTimeDisplay(player, options) { _classCallCheck(this, CurrentTimeDisplay); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.on(player, 'timeupdate', _this.updateContent); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ CurrentTimeDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-current-time vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-current-time-display', // label the current time for screen reader users innerHTML: '<span class="vjs-control-text">Current Time </span>' + '0:00' }, { // tell screen readers not to automatically read the time as it changes 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; }; /** * Update current time display * * @param {EventTarget~Event} [event] * The `timeupdate` event that caused this function to run. * * @listens Player#timeupdate */ CurrentTimeDisplay.prototype.updateContent = function updateContent(event) { // Allows for smooth scrubbing, when player can't keep up. var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); var localizedText = this.localize('Current Time'); var formattedTime = (0, _formatTime2['default'])(time, this.player_.duration()); if (formattedTime !== this.formattedTime_) { this.formattedTime_ = formattedTime; this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> ' + formattedTime; } }; return CurrentTimeDisplay; }(_component2['default']); _component2['default'].registerComponent('CurrentTimeDisplay', CurrentTimeDisplay); exports['default'] = CurrentTimeDisplay; },{"5":5,"81":81,"84":84}],33:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(81); var Dom = _interopRequireWildcard(_dom); var _formatTime = _dereq_(84); var _formatTime2 = _interopRequireDefault(_formatTime); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file duration-display.js */ /** * Displays the duration * * @extends Component */ var DurationDisplay = function (_Component) { _inherits(DurationDisplay, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function DurationDisplay(player, options) { _classCallCheck(this, DurationDisplay); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.on(player, 'durationchange', _this.updateContent); // Also listen for timeupdate and loadedmetadata because removing those // listeners could have broken dependent applications/libraries. These // can likely be removed for 6.0. _this.on(player, 'timeupdate', _this.updateContent); _this.on(player, 'loadedmetadata', _this.updateContent); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ DurationDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-duration vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-duration-display', // label the duration time for screen reader users innerHTML: '<span class="vjs-control-text">' + this.localize('Duration Time') + '</span> 0:00' }, { // tell screen readers not to automatically read the time as it changes 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; }; /** * Update duration time display. * * @param {EventTarget~Event} [event] * The `durationchange`, `timeupdate`, or `loadedmetadata` event that caused * this function to be called. * * @listens Player#durationchange * @listens Player#timeupdate * @listens Player#loadedmetadata */ DurationDisplay.prototype.updateContent = function updateContent(event) { var duration = this.player_.duration(); if (duration && this.duration_ !== duration) { this.duration_ = duration; var localizedText = this.localize('Duration Time'); var formattedTime = (0, _formatTime2['default'])(duration); // label the duration time for screen reader users this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> ' + formattedTime; } }; return DurationDisplay; }(_component2['default']); _component2['default'].registerComponent('DurationDisplay', DurationDisplay); exports['default'] = DurationDisplay; },{"5":5,"81":81,"84":84}],34:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(81); var Dom = _interopRequireWildcard(_dom); var _formatTime = _dereq_(84); var _formatTime2 = _interopRequireDefault(_formatTime); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file remaining-time-display.js */ /** * Displays the time left in the video * * @extends Component */ var RemainingTimeDisplay = function (_Component) { _inherits(RemainingTimeDisplay, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function RemainingTimeDisplay(player, options) { _classCallCheck(this, RemainingTimeDisplay); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.on(player, 'timeupdate', _this.updateContent); _this.on(player, 'durationchange', _this.updateContent); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ RemainingTimeDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-remaining-time vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-remaining-time-display', // label the remaining time for screen reader users innerHTML: '<span class="vjs-control-text">' + this.localize('Remaining Time') + '</span> -0:00' }, { // tell screen readers not to automatically read the time as it changes 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; }; /** * Update remaining time display. * * @param {EventTarget~Event} [event] * The `timeupdate` or `durationchange` event that caused this to run. * * @listens Player#timeupdate * @listens Player#durationchange */ RemainingTimeDisplay.prototype.updateContent = function updateContent(event) { if (this.player_.duration()) { var localizedText = this.localize('Remaining Time'); var formattedTime = (0, _formatTime2['default'])(this.player_.remainingTime()); if (formattedTime !== this.formattedTime_) { this.formattedTime_ = formattedTime; this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> -' + formattedTime; } } // Allows for smooth scrubbing, when player can't keep up. // var time = (this.player_.scrubbing()) ? this.player_.getCache().currentTime : this.player_.currentTime(); // this.contentEl_.innerHTML = vjs.formatTime(time, this.player_.duration()); }; return RemainingTimeDisplay; }(_component2['default']); _component2['default'].registerComponent('RemainingTimeDisplay', RemainingTimeDisplay); exports['default'] = RemainingTimeDisplay; },{"5":5,"81":81,"84":84}],35:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file time-divider.js */ /** * The separator between the current time and duration. * Can be hidden if it's not needed in the design. * * @extends Component */ var TimeDivider = function (_Component) { _inherits(TimeDivider, _Component); function TimeDivider() { _classCallCheck(this, TimeDivider); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } /** * Create the component's DOM element * * @return {Element} * The element that was created. */ TimeDivider.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-time-control vjs-time-divider', innerHTML: '<div><span>/</span></div>' }); }; return TimeDivider; }(_component2['default']); _component2['default'].registerComponent('TimeDivider', TimeDivider); exports['default'] = TimeDivider; },{"5":5}],36:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _menuButton = _dereq_(47); var _menuButton2 = _interopRequireDefault(_menuButton); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file track-button.js */ /** * The base class for buttons that toggle specific track types (e.g. subtitles). * * @extends MenuButton */ var TrackButton = function (_MenuButton) { _inherits(TrackButton, _MenuButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function TrackButton(player, options) { _classCallCheck(this, TrackButton); var tracks = options.tracks; var _this = _possibleConstructorReturn(this, _MenuButton.call(this, player, options)); if (_this.items.length <= 1) { _this.hide(); } if (!tracks) { return _possibleConstructorReturn(_this); } var updateHandler = Fn.bind(_this, _this.update); tracks.addEventListener('removetrack', updateHandler); tracks.addEventListener('addtrack', updateHandler); _this.player_.on('dispose', function () { tracks.removeEventListener('removetrack', updateHandler); tracks.removeEventListener('addtrack', updateHandler); }); return _this; } return TrackButton; }(_menuButton2['default']); _component2['default'].registerComponent('TrackButton', TrackButton); exports['default'] = TrackButton; },{"47":47,"5":5,"83":83}],37:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _slider = _dereq_(57); var _slider2 = _interopRequireDefault(_slider); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); _dereq_(39); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file volume-bar.js */ // Required children /** * The bar that contains the volume level and can be clicked on to adjust the level * * @extends Slider */ var VolumeBar = function (_Slider) { _inherits(VolumeBar, _Slider); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function VolumeBar(player, options) { _classCallCheck(this, VolumeBar); var _this = _possibleConstructorReturn(this, _Slider.call(this, player, options)); _this.on(player, 'volumechange', _this.updateARIAAttributes); player.ready(Fn.bind(_this, _this.updateARIAAttributes)); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ VolumeBar.prototype.createEl = function createEl() { return _Slider.prototype.createEl.call(this, 'div', { className: 'vjs-volume-bar vjs-slider-bar' }, { 'aria-label': 'volume level' }); }; /** * Handle movement events on the {@link VolumeMenuButton}. * * @param {EventTarget~Event} event * The event that caused this function to run. * * @listens mousemove */ VolumeBar.prototype.handleMouseMove = function handleMouseMove(event) { this.checkMuted(); this.player_.volume(this.calculateDistance(event)); }; /** * If the player is muted unmute it. */ VolumeBar.prototype.checkMuted = function checkMuted() { if (this.player_.muted()) { this.player_.muted(false); } }; /** * Get percent of volume level * * @return {number} * Volume level percent as a decimal number. */ VolumeBar.prototype.getPercent = function getPercent() { if (this.player_.muted()) { return 0; } return this.player_.volume(); }; /** * Increase volume level for keyboard users */ VolumeBar.prototype.stepForward = function stepForward() { this.checkMuted(); this.player_.volume(this.player_.volume() + 0.1); }; /** * Decrease volume level for keyboard users */ VolumeBar.prototype.stepBack = function stepBack() { this.checkMuted(); this.player_.volume(this.player_.volume() - 0.1); }; /** * Update ARIA accessibility attributes * * @param {EventTarget~Event} [event] * The `volumechange` event that caused this function to run. * * @listens Player#volumechange */ VolumeBar.prototype.updateARIAAttributes = function updateARIAAttributes(event) { // Current value of volume bar as a percentage var volume = (this.player_.volume() * 100).toFixed(2); this.el_.setAttribute('aria-valuenow', volume); this.el_.setAttribute('aria-valuetext', volume + '%'); }; return VolumeBar; }(_slider2['default']); /** * Default options for the `VolumeBar` * * @type {Object} * @private */ VolumeBar.prototype.options_ = { children: ['volumeLevel'], barName: 'volumeLevel' }; /** * Call the update event for this Slider when this event happens on the player. * * @type {string} */ VolumeBar.prototype.playerEvent = 'volumechange'; _component2['default'].registerComponent('VolumeBar', VolumeBar); exports['default'] = VolumeBar; },{"39":39,"5":5,"57":57,"83":83}],38:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); _dereq_(37); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file volume-control.js */ // Required children /** * The component for controlling the volume level * * @extends Component */ var VolumeControl = function (_Component) { _inherits(VolumeControl, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options={}] * The key/value store of player options. */ function VolumeControl(player, options) { _classCallCheck(this, VolumeControl); // hide volume controls when they're not supported by the current tech var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); if (player.tech_ && player.tech_.featuresVolumeControl === false) { _this.addClass('vjs-hidden'); } _this.on(player, 'loadstart', function () { if (player.tech_.featuresVolumeControl === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); return _this; } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ VolumeControl.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-control vjs-control' }); }; return VolumeControl; }(_component2['default']); /** * Default options for the `VolumeControl` * * @type {Object} * @private */ VolumeControl.prototype.options_ = { children: ['volumeBar'] }; _component2['default'].registerComponent('VolumeControl', VolumeControl); exports['default'] = VolumeControl; },{"37":37,"5":5}],39:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file volume-level.js */ /** * Shows volume level * * @extends Component */ var VolumeLevel = function (_Component) { _inherits(VolumeLevel, _Component); function VolumeLevel() { _classCallCheck(this, VolumeLevel); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } /** * Create the `Component`'s DOM element * * @return {Element} * The element that was created. */ VolumeLevel.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-level', innerHTML: '<span class="vjs-control-text"></span>' }); }; return VolumeLevel; }(_component2['default']); _component2['default'].registerComponent('VolumeLevel', VolumeLevel); exports['default'] = VolumeLevel; },{"5":5}],40:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _popup = _dereq_(54); var _popup2 = _interopRequireDefault(_popup); var _popupButton = _dereq_(53); var _popupButton2 = _interopRequireDefault(_popupButton); var _muteToggle = _dereq_(11); var _muteToggle2 = _interopRequireDefault(_muteToggle); var _volumeBar = _dereq_(37); var _volumeBar2 = _interopRequireDefault(_volumeBar); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file volume-menu-button.js */ /** * Button for volume popup * * @extends PopupButton */ var VolumeMenuButton = function (_PopupButton) { _inherits(VolumeMenuButton, _PopupButton); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options={}] * The key/value store of player options. */ function VolumeMenuButton(player) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; _classCallCheck(this, VolumeMenuButton); // Default to inline if (options.inline === undefined) { options.inline = true; } // If the vertical option isn't passed at all, default to true. if (options.vertical === undefined) { // If an inline volumeMenuButton is used, we should default to using // a horizontal slider for obvious reasons. if (options.inline) { options.vertical = false; } else { options.vertical = true; } } // The vertical option needs to be set on the volumeBar as well, // since that will need to be passed along to the VolumeBar constructor options.volumeBar = options.volumeBar || {}; options.volumeBar.vertical = !!options.vertical; // Same listeners as MuteToggle var _this = _possibleConstructorReturn(this, _PopupButton.call(this, player, options)); _this.on(player, 'volumechange', _this.volumeUpdate); _this.on(player, 'loadstart', _this.volumeUpdate); // hide mute toggle if the current tech doesn't support volume control function updateVisibility() { if (player.tech_ && player.tech_.featuresVolumeControl === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } } updateVisibility.call(_this); _this.on(player, 'loadstart', updateVisibility); _this.on(_this.volumeBar, ['slideractive', 'focus'], function () { this.addClass('vjs-slider-active'); }); _this.on(_this.volumeBar, ['sliderinactive', 'blur'], function () { this.removeClass('vjs-slider-active'); }); _this.on(_this.volumeBar, ['focus'], function () { this.addClass('vjs-lock-showing'); }); _this.on(_this.volumeBar, ['blur'], function () { this.removeClass('vjs-lock-showing'); }); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ VolumeMenuButton.prototype.buildCSSClass = function buildCSSClass() { var orientationClass = ''; if (this.options_.vertical) { orientationClass = 'vjs-volume-menu-button-vertical'; } else { orientationClass = 'vjs-volume-menu-button-horizontal'; } return 'vjs-volume-menu-button ' + _PopupButton.prototype.buildCSSClass.call(this) + ' ' + orientationClass; }; /** * Create the VolumeMenuButton popup * * @return {Popup} * The popup that was created */ VolumeMenuButton.prototype.createPopup = function createPopup() { var popup = new _popup2['default'](this.player_, { contentElType: 'div' }); var vb = new _volumeBar2['default'](this.player_, this.options_.volumeBar); popup.addChild(vb); this.menuContent = popup; this.volumeBar = vb; this.attachVolumeBarEvents(); return popup; }; /** * This gets called when an `VolumeMenuButton` is "clicked". See * {@link ClickableComponent} for more detailed information on what a click can be. * * @param {EventTarget~Event} [event] * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ VolumeMenuButton.prototype.handleClick = function handleClick(event) { _muteToggle2['default'].prototype.handleClick.call(this); _PopupButton.prototype.handleClick.call(this); }; /** * Add events listeners to the created `VolumeBar`. */ VolumeMenuButton.prototype.attachVolumeBarEvents = function attachVolumeBarEvents() { this.menuContent.on(['mousedown', 'touchdown'], Fn.bind(this, this.handleMouseDown)); }; /** * Handle the `mousedown` and `touchdown` events on the `VolumeBar` * * @param {EventTarget~Event} [event] * The `mousedown` or `touchdown` event that caused this to run. * * @listens mousedown * @listens touchdown */ VolumeMenuButton.prototype.handleMouseDown = function handleMouseDown(event) { this.on(['mousemove', 'touchmove'], Fn.bind(this.volumeBar, this.volumeBar.handleMouseMove)); this.on(this.el_.ownerDocument, ['mouseup', 'touchend'], this.handleMouseUp); }; /** * Handle the `mouseup` and `touchend` events on the `VolumeBar` * * @param {EventTarget~Event} [event] * The `mouseup` or `touchend` event that caused this to run. * * @listens mouseup * @listens touchend */ VolumeMenuButton.prototype.handleMouseUp = function handleMouseUp(event) { this.off(['mousemove', 'touchmove'], Fn.bind(this.volumeBar, this.volumeBar.handleMouseMove)); }; return VolumeMenuButton; }(_popupButton2['default']); /** * @borrows MuteToggle#update as VolumeMenuButton#volumeUpdate */ VolumeMenuButton.prototype.volumeUpdate = _muteToggle2['default'].prototype.update; /** * The text that should display over the `VolumeMenuButton`s controls. Added for localization. * * @type {string} * @private */ VolumeMenuButton.prototype.controlText_ = 'Mute'; _component2['default'].registerComponent('VolumeMenuButton', VolumeMenuButton); exports['default'] = VolumeMenuButton; },{"11":11,"37":37,"5":5,"53":53,"54":54,"83":83}],41:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _modalDialog = _dereq_(50); var _modalDialog2 = _interopRequireDefault(_modalDialog); var _mergeOptions = _dereq_(87); var _mergeOptions2 = _interopRequireDefault(_mergeOptions); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file error-display.js */ /** * A display that indicates an error has occurred. This means that the video * is unplayable. * * @extends ModalDialog */ var ErrorDisplay = function (_ModalDialog) { _inherits(ErrorDisplay, _ModalDialog); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function ErrorDisplay(player, options) { _classCallCheck(this, ErrorDisplay); var _this = _possibleConstructorReturn(this, _ModalDialog.call(this, player, options)); _this.on(player, 'error', _this.open); return _this; } /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. * * @deprecated Since version 5. */ ErrorDisplay.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-error-display ' + _ModalDialog.prototype.buildCSSClass.call(this); }; /** * Gets the localized error message based on the `Player`s error. * * @return {string} * The `Player`s error message localized or an empty string. */ ErrorDisplay.prototype.content = function content() { var error = this.player().error(); return error ? this.localize(error.message) : ''; }; return ErrorDisplay; }(_modalDialog2['default']); /** * The default options for an `ErrorDisplay`. * * @private */ ErrorDisplay.prototype.options_ = (0, _mergeOptions2['default'])(_modalDialog2['default'].prototype.options_, { pauseOnOpen: false, fillAlways: true, temporary: false, uncloseable: true }); _component2['default'].registerComponent('ErrorDisplay', ErrorDisplay); exports['default'] = ErrorDisplay; },{"5":5,"50":50,"87":87}],42:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _events = _dereq_(82); var Events = _interopRequireWildcard(_events); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } /** * `EventTarget` is a class that can have the same API as the DOM `EventTarget`. It * adds shorthand functions that wrap around lengthy functions. For example: * the `on` function is a wrapper around `addEventListener`. * * @see [EventTarget Spec]{@link https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget} * @class EventTarget */ var EventTarget = function EventTarget() {}; /** * A Custom DOM event. * * @typedef {Object} EventTarget~Event * @see [Properties]{@link https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent} */ /** * All event listeners should follow the following format. * * @callback EventTarget~EventListener * @this {EventTarget} * * @param {EventTarget~Event} event * the event that triggered this function * * @param {Object} [hash] * hash of data sent during the event */ /** * An object containing event names as keys and booleans as values. * * > NOTE: If an event name is set to a true value here {@link EventTarget#trigger} * will have extra functionality. See that function for more information. * * @property EventTarget.prototype.allowedEvents_ * @private */ /** * @file src/js/event-target.js */ EventTarget.prototype.allowedEvents_ = {}; /** * Adds an `event listener` to an instance of an `EventTarget`. An `event listener` is a * function that will get called when an event with a certain name gets triggered. * * @param {string|string[]} type * An event name or an array of event names. * * @param {EventTarget~EventListener} fn * The function to call with `EventTarget`s */ EventTarget.prototype.on = function (type, fn) { // Remove the addEventListener alias before calling Events.on // so we don't get into an infinite type loop var ael = this.addEventListener; this.addEventListener = function () {}; Events.on(this, type, fn); this.addEventListener = ael; }; /** * An alias of {@link EventTarget#on}. Allows `EventTarget` to mimic * the standard DOM API. * * @function * @see {@link EventTarget#on} */ EventTarget.prototype.addEventListener = EventTarget.prototype.on; /** * Removes an `event listener` for a specific event from an instance of `EventTarget`. * This makes it so that the `event listener` will no longer get called when the * named event happens. * * @param {string|string[]} type * An event name or an array of event names. * * @param {EventTarget~EventListener} fn * The function to remove. */ EventTarget.prototype.off = function (type, fn) { Events.off(this, type, fn); }; /** * An alias of {@link EventTarget#off}. Allows `EventTarget` to mimic * the standard DOM API. * * @function * @see {@link EventTarget#off} */ EventTarget.prototype.removeEventListener = EventTarget.prototype.off; /** * This function will add an `event listener` that gets triggered only once. After the * first trigger it will get removed. This is like adding an `event listener` * with {@link EventTarget#on} that calls {@link EventTarget#off} on itself. * * @param {string|string[]} type * An event name or an array of event names. * * @param {EventTarget~EventListener} fn * The function to be called once for each event name. */ EventTarget.prototype.one = function (type, fn) { // Remove the addEventListener alialing Events.on // so we don't get into an infinite type loop var ael = this.addEventListener; this.addEventListener = function () {}; Events.one(this, type, fn); this.addEventListener = ael; }; /** * This function causes an event to happen. This will then cause any `event listeners` * that are waiting for that event, to get called. If there are no `event listeners` * for an event then nothing will happen. * * If the name of the `Event` that is being triggered is in `EventTarget.allowedEvents_`. * Trigger will also call the `on` + `uppercaseEventName` function. * * Example: * 'click' is in `EventTarget.allowedEvents_`, so, trigger will attempt to call * `onClick` if it exists. * * @param {string|EventTarget~Event|Object} event * The name of the event, an `Event`, or an object with a key of type set to * an event name. */ EventTarget.prototype.trigger = function (event) { var type = event.type || event; if (typeof event === 'string') { event = { type: type }; } event = Events.fixEvent(event); if (this.allowedEvents_[type] && this['on' + type]) { this['on' + type](event); } Events.trigger(this, event); }; /** * An alias of {@link EventTarget#trigger}. Allows `EventTarget` to mimic * the standard DOM API. * * @function * @see {@link EventTarget#trigger} */ EventTarget.prototype.dispatchEvent = EventTarget.prototype.trigger; exports['default'] = EventTarget; },{"82":82}],43:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _log = _dereq_(86); var _log2 = _interopRequireDefault(_log); var _obj = _dereq_(88); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * @file extend.js * @module extend */ /** * A combination of node inherits and babel's inherits (after transpile). * Both work the same but node adds `super_` to the subClass * and Bable adds the superClass as __proto__. Both seem useful. * * @param {Object} subClass * The class to inherit to * * @param {Object} superClass * The class to inherit from * * @private */ var _inherits = function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + (typeof superClass === 'undefined' ? 'undefined' : _typeof(superClass))); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) { // node subClass.super_ = superClass; } }; /** * Function for subclassing using the same inheritance that * videojs uses internally * * @param {Object} superClass * The class to inherit from * * @param {Object} [subClassMethods={}] * The class to inherit to * * @return {Object} * The new object with subClassMethods that inherited superClass. */ var extendFn = function extendFn(superClass) { var subClassMethods = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var subClass = function subClass() { superClass.apply(this, arguments); }; var methods = {}; if ((0, _obj.isObject)(subClassMethods)) { if (typeof subClassMethods.init === 'function') { _log2['default'].warn('Constructor logic via init() is deprecated; please use constructor() instead.'); subClassMethods.constructor = subClassMethods.init; } if (subClassMethods.constructor !== Object.prototype.constructor) { subClass = subClassMethods.constructor; } methods = subClassMethods; } else if (typeof subClassMethods === 'function') { subClass = subClassMethods; } _inherits(subClass, superClass); // Extend subObj's prototype with functions and other properties from props for (var name in methods) { if (methods.hasOwnProperty(name)) { subClass.prototype[name] = methods[name]; } } return subClass; }; exports['default'] = extendFn; },{"86":86,"88":88}],44:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _document = _dereq_(94); var _document2 = _interopRequireDefault(_document); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Store the browser-specific methods for the fullscreen API. * * @type {Object} * @see [Specification]{@link https://fullscreen.spec.whatwg.org} * @see [Map Approach From Screenfull.js]{@link https://github.com/sindresorhus/screenfull.js} */ var FullscreenApi = {}; // browser API methods /** * @file fullscreen-api.js * @module fullscreen-api * @private */ var apiMap = [['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror'], // WebKit ['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror'], // Old WebKit (Safari 5.1) ['webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitCurrentFullScreenElement', 'webkitCancelFullScreen', 'webkitfullscreenchange', 'webkitfullscreenerror'], // Mozilla ['mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror'], // Microsoft ['msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError']]; var specApi = apiMap[0]; var browserApi = void 0; // determine the supported set of functions for (var i = 0; i < apiMap.length; i++) { // check for exitFullscreen function if (apiMap[i][1] in _document2['default']) { browserApi = apiMap[i]; break; } } // map the browser API names to the spec API names if (browserApi) { for (var _i = 0; _i < browserApi.length; _i++) { FullscreenApi[specApi[_i]] = browserApi[_i]; } } exports['default'] = FullscreenApi; },{"94":94}],45:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file loading-spinner.js */ /** * A loading spinner for use during waiting/loading events. * * @extends Component */ var LoadingSpinner = function (_Component) { _inherits(LoadingSpinner, _Component); function LoadingSpinner() { _classCallCheck(this, LoadingSpinner); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } /** * Create the `LoadingSpinner`s DOM element. * * @return {Element} * The dom element that gets created. */ LoadingSpinner.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-loading-spinner', dir: 'ltr' }); }; return LoadingSpinner; }(_component2['default']); _component2['default'].registerComponent('LoadingSpinner', LoadingSpinner); exports['default'] = LoadingSpinner; },{"5":5}],46:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _obj = _dereq_(88); /** * A Custom `MediaError` class which mimics the standard HTML5 `MediaError` class. * * @param {number|string|Object|MediaError} value * This can be of multiple types: * - number: should be a standard error code * - string: an error message (the code will be 0) * - Object: arbitrary properties * - `MediaError` (native): used to populate a video.js `MediaError` object * - `MediaError` (video.js): will return itself if it's already a * video.js `MediaError` object. * * @see [MediaError Spec]{@link https://dev.w3.org/html5/spec-author-view/video.html#mediaerror} * @see [Encrypted MediaError Spec]{@link https://www.w3.org/TR/2013/WD-encrypted-media-20130510/#error-codes} * * @class MediaError */ function MediaError(value) { // Allow redundant calls to this constructor to avoid having `instanceof` // checks peppered around the code. if (value instanceof MediaError) { return value; } if (typeof value === 'number') { this.code = value; } else if (typeof value === 'string') { // default code is zero, so this is a custom error this.message = value; } else if ((0, _obj.isObject)(value)) { // We assign the `code` property manually because native `MediaError` objects // do not expose it as an own/enumerable property of the object. if (typeof value.code === 'number') { this.code = value.code; } (0, _obj.assign)(this, value); } if (!this.message) { this.message = MediaError.defaultMessages[this.code] || ''; } } /** * The error code that refers two one of the defined `MediaError` types * * @type {Number} */ /** * @file media-error.js */ MediaError.prototype.code = 0; /** * An optional message that to show with the error. Message is not part of the HTML5 * video spec but allows for more informative custom errors. * * @type {String} */ MediaError.prototype.message = ''; /** * An optional status code that can be set by plugins to allow even more detail about * the error. For example a plugin might provide a specific HTTP status code and an * error message for that code. Then when the plugin gets that error this class will * know how to display an error message for it. This allows a custom message to show * up on the `Player` error overlay. * * @type {Array} */ MediaError.prototype.status = null; /** * Errors indexed by the W3C standard. The order **CANNOT CHANGE**! See the * specification listed under {@link MediaError} for more information. * * @enum {array} * @readonly * @property {string} 0 - MEDIA_ERR_CUSTOM * @property {string} 1 - MEDIA_ERR_CUSTOM * @property {string} 2 - MEDIA_ERR_ABORTED * @property {string} 3 - MEDIA_ERR_NETWORK * @property {string} 4 - MEDIA_ERR_SRC_NOT_SUPPORTED * @property {string} 5 - MEDIA_ERR_ENCRYPTED */ MediaError.errorTypes = ['MEDIA_ERR_CUSTOM', 'MEDIA_ERR_ABORTED', 'MEDIA_ERR_NETWORK', 'MEDIA_ERR_DECODE', 'MEDIA_ERR_SRC_NOT_SUPPORTED', 'MEDIA_ERR_ENCRYPTED']; /** * The default `MediaError` messages based on the {@link MediaError.errorTypes}. * * @type {Array} * @constant */ MediaError.defaultMessages = { 1: 'You aborted the media playback', 2: 'A network error caused the media download to fail part-way.', 3: 'The media playback was aborted due to a corruption problem or because the media used features your browser did not support.', 4: 'The media could not be loaded, either because the server or network failed or because the format is not supported.', 5: 'The media is encrypted and we do not have the keys to decrypt it.' }; // Add types as properties on MediaError // e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4; for (var errNum = 0; errNum < MediaError.errorTypes.length; errNum++) { MediaError[MediaError.errorTypes[errNum]] = errNum; // values should be accessible on both the class and instance MediaError.prototype[MediaError.errorTypes[errNum]] = errNum; } // jsdocs for instance/static members added above // instance methods use `#` and static methods use `.` /** * W3C error code for any custom error. * * @member MediaError#MEDIA_ERR_CUSTOM * @constant {number} * @default 0 */ /** * W3C error code for any custom error. * * @member MediaError.MEDIA_ERR_CUSTOM * @constant {number} * @default 0 */ /** * W3C error code for media error aborted. * * @member MediaError#MEDIA_ERR_ABORTED * @constant {number} * @default 1 */ /** * W3C error code for media error aborted. * * @member MediaError.MEDIA_ERR_ABORTED * @constant {number} * @default 1 */ /** * W3C error code for any network error. * * @member MediaError#MEDIA_ERR_NETWORK * @constant {number} * @default 2 */ /** * W3C error code for any network error. * * @member MediaError.MEDIA_ERR_NETWORK * @constant {number} * @default 2 */ /** * W3C error code for any decoding error. * * @member MediaError#MEDIA_ERR_DECODE * @constant {number} * @default 3 */ /** * W3C error code for any decoding error. * * @member MediaError.MEDIA_ERR_DECODE * @constant {number} * @default 3 */ /** * W3C error code for any time that a source is not supported. * * @member MediaError#MEDIA_ERR_SRC_NOT_SUPPORTED * @constant {number} * @default 4 */ /** * W3C error code for any time that a source is not supported. * * @member MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED * @constant {number} * @default 4 */ /** * W3C error code for any time that a source is encrypted. * * @member MediaError#MEDIA_ERR_ENCRYPTED * @constant {number} * @default 5 */ /** * W3C error code for any time that a source is encrypted. * * @member MediaError.MEDIA_ERR_ENCRYPTED * @constant {number} * @default 5 */ exports['default'] = MediaError; },{"88":88}],47:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _clickableComponent = _dereq_(3); var _clickableComponent2 = _interopRequireDefault(_clickableComponent); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _menu = _dereq_(49); var _menu2 = _interopRequireDefault(_menu); var _dom = _dereq_(81); var Dom = _interopRequireWildcard(_dom); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); var _toTitleCase = _dereq_(91); var _toTitleCase2 = _interopRequireDefault(_toTitleCase); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file menu-button.js */ /** * A `MenuButton` class for any popup {@link Menu}. * * @extends ClickableComponent */ var MenuButton = function (_ClickableComponent) { _inherits(MenuButton, _ClickableComponent); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options={}] * The key/value store of player options. */ function MenuButton(player) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; _classCallCheck(this, MenuButton); var _this = _possibleConstructorReturn(this, _ClickableComponent.call(this, player, options)); _this.update(); _this.enabled_ = true; _this.el_.setAttribute('aria-haspopup', 'true'); _this.el_.setAttribute('role', 'menuitem'); _this.on('keydown', _this.handleSubmenuKeyPress); return _this; } /** * Update the menu based on the current state of its items. */ MenuButton.prototype.update = function update() { var menu = this.createMenu(); if (this.menu) { this.removeChild(this.menu); } this.menu = menu; this.addChild(menu); /** * Track the state of the menu button * * @type {Boolean} * @private */ this.buttonPressed_ = false; this.el_.setAttribute('aria-expanded', 'false'); if (this.items && this.items.length <= this.hideThreshold_) { this.hide(); } else { this.show(); } }; /** * Create the menu and add all items to it. * * @return {Menu} * The constructed menu */ MenuButton.prototype.createMenu = function createMenu() { var menu = new _menu2['default'](this.player_); /** * Hide the menu if the number of items is less than or equal to this threshold. This defaults * to 0 and whenever we add items which can be hidden to the menu we'll increment it. We list * it here because every time we run `createMenu` we need to reset the value. * * @protected * @type {Number} */ this.hideThreshold_ = 0; // Add a title list item to the top if (this.options_.title) { var title = Dom.createEl('li', { className: 'vjs-menu-title', innerHTML: (0, _toTitleCase2['default'])(this.options_.title), tabIndex: -1 }); this.hideThreshold_ += 1; menu.children_.unshift(title); Dom.insertElFirst(title, menu.contentEl()); } this.items = this.createItems(); if (this.items) { // Add menu items to the menu for (var i = 0; i < this.items.length; i++) { menu.addItem(this.items[i]); } } return menu; }; /** * Create the list of menu items. Specific to each subclass. * * @abstract */ MenuButton.prototype.createItems = function createItems() {}; /** * Create the `MenuButtons`s DOM element. * * @return {Element} * The element that gets created. */ MenuButton.prototype.createEl = function createEl() { return _ClickableComponent.prototype.createEl.call(this, 'div', { className: this.buildCSSClass() }); }; /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ MenuButton.prototype.buildCSSClass = function buildCSSClass() { var menuButtonClass = 'vjs-menu-button'; // If the inline option is passed, we want to use different styles altogether. if (this.options_.inline === true) { menuButtonClass += '-inline'; } else { menuButtonClass += '-popup'; } return 'vjs-menu-button ' + menuButtonClass + ' ' + _ClickableComponent.prototype.buildCSSClass.call(this); }; /** * Handle a click on a `MenuButton`. * See {@link ClickableComponent#handleClick} for instances where this is called. * * @param {EventTarget~Event} event * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ MenuButton.prototype.handleClick = function handleClick(event) { // When you click the button it adds focus, which will show the menu. // So we'll remove focus when the mouse leaves the button. Focus is needed // for tab navigation. this.one(this.menu.contentEl(), 'mouseleave', Fn.bind(this, function (e) { this.unpressButton(); this.el_.blur(); })); if (this.buttonPressed_) { this.unpressButton(); } else { this.pressButton(); } }; /** * Handle tab, escape, down arrow, and up arrow keys for `MenuButton`. See * {@link ClickableComponent#handleKeyPress} for instances where this is called. * * @param {EventTarget~Event} event * The `keydown` event that caused this function to be called. * * @listens keydown */ MenuButton.prototype.handleKeyPress = function handleKeyPress(event) { // Escape (27) key or Tab (9) key unpress the 'button' if (event.which === 27 || event.which === 9) { if (this.buttonPressed_) { this.unpressButton(); } // Don't preventDefault for Tab key - we still want to lose focus if (event.which !== 9) { event.preventDefault(); } // Up (38) key or Down (40) key press the 'button' } else if (event.which === 38 || event.which === 40) { if (!this.buttonPressed_) { this.pressButton(); event.preventDefault(); } } else { _ClickableComponent.prototype.handleKeyPress.call(this, event); } }; /** * Handle a `keydown` event on a sub-menu. The listener for this is added in * the constructor. * * @param {EventTarget~Event} event * Key press event * * @listens keydown */ MenuButton.prototype.handleSubmenuKeyPress = function handleSubmenuKeyPress(event) { // Escape (27) key or Tab (9) key unpress the 'button' if (event.which === 27 || event.which === 9) { if (this.buttonPressed_) { this.unpressButton(); } // Don't preventDefault for Tab key - we still want to lose focus if (event.which !== 9) { event.preventDefault(); } } }; /** * Put the current `MenuButton` into a pressed state. */ MenuButton.prototype.pressButton = function pressButton() { if (this.enabled_) { this.buttonPressed_ = true; this.menu.lockShowing(); this.el_.setAttribute('aria-expanded', 'true'); // set the focus into the submenu this.menu.focus(); } }; /** * Take the current `MenuButton` out of a pressed state. */ MenuButton.prototype.unpressButton = function unpressButton() { if (this.enabled_) { this.buttonPressed_ = false; this.menu.unlockShowing(); this.el_.setAttribute('aria-expanded', 'false'); // Set focus back to this menu button this.el_.focus(); } }; /** * Disable the `MenuButton`. Don't allow it to be clicked. * * @return {MenuButton} * Returns itself; method can be chained. */ MenuButton.prototype.disable = function disable() { // Unpress, but don't force focus on this button this.buttonPressed_ = false; this.menu.unlockShowing(); this.el_.setAttribute('aria-expanded', 'false'); this.enabled_ = false; return _ClickableComponent.prototype.disable.call(this); }; /** * Enable the `MenuButton`. Allow it to be clicked. * * @return {MenuButton} * Returns itself; method can be chained. */ MenuButton.prototype.enable = function enable() { this.enabled_ = true; return _ClickableComponent.prototype.enable.call(this); }; return MenuButton; }(_clickableComponent2['default']); _component2['default'].registerComponent('MenuButton', MenuButton); exports['default'] = MenuButton; },{"3":3,"49":49,"5":5,"81":81,"83":83,"91":91}],48:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _clickableComponent = _dereq_(3); var _clickableComponent2 = _interopRequireDefault(_clickableComponent); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _obj = _dereq_(88); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file menu-item.js */ /** * The component for a menu item. `<li>` * * @extends ClickableComponent */ var MenuItem = function (_ClickableComponent) { _inherits(MenuItem, _ClickableComponent); /** * Creates an instance of the this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options={}] * The key/value store of player options. * */ function MenuItem(player, options) { _classCallCheck(this, MenuItem); var _this = _possibleConstructorReturn(this, _ClickableComponent.call(this, player, options)); _this.selectable = options.selectable; _this.selected(options.selected); if (_this.selectable) { // TODO: May need to be either menuitemcheckbox or menuitemradio, // and may need logical grouping of menu items. _this.el_.setAttribute('role', 'menuitemcheckbox'); } else { _this.el_.setAttribute('role', 'menuitem'); } return _this; } /** * Create the `MenuItem's DOM element * * @param {string} [type=li] * Element's node type, not actually used, always set to `li`. * * @param {Object} [props={}] * An object of properties that should be set on the element * * @param {Object} [attrs={}] * An object of attributes that should be set on the element * * @return {Element} * The element that gets created. */ MenuItem.prototype.createEl = function createEl(type, props, attrs) { // The control is textual, not just an icon this.nonIconControl = true; return _ClickableComponent.prototype.createEl.call(this, 'li', (0, _obj.assign)({ className: 'vjs-menu-item', innerHTML: this.localize(this.options_.label), tabIndex: -1 }, props), attrs); }; /** * Any click on a `MenuItem` puts int into the selected state. * See {@link ClickableComponent#handleClick} for instances where this is called. * * @param {EventTarget~Event} event * The `keydown`, `tap`, or `click` event that caused this function to be * called. * * @listens tap * @listens click */ MenuItem.prototype.handleClick = function handleClick(event) { this.selected(true); }; /** * Set the state for this menu item as selected or not. * * @param {boolean} selected * if the menu item is selected or not */ MenuItem.prototype.selected = function selected(_selected) { if (this.selectable) { if (_selected) { this.addClass('vjs-selected'); this.el_.setAttribute('aria-checked', 'true'); // aria-checked isn't fully supported by browsers/screen readers, // so indicate selected state to screen reader in the control text. this.controlText(', selected'); } else { this.removeClass('vjs-selected'); this.el_.setAttribute('aria-checked', 'false'); // Indicate un-selected state to screen reader // Note that a space clears out the selected state text this.controlText(' '); } } }; return MenuItem; }(_clickableComponent2['default']); _component2['default'].registerComponent('MenuItem', MenuItem); exports['default'] = MenuItem; },{"3":3,"5":5,"88":88}],49:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(81); var Dom = _interopRequireWildcard(_dom); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); var _events = _dereq_(82); var Events = _interopRequireWildcard(_events); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file menu.js */ /** * The Menu component is used to build popup menus, including subtitle and * captions selection menus. * * @extends Component */ var Menu = function (_Component) { _inherits(Menu, _Component); /** * Create an instance of this class. * * @param {Player} player * the player that this component should attach to * * @param {Object} [options] * Object of option names and values * */ function Menu(player, options) { _classCallCheck(this, Menu); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.focusedChild_ = -1; _this.on('keydown', _this.handleKeyPress); return _this; } /** * Add a {@link MenuItem} to the menu. * * @param {Object|string} component * The name or instance of the `MenuItem` to add. * */ Menu.prototype.addItem = function addItem(component) { this.addChild(component); component.on('click', Fn.bind(this, function (event) { this.unlockShowing(); // TODO: Need to set keyboard focus back to the menuButton })); }; /** * Create the `Menu`s DOM element. * * @return {Element} * the element that was created */ Menu.prototype.createEl = function createEl() { var contentElType = this.options_.contentElType || 'ul'; this.contentEl_ = Dom.createEl(contentElType, { className: 'vjs-menu-content' }); this.contentEl_.setAttribute('role', 'menu'); var el = _Component.prototype.createEl.call(this, 'div', { append: this.contentEl_, className: 'vjs-menu' }); el.setAttribute('role', 'presentation'); el.appendChild(this.contentEl_); // Prevent clicks from bubbling up. Needed for Menu Buttons, // where a click on the parent is significant Events.on(el, 'click', function (event) { event.preventDefault(); event.stopImmediatePropagation(); }); return el; }; /** * Handle a `keydown` event on this menu. This listener is added in the constructor. * * @param {EventTarget~Event} event * A `keydown` event that happened on the menu. * * @listens keydown */ Menu.prototype.handleKeyPress = function handleKeyPress(event) { // Left and Down Arrows if (event.which === 37 || event.which === 40) { event.preventDefault(); this.stepForward(); // Up and Right Arrows } else if (event.which === 38 || event.which === 39) { event.preventDefault(); this.stepBack(); } }; /** * Move to next (lower) menu item for keyboard users. */ Menu.prototype.stepForward = function stepForward() { var stepChild = 0; if (this.focusedChild_ !== undefined) { stepChild = this.focusedChild_ + 1; } this.focus(stepChild); }; /** * Move to previous (higher) menu item for keyboard users. */ Menu.prototype.stepBack = function stepBack() { var stepChild = 0; if (this.focusedChild_ !== undefined) { stepChild = this.focusedChild_ - 1; } this.focus(stepChild); }; /** * Set focus on a {@link MenuItem} in the `Menu`. * * @param {Object|string} [item=0] * Index of child item set focus on. */ Menu.prototype.focus = function focus() { var item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var children = this.children().slice(); var haveTitle = children.length && children[0].className && /vjs-menu-title/.test(children[0].className); if (haveTitle) { children.shift(); } if (children.length > 0) { if (item < 0) { item = 0; } else if (item >= children.length) { item = children.length - 1; } this.focusedChild_ = item; children[item].el_.focus(); } }; return Menu; }(_component2['default']); _component2['default'].registerComponent('Menu', Menu); exports['default'] = Menu; },{"5":5,"81":81,"82":82,"83":83}],50:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _dom = _dereq_(81); var Dom = _interopRequireWildcard(_dom); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file modal-dialog.js */ var MODAL_CLASS_NAME = 'vjs-modal-dialog'; var ESC = 27; /** * The `ModalDialog` displays over the video and its controls, which blocks * interaction with the player until it is closed. * * Modal dialogs include a "Close" button and will close when that button * is activated - or when ESC is pressed anywhere. * * @extends Component */ var ModalDialog = function (_Component) { _inherits(ModalDialog, _Component); /** * Create an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. * * @param {Mixed} [options.content=undefined] * Provide customized content for this modal. * * @param {string} [options.description] * A text description for the modal, primarily for accessibility. * * @param {boolean} [options.fillAlways=false] * Normally, modals are automatically filled only the first time * they open. This tells the modal to refresh its content * every time it opens. * * @param {string} [options.label] * A text label for the modal, primarily for accessibility. * * @param {boolean} [options.temporary=true] * If `true`, the modal can only be opened once; it will be * disposed as soon as it's closed. * * @param {boolean} [options.uncloseable=false] * If `true`, the user will not be able to close the modal * through the UI in the normal ways. Programmatic closing is * still possible. */ function ModalDialog(player, options) { _classCallCheck(this, ModalDialog); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.opened_ = _this.hasBeenOpened_ = _this.hasBeenFilled_ = false; _this.closeable(!_this.options_.uncloseable); _this.content(_this.options_.content); // Make sure the contentEl is defined AFTER any children are initialized // because we only want the contents of the modal in the contentEl // (not the UI elements like the close button). _this.contentEl_ = Dom.createEl('div', { className: MODAL_CLASS_NAME + '-content' }, { role: 'document' }); _this.descEl_ = Dom.createEl('p', { className: MODAL_CLASS_NAME + '-description vjs-offscreen', id: _this.el().getAttribute('aria-describedby') }); Dom.textContent(_this.descEl_, _this.description()); _this.el_.appendChild(_this.descEl_); _this.el_.appendChild(_this.contentEl_); return _this; } /** * Create the `ModalDialog`'s DOM element * * @return {Element} * The DOM element that gets created. */ ModalDialog.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: this.buildCSSClass(), tabIndex: -1 }, { 'aria-describedby': this.id() + '_description', 'aria-hidden': 'true', 'aria-label': this.label(), 'role': 'dialog' }); }; /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ ModalDialog.prototype.buildCSSClass = function buildCSSClass() { return MODAL_CLASS_NAME + ' vjs-hidden ' + _Component.prototype.buildCSSClass.call(this); }; /** * Handles `keydown` events on the document, looking for ESC, which closes * the modal. * * @param {EventTarget~Event} e * The keypress that triggered this event. * * @listens keydown */ ModalDialog.prototype.handleKeyPress = function handleKeyPress(e) { if (e.which === ESC && this.closeable()) { this.close(); } }; /** * Returns the label string for this modal. Primarily used for accessibility. * * @return {string} * the localized or raw label of this modal. */ ModalDialog.prototype.label = function label() { return this.options_.label || this.localize('Modal Window'); }; /** * Returns the description string for this modal. Primarily used for * accessibility. * * @return {string} * The localized or raw description of this modal. */ ModalDialog.prototype.description = function description() { var desc = this.options_.description || this.localize('This is a modal window.'); // Append a universal closeability message if the modal is closeable. if (this.closeable()) { desc += ' ' + this.localize('This modal can be closed by pressing the Escape key or activating the close button.'); } return desc; }; /** * Opens the modal. * * @fires ModalDialog#beforemodalopen * @fires ModalDialog#modalopen * * @return {ModalDialog} * Returns itself; method can be chained. */ ModalDialog.prototype.open = function open() { if (!this.opened_) { var player = this.player(); /** * Fired just before a `ModalDialog` is opened. * * @event ModalDialog#beforemodalopen * @type {EventTarget~Event} */ this.trigger('beforemodalopen'); this.opened_ = true; // Fill content if the modal has never opened before and // never been filled. if (this.options_.fillAlways || !this.hasBeenOpened_ && !this.hasBeenFilled_) { this.fill(); } // If the player was playing, pause it and take note of its previously // playing state. this.wasPlaying_ = !player.paused(); if (this.options_.pauseOnOpen && this.wasPlaying_) { player.pause(); } if (this.closeable()) { this.on(this.el_.ownerDocument, 'keydown', Fn.bind(this, this.handleKeyPress)); } player.controls(false); this.show(); this.el().setAttribute('aria-hidden', 'false'); /** * Fired just after a `ModalDialog` is opened. * * @event ModalDialog#modalopen * @type {EventTarget~Event} */ this.trigger('modalopen'); this.hasBeenOpened_ = true; } return this; }; /** * If the `ModalDialog` is currently open or closed. * * @param {boolean} [value] * If given, it will open (`true`) or close (`false`) the modal. * * @return {boolean} * the current open state of the modaldialog */ ModalDialog.prototype.opened = function opened(value) { if (typeof value === 'boolean') { this[value ? 'open' : 'close'](); } return this.opened_; }; /** * Closes the modal, does nothing if the `ModalDialog` is * not open. * * @fires ModalDialog#beforemodalclose * @fires ModalDialog#modalclose * * @return {ModalDialog} * Returns itself; method can be chained. */ ModalDialog.prototype.close = function close() { if (this.opened_) { var player = this.player(); /** * Fired just before a `ModalDialog` is closed. * * @event ModalDialog#beforemodalclose * @type {EventTarget~Event} */ this.trigger('beforemodalclose'); this.opened_ = false; if (this.wasPlaying_ && this.options_.pauseOnOpen) { player.play(); } if (this.closeable()) { this.off(this.el_.ownerDocument, 'keydown', Fn.bind(this, this.handleKeyPress)); } player.controls(true); this.hide(); this.el().setAttribute('aria-hidden', 'true'); /** * Fired just after a `ModalDialog` is closed. * * @event ModalDialog#modalclose * @type {EventTarget~Event} */ this.trigger('modalclose'); if (this.options_.temporary) { this.dispose(); } } return this; }; /** * Check to see if the `ModalDialog` is closeable via the UI. * * @param {boolean} [value] * If given as a boolean, it will set the `closeable` option. * * @return {boolean} * Returns the final value of the closable option. */ ModalDialog.prototype.closeable = function closeable(value) { if (typeof value === 'boolean') { var closeable = this.closeable_ = !!value; var close = this.getChild('closeButton'); // If this is being made closeable and has no close button, add one. if (closeable && !close) { // The close button should be a child of the modal - not its // content element, so temporarily change the content element. var temp = this.contentEl_; this.contentEl_ = this.el_; close = this.addChild('closeButton', { controlText: 'Close Modal Dialog' }); this.contentEl_ = temp; this.on(close, 'close', this.close); } // If this is being made uncloseable and has a close button, remove it. if (!closeable && close) { this.off(close, 'close', this.close); this.removeChild(close); close.dispose(); } } return this.closeable_; }; /** * Fill the modal's content element with the modal's "content" option. * The content element will be emptied before this change takes place. * * @return {ModalDialog} * Returns itself; method can be chained. */ ModalDialog.prototype.fill = function fill() { return this.fillWith(this.content()); }; /** * Fill the modal's content element with arbitrary content. * The content element will be emptied before this change takes place. * * @fires ModalDialog#beforemodalfill * @fires ModalDialog#modalfill * * @param {Mixed} [content] * The same rules apply to this as apply to the `content` option. * * @return {ModalDialog} * Returns itself; method can be chained. */ ModalDialog.prototype.fillWith = function fillWith(content) { var contentEl = this.contentEl(); var parentEl = contentEl.parentNode; var nextSiblingEl = contentEl.nextSibling; /** * Fired just before a `ModalDialog` is filled with content. * * @event ModalDialog#beforemodalfill * @type {EventTarget~Event} */ this.trigger('beforemodalfill'); this.hasBeenFilled_ = true; // Detach the content element from the DOM before performing // manipulation to avoid modifying the live DOM multiple times. parentEl.removeChild(contentEl); this.empty(); Dom.insertContent(contentEl, content); /** * Fired just after a `ModalDialog` is filled with content. * * @event ModalDialog#modalfill * @type {EventTarget~Event} */ this.trigger('modalfill'); // Re-inject the re-filled content element. if (nextSiblingEl) { parentEl.insertBefore(contentEl, nextSiblingEl); } else { parentEl.appendChild(contentEl); } return this; }; /** * Empties the content element. This happens anytime the modal is filled. * * @fires ModalDialog#beforemodalempty * @fires ModalDialog#modalempty * * @return {ModalDialog} * Returns itself; method can be chained. */ ModalDialog.prototype.empty = function empty() { /** * Fired just before a `ModalDialog` is emptied. * * @event ModalDialog#beforemodalempty * @type {EventTarget~Event} */ this.trigger('beforemodalempty'); Dom.emptyEl(this.contentEl()); /** * Fired just after a `ModalDialog` is emptied. * * @event ModalDialog#modalempty * @type {EventTarget~Event} */ this.trigger('modalempty'); return this; }; /** * Gets or sets the modal content, which gets normalized before being * rendered into the DOM. * * This does not update the DOM or fill the modal, but it is called during * that process. * * @param {Mixed} [value] * If defined, sets the internal content value to be used on the * next call(s) to `fill`. This value is normalized before being * inserted. To "clear" the internal content value, pass `null`. * * @return {Mixed} * The current content of the modal dialog */ ModalDialog.prototype.content = function content(value) { if (typeof value !== 'undefined') { this.content_ = value; } return this.content_; }; return ModalDialog; }(_component2['default']); /** * Default options for `ModalDialog` default options. * * @type {Object} * @private */ ModalDialog.prototype.options_ = { pauseOnOpen: true, temporary: true }; _component2['default'].registerComponent('ModalDialog', ModalDialog); exports['default'] = ModalDialog; },{"5":5,"81":81,"83":83}],51:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _document = _dereq_(94); var _document2 = _interopRequireDefault(_document); var _window = _dereq_(95); var _window2 = _interopRequireDefault(_window); var _events = _dereq_(82); var Events = _interopRequireWildcard(_events); var _dom = _dereq_(81); var Dom = _interopRequireWildcard(_dom); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); var _guid = _dereq_(85); var Guid = _interopRequireWildcard(_guid); var _browser = _dereq_(78); var browser = _interopRequireWildcard(_browser); var _log = _dereq_(86); var _log2 = _interopRequireDefault(_log); var _toTitleCase = _dereq_(91); var _toTitleCase2 = _interopRequireDefault(_toTitleCase); var _timeRanges = _dereq_(90); var _buffer = _dereq_(79); var _stylesheet = _dereq_(89); var stylesheet = _interopRequireWildcard(_stylesheet); var _fullscreenApi = _dereq_(44); var _fullscreenApi2 = _interopRequireDefault(_fullscreenApi); var _mediaError = _dereq_(46); var _mediaError2 = _interopRequireDefault(_mediaError); var _tuple = _dereq_(97); var _tuple2 = _interopRequireDefault(_tuple); var _obj = _dereq_(88); var _mergeOptions = _dereq_(87); var _mergeOptions2 = _interopRequireDefault(_mergeOptions); var _textTrackListConverter = _dereq_(69); var _textTrackListConverter2 = _interopRequireDefault(_textTrackListConverter); var _modalDialog = _dereq_(50); var _modalDialog2 = _interopRequireDefault(_modalDialog); var _tech = _dereq_(62); var _tech2 = _interopRequireDefault(_tech); var _audioTrackList = _dereq_(63); var _audioTrackList2 = _interopRequireDefault(_audioTrackList); var _videoTrackList = _dereq_(76); var _videoTrackList2 = _interopRequireDefault(_videoTrackList); _dereq_(61); _dereq_(59); _dereq_(55); _dereq_(68); _dereq_(45); _dereq_(1); _dereq_(4); _dereq_(8); _dereq_(41); _dereq_(71); _dereq_(60); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file player.js */ // Subclasses Component // The following imports are used only to ensure that the corresponding modules // are always included in the video.js package. Importing the modules will // execute them and they will register themselves with video.js. // Import Html5 tech, at least for disposing the original video tag. // The following tech events are simply re-triggered // on the player when they happen var TECH_EVENTS_RETRIGGER = [ /** * Fired while the user agent is downloading media data. * * @event Player#progress * @type {EventTarget~Event} */ /** * Retrigger the `progress` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechProgress_ * @fires Player#progress * @listens Tech#progress */ 'progress', /** * Fires when the loading of an audio/video is aborted. * * @event Player#abort * @type {EventTarget~Event} */ /** * Retrigger the `abort` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechAbort_ * @fires Player#abort * @listens Tech#abort */ 'abort', /** * Fires when the browser is intentionally not getting media data. * * @event Player#suspend * @type {EventTarget~Event} */ /** * Retrigger the `suspend` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechSuspend_ * @fires Player#suspend * @listens Tech#suspend */ 'suspend', /** * Fires when the current playlist is empty. * * @event Player#emptied * @type {EventTarget~Event} */ /** * Retrigger the `emptied` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechEmptied_ * @fires Player#emptied * @listens Tech#emptied */ 'emptied', /** * Fires when the browser is trying to get media data, but data is not available. * * @event Player#stalled * @type {EventTarget~Event} */ /** * Retrigger the `stalled` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechStalled_ * @fires Player#stalled * @listens Tech#stalled */ 'stalled', /** * Fires when the browser has loaded meta data for the audio/video. * * @event Player#loadedmetadata * @type {EventTarget~Event} */ /** * Retrigger the `stalled` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechLoadedmetadata_ * @fires Player#loadedmetadata * @listens Tech#loadedmetadata */ 'loadedmetadata', /** * Fires when the browser has loaded the current frame of the audio/video. * * @event player#loadeddata * @type {event} */ /** * Retrigger the `loadeddata` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechLoaddeddata_ * @fires Player#loadeddata * @listens Tech#loadeddata */ 'loadeddata', /** * Fires when the current playback position has changed. * * @event player#timeupdate * @type {event} */ /** * Retrigger the `timeupdate` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechTimeUpdate_ * @fires Player#timeupdate * @listens Tech#timeupdate */ 'timeupdate', /** * Fires when the playing speed of the audio/video is changed * * @event player#ratechange * @type {event} */ /** * Retrigger the `ratechange` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechRatechange_ * @fires Player#ratechange * @listens Tech#ratechange */ 'ratechange', /** * Fires when the volume has been changed * * @event player#volumechange * @type {event} */ /** * Retrigger the `volumechange` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechVolumechange_ * @fires Player#volumechange * @listens Tech#volumechange */ 'volumechange', /** * Fires when the text track has been changed * * @event player#texttrackchange * @type {event} */ /** * Retrigger the `texttrackchange` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechTexttrackchange_ * @fires Player#texttrackchange * @listens Tech#texttrackchange */ 'texttrackchange']; /** * An instance of the `Player` class is created when any of the Video.js setup methods * are used to initialize a video. * * After an instance has been created it can be accessed globally in two ways: * 1. By calling `videojs('example_video_1');` * 2. By using it directly via `videojs.players.example_video_1;` * * @extends Component */ var Player = function (_Component) { _inherits(Player, _Component); /** * Create an instance of this class. * * @param {Element} tag * The original video DOM element used for configuring options. * * @param {Object} [options] * Object of option names and values. * * @param {Component~ReadyCallback} [ready] * Ready callback function. */ function Player(tag, options, ready) { _classCallCheck(this, Player); // Make sure tag ID exists tag.id = tag.id || 'vjs_video_' + Guid.newGUID(); // Set Options // The options argument overrides options set in the video tag // which overrides globally set options. // This latter part coincides with the load order // (tag must exist before Player) options = (0, _obj.assign)(Player.getTagSettings(tag), options); // Delay the initialization of children because we need to set up // player properties first, and can't use `this` before `super()` options.initChildren = false; // Same with creating the element options.createEl = false; // we don't want the player to report touch activity on itself // see enableTouchActivity in Component options.reportTouchActivity = false; // If language is not set, get the closest lang attribute if (!options.language) { if (typeof tag.closest === 'function') { var closest = tag.closest('[lang]'); if (closest) { options.language = closest.getAttribute('lang'); } } else { var element = tag; while (element && element.nodeType === 1) { if (Dom.getElAttributes(element).hasOwnProperty('lang')) { options.language = element.getAttribute('lang'); break; } element = element.parentNode; } } } // Run base component initializing with new options // if the global option object was accidentally blown away by // someone, bail early with an informative error var _this = _possibleConstructorReturn(this, _Component.call(this, null, options, ready)); if (!_this.options_ || !_this.options_.techOrder || !_this.options_.techOrder.length) { throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?'); } // Store the original tag used to set options _this.tag = tag; // Store the tag attributes used to restore html5 element _this.tagAttributes = tag && Dom.getElAttributes(tag); // Update current language _this.language(_this.options_.language); // Update Supported Languages if (options.languages) { // Normalise player option languages to lowercase var languagesToLower = {}; Object.getOwnPropertyNames(options.languages).forEach(function (name) { languagesToLower[name.toLowerCase()] = options.languages[name]; }); _this.languages_ = languagesToLower; } else { _this.languages_ = Player.prototype.options_.languages; } // Cache for video property values. _this.cache_ = {}; // Set poster _this.poster_ = options.poster || ''; // Set controls _this.controls_ = !!options.controls; // Original tag settings stored in options // now remove immediately so native controls don't flash. // May be turned back on by HTML5 tech if nativeControlsForTouch is true tag.controls = false; /* * Store the internal state of scrubbing * * @private * @return {Boolean} True if the user is scrubbing */ _this.scrubbing_ = false; _this.el_ = _this.createEl(); // We also want to pass the original player options to each component and plugin // as well so they don't need to reach back into the player for options later. // We also need to do another copy of this.options_ so we don't end up with // an infinite loop. var playerOptionsCopy = (0, _mergeOptions2['default'])(_this.options_); // Load plugins if (options.plugins) { var plugins = options.plugins; Object.getOwnPropertyNames(plugins).forEach(function (name) { if (typeof this[name] === 'function') { this[name](plugins[name]); } else { _log2['default'].error('Unable to find plugin:', name); } }, _this); } _this.options_.playerOptions = playerOptionsCopy; _this.initChildren(); // Set isAudio based on whether or not an audio tag was used _this.isAudio(tag.nodeName.toLowerCase() === 'audio'); // Update controls className. Can't do this when the controls are initially // set because the element doesn't exist yet. if (_this.controls()) { _this.addClass('vjs-controls-enabled'); } else { _this.addClass('vjs-controls-disabled'); } // Set ARIA label and region role depending on player type _this.el_.setAttribute('role', 'region'); if (_this.isAudio()) { _this.el_.setAttribute('aria-label', 'audio player'); } else { _this.el_.setAttribute('aria-label', 'video player'); } if (_this.isAudio()) { _this.addClass('vjs-audio'); } if (_this.flexNotSupported_()) { _this.addClass('vjs-no-flex'); } // TODO: Make this smarter. Toggle user state between touching/mousing // using events, since devices can have both touch and mouse events. // if (browser.TOUCH_ENABLED) { // this.addClass('vjs-touch-enabled'); // } // iOS Safari has broken hover handling if (!browser.IS_IOS) { _this.addClass('vjs-workinghover'); } // Make player easily findable by ID Player.players[_this.id_] = _this; // When the player is first initialized, trigger activity so components // like the control bar show themselves if needed _this.userActive(true); _this.reportUserActivity(); _this.listenForUserActivity_(); _this.on('fullscreenchange', _this.handleFullscreenChange_); _this.on('stageclick', _this.handleStageClick_); return _this; } /** * Destroys the video player and does any necessary cleanup. * * This is especially helpful if you are dynamically adding and removing videos * to/from the DOM. * * @fires Player#dispose */ Player.prototype.dispose = function dispose() { /** * Called when the player is being disposed of. * * @event Player#dispose * @type {EventTarget~Event} */ this.trigger('dispose'); // prevent dispose from being called twice this.off('dispose'); if (this.styleEl_ && this.styleEl_.parentNode) { this.styleEl_.parentNode.removeChild(this.styleEl_); } // Kill reference to this player Player.players[this.id_] = null; if (this.tag && this.tag.player) { this.tag.player = null; } if (this.el_ && this.el_.player) { this.el_.player = null; } if (this.tech_) { this.tech_.dispose(); } _Component.prototype.dispose.call(this); }; /** * Create the `Player`'s DOM element. * * @return {Element} * The DOM element that gets created. */ Player.prototype.createEl = function createEl() { var tag = this.tag; var el = void 0; var playerElIngest = this.playerElIngest_ = tag.parentNode && tag.parentNode.hasAttribute && tag.parentNode.hasAttribute('data-vjs-player'); if (playerElIngest) { el = this.el_ = tag.parentNode; } else { el = this.el_ = _Component.prototype.createEl.call(this, 'div'); } // set tabindex to -1 so we could focus on the player element tag.setAttribute('tabindex', '-1'); // Remove width/height attrs from tag so CSS can make it 100% width/height tag.removeAttribute('width'); tag.removeAttribute('height'); // Copy over all the attributes from the tag, including ID and class // ID will now reference player box, not the video tag var attrs = Dom.getElAttributes(tag); Object.getOwnPropertyNames(attrs).forEach(function (attr) { // workaround so we don't totally break IE7 // http://stackoverflow.com/questions/3653444/css-styles-not-applied-on-dynamic-elements-in-internet-explorer-7 if (attr === 'class') { el.className += ' ' + attrs[attr]; } else { el.setAttribute(attr, attrs[attr]); } }); // Update tag id/class for use as HTML5 playback tech // Might think we should do this after embedding in container so .vjs-tech class // doesn't flash 100% width/height, but class only applies with .video-js parent tag.playerId = tag.id; tag.id += '_html5_api'; tag.className = 'vjs-tech'; // Make player findable on elements tag.player = el.player = this; // Default state of video is paused this.addClass('vjs-paused'); // Add a style element in the player that we'll use to set the width/height // of the player in a way that's still overrideable by CSS, just like the // video element if (_window2['default'].VIDEOJS_NO_DYNAMIC_STYLE !== true) { this.styleEl_ = stylesheet.createStyleElement('vjs-styles-dimensions'); var defaultsStyleEl = Dom.$('.vjs-styles-defaults'); var head = Dom.$('head'); head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild); } // Pass in the width/height/aspectRatio options which will update the style el this.width(this.options_.width); this.height(this.options_.height); this.fluid(this.options_.fluid); this.aspectRatio(this.options_.aspectRatio); // Hide any links within the video/audio tag, because IE doesn't hide them completely. var links = tag.getElementsByTagName('a'); for (var i = 0; i < links.length; i++) { var linkEl = links.item(i); Dom.addElClass(linkEl, 'vjs-hidden'); linkEl.setAttribute('hidden', 'hidden'); } // insertElFirst seems to cause the networkState to flicker from 3 to 2, so // keep track of the original for later so we can know if the source originally failed tag.initNetworkState_ = tag.networkState; // Wrap video tag in div (el/box) container if (tag.parentNode && !playerElIngest) { tag.parentNode.insertBefore(el, tag); } // insert the tag as the first child of the player element // then manually add it to the children array so that this.addChild // will work properly for other components // // Breaks iPhone, fixed in HTML5 setup. Dom.insertElFirst(tag, el); this.children_.unshift(tag); this.el_ = el; return el; }; /** * A getter/setter for the `Player`'s width. * * @param {number} [value] * The value to set the `Player's width to. * * @return {number} * The current width of the `Player`. */ Player.prototype.width = function width(value) { return this.dimension('width', value); }; /** * A getter/setter for the `Player`'s height. * * @param {number} [value] * The value to set the `Player's heigth to. * * @return {number} * The current heigth of the `Player`. */ Player.prototype.height = function height(value) { return this.dimension('height', value); }; /** * A getter/setter for the `Player`'s width & height. * * @param {string} dimension * This string can be: * - 'width' * - 'height' * * @param {number} [value] * Value for dimension specified in the first argument. * * @return {Player|number} * - Returns itself when setting; method can be chained. * - The dimension arguments value when getting (width/height). */ Player.prototype.dimension = function dimension(_dimension, value) { var privDimension = _dimension + '_'; if (value === undefined) { return this[privDimension] || 0; } if (value === '') { // If an empty string is given, reset the dimension to be automatic this[privDimension] = undefined; } else { var parsedVal = parseFloat(value); if (isNaN(parsedVal)) { _log2['default'].error('Improper value "' + value + '" supplied for for ' + _dimension); return this; } this[privDimension] = parsedVal; } this.updateStyleEl_(); return this; }; /** * A getter/setter/toggler for the vjs-fluid `className` on the `Player`. * * @param {boolean} [bool] * - A value of true adds the class. * - A value of false removes the class. * - No value will toggle the fluid class. * * @return {boolean|undefined} * - The value of fluid when getting. * - `undefined` when setting. */ Player.prototype.fluid = function fluid(bool) { if (bool === undefined) { return !!this.fluid_; } this.fluid_ = !!bool; if (bool) { this.addClass('vjs-fluid'); } else { this.removeClass('vjs-fluid'); } this.updateStyleEl_(); }; /** * Get/Set the aspect ratio * * @param {string} [ratio] * Aspect ratio for player * * @return {string|undefined} * returns the current aspect ratio when getting */ /** * A getter/setter for the `Player`'s aspect ratio. * * @param {string} [ratio] * The value to set the `Player's aspect ratio to. * * @return {string|undefined} * - The current aspect ratio of the `Player` when getting. * - undefined when setting */ Player.prototype.aspectRatio = function aspectRatio(ratio) { if (ratio === undefined) { return this.aspectRatio_; } // Check for width:height format if (!/^\d+\:\d+$/.test(ratio)) { throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.'); } this.aspectRatio_ = ratio; // We're assuming if you set an aspect ratio you want fluid mode, // because in fixed mode you could calculate width and height yourself. this.fluid(true); this.updateStyleEl_(); }; /** * Update styles of the `Player` element (height, width and aspect ratio). * * @private * @listens Tech#loadedmetadata */ Player.prototype.updateStyleEl_ = function updateStyleEl_() { if (_window2['default'].VIDEOJS_NO_DYNAMIC_STYLE === true) { var _width = typeof this.width_ === 'number' ? this.width_ : this.options_.width; var _height = typeof this.height_ === 'number' ? this.height_ : this.options_.height; var techEl = this.tech_ && this.tech_.el(); if (techEl) { if (_width >= 0) { techEl.width = _width; } if (_height >= 0) { techEl.height = _height; } } return; } var width = void 0; var height = void 0; var aspectRatio = void 0; var idClass = void 0; // The aspect ratio is either used directly or to calculate width and height. if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') { // Use any aspectRatio that's been specifically set aspectRatio = this.aspectRatio_; } else if (this.videoWidth() > 0) { // Otherwise try to get the aspect ratio from the video metadata aspectRatio = this.videoWidth() + ':' + this.videoHeight(); } else { // Or use a default. The video element's is 2:1, but 16:9 is more common. aspectRatio = '16:9'; } // Get the ratio as a decimal we can use to calculate dimensions var ratioParts = aspectRatio.split(':'); var ratioMultiplier = ratioParts[1] / ratioParts[0]; if (this.width_ !== undefined) { // Use any width that's been specifically set width = this.width_; } else if (this.height_ !== undefined) { // Or calulate the width from the aspect ratio if a height has been set width = this.height_ / ratioMultiplier; } else { // Or use the video's metadata, or use the video el's default of 300 width = this.videoWidth() || 300; } if (this.height_ !== undefined) { // Use any height that's been specifically set height = this.height_; } else { // Otherwise calculate the height from the ratio and the width height = width * ratioMultiplier; } // Ensure the CSS class is valid by starting with an alpha character if (/^[^a-zA-Z]/.test(this.id())) { idClass = 'dimensions-' + this.id(); } else { idClass = this.id() + '-dimensions'; } // Ensure the right class is still on the player for the style element this.addClass(idClass); stylesheet.setTextContent(this.styleEl_, '\n .' + idClass + ' {\n width: ' + width + 'px;\n height: ' + height + 'px;\n }\n\n .' + idClass + '.vjs-fluid {\n padding-top: ' + ratioMultiplier * 100 + '%;\n }\n '); }; /** * Load/Create an instance of playback {@link Tech} including element * and API methods. Then append the `Tech` element in `Player` as a child. * * @param {string} techName * name of the playback technology * * @param {string} source * video source * * @private */ Player.prototype.loadTech_ = function loadTech_(techName, source) { var _this2 = this; // Pause and remove current playback technology if (this.tech_) { this.unloadTech_(); } // get rid of the HTML5 video tag as soon as we are using another tech if (techName !== 'Html5' && this.tag) { _tech2['default'].getTech('Html5').disposeMediaElement(this.tag); this.tag.player = null; this.tag = null; } this.techName_ = techName; // Turn off API access because we're loading a new tech that might load asynchronously this.isReady_ = false; // Grab tech-specific options from player options and add source and parent element to use. var techOptions = (0, _obj.assign)({ source: source, 'nativeControlsForTouch': this.options_.nativeControlsForTouch, 'playerId': this.id(), 'techId': this.id() + '_' + techName + '_api', 'videoTracks': this.videoTracks_, 'textTracks': this.textTracks_, 'audioTracks': this.audioTracks_, 'autoplay': this.options_.autoplay, 'preload': this.options_.preload, 'loop': this.options_.loop, 'muted': this.options_.muted, 'poster': this.poster(), 'language': this.language(), 'playerElIngest': this.playerElIngest_ || false, 'vtt.js': this.options_['vtt.js'] }, this.options_[techName.toLowerCase()]); if (this.tag) { techOptions.tag = this.tag; } if (source) { this.currentType_ = source.type; if (source.src === this.cache_.src && this.cache_.currentTime > 0) { techOptions.startTime = this.cache_.currentTime; } this.cache_.sources = null; this.cache_.source = source; this.cache_.src = source.src; } // Initialize tech instance var TechComponent = _tech2['default'].getTech(techName); // Support old behavior of techs being registered as components. // Remove once that deprecated behavior is removed. if (!TechComponent) { TechComponent = _component2['default'].getComponent(techName); } this.tech_ = new TechComponent(techOptions); // player.triggerReady is always async, so don't need this to be async this.tech_.ready(Fn.bind(this, this.handleTechReady_), true); _textTrackListConverter2['default'].jsonToTextTracks(this.textTracksJson_ || [], this.tech_); // Listen to all HTML5-defined events and trigger them on the player TECH_EVENTS_RETRIGGER.forEach(function (event) { _this2.on(_this2.tech_, event, _this2['handleTech' + (0, _toTitleCase2['default'])(event) + '_']); }); this.on(this.tech_, 'loadstart', this.handleTechLoadStart_); this.on(this.tech_, 'waiting', this.handleTechWaiting_); this.on(this.tech_, 'canplay', this.handleTechCanPlay_); this.on(this.tech_, 'canplaythrough', this.handleTechCanPlayThrough_); this.on(this.tech_, 'playing', this.handleTechPlaying_); this.on(this.tech_, 'ended', this.handleTechEnded_); this.on(this.tech_, 'seeking', this.handleTechSeeking_); this.on(this.tech_, 'seeked', this.handleTechSeeked_); this.on(this.tech_, 'play', this.handleTechPlay_); this.on(this.tech_, 'firstplay', this.handleTechFirstPlay_); this.on(this.tech_, 'pause', this.handleTechPause_); this.on(this.tech_, 'durationchange', this.handleTechDurationChange_); this.on(this.tech_, 'fullscreenchange', this.handleTechFullscreenChange_); this.on(this.tech_, 'error', this.handleTechError_); this.on(this.tech_, 'loadedmetadata', this.updateStyleEl_); this.on(this.tech_, 'posterchange', this.handleTechPosterChange_); this.on(this.tech_, 'textdata', this.handleTechTextData_); this.usingNativeControls(this.techGet_('controls')); if (this.controls() && !this.usingNativeControls()) { this.addTechControlsListeners_(); } // Add the tech element in the DOM if it was not already there // Make sure to not insert the original video element if using Html5 if (this.tech_.el().parentNode !== this.el() && (techName !== 'Html5' || !this.tag)) { Dom.insertElFirst(this.tech_.el(), this.el()); } // Get rid of the original video tag reference after the first tech is loaded if (this.tag) { this.tag.player = null; this.tag = null; } }; /** * Unload and dispose of the current playback {@link Tech}. * * @private */ Player.prototype.unloadTech_ = function unloadTech_() { // Save the current text tracks so that we can reuse the same text tracks with the next tech this.videoTracks_ = this.videoTracks(); this.textTracks_ = this.textTracks(); this.audioTracks_ = this.audioTracks(); this.textTracksJson_ = _textTrackListConverter2['default'].textTracksToJson(this.tech_); this.isReady_ = false; this.tech_.dispose(); this.tech_ = false; }; /** * Return a reference to the current {@link Tech}, but only if given an object with the * `IWillNotUseThisInPlugins` property having a true value. This is try and prevent misuse * of techs by plugins. * * @param {Object} safety * An object that must contain `{IWillNotUseThisInPlugins: true}` * * @param {boolean} safety.IWillNotUseThisInPlugins * Must be set to true or else this function will throw an error. * * @return {Tech} * The Tech */ Player.prototype.tech = function tech(safety) { if (safety && safety.IWillNotUseThisInPlugins) { return this.tech_; } var errorText = '\n Please make sure that you are not using this inside of a plugin.\n To disable this alert and error, please pass in an object with\n `IWillNotUseThisInPlugins` to the `tech` method. See\n https://github.com/videojs/video.js/issues/2617 for more info.\n '; _window2['default'].alert(errorText); throw new Error(errorText); }; /** * Set up click and touch listeners for the playback element * * - On desktops: a click on the video itself will toggle playback * - On mobile devices: a click on the video toggles controls * which is done by toggling the user state between active and * inactive * - A tap can signal that a user has become active or has become inactive * e.g. a quick tap on an iPhone movie should reveal the controls. Another * quick tap should hide them again (signaling the user is in an inactive * viewing state) * - In addition to this, we still want the user to be considered inactive after * a few seconds of inactivity. * * > Note: the only part of iOS interaction we can't mimic with this setup * is a touch and hold on the video element counting as activity in order to * keep the controls showing, but that shouldn't be an issue. A touch and hold * on any controls will still keep the user active * * @private */ Player.prototype.addTechControlsListeners_ = function addTechControlsListeners_() { // Make sure to remove all the previous listeners in case we are called multiple times. this.removeTechControlsListeners_(); // Some browsers (Chrome & IE) don't trigger a click on a flash swf, but do // trigger mousedown/up. // http://stackoverflow.com/questions/1444562/javascript-onclick-event-over-flash-object // Any touch events are set to block the mousedown event from happening this.on(this.tech_, 'mousedown', this.handleTechClick_); // If the controls were hidden we don't want that to change without a tap event // so we'll check if the controls were already showing before reporting user // activity this.on(this.tech_, 'touchstart', this.handleTechTouchStart_); this.on(this.tech_, 'touchmove', this.handleTechTouchMove_); this.on(this.tech_, 'touchend', this.handleTechTouchEnd_); // The tap listener needs to come after the touchend listener because the tap // listener cancels out any reportedUserActivity when setting userActive(false) this.on(this.tech_, 'tap', this.handleTechTap_); }; /** * Remove the listeners used for click and tap controls. This is needed for * toggling to controls disabled, where a tap/touch should do nothing. * * @private */ Player.prototype.removeTechControlsListeners_ = function removeTechControlsListeners_() { // We don't want to just use `this.off()` because there might be other needed // listeners added by techs that extend this. this.off(this.tech_, 'tap', this.handleTechTap_); this.off(this.tech_, 'touchstart', this.handleTechTouchStart_); this.off(this.tech_, 'touchmove', this.handleTechTouchMove_); this.off(this.tech_, 'touchend', this.handleTechTouchEnd_); this.off(this.tech_, 'mousedown', this.handleTechClick_); }; /** * Player waits for the tech to be ready * * @private */ Player.prototype.handleTechReady_ = function handleTechReady_() { this.triggerReady(); // Keep the same volume as before if (this.cache_.volume) { this.techCall_('setVolume', this.cache_.volume); } // Look if the tech found a higher resolution poster while loading this.handleTechPosterChange_(); // Update the duration if available this.handleTechDurationChange_(); // Chrome and Safari both have issues with autoplay. // In Safari (5.1.1), when we move the video element into the container div, autoplay doesn't work. // In Chrome (15), if you have autoplay + a poster + no controls, the video gets hidden (but audio plays) // This fixes both issues. Need to wait for API, so it updates displays correctly if ((this.src() || this.currentSrc()) && this.tag && this.options_.autoplay && this.paused()) { try { // Chrome Fix. Fixed in Chrome v16. delete this.tag.poster; } catch (e) { (0, _log2['default'])('deleting tag.poster throws in some browsers', e); } this.play(); } }; /** * Retrigger the `loadstart` event that was triggered by the {@link Tech}. This * function will also trigger {@link Player#firstplay} if it is the first loadstart * for a video. * * @fires Player#loadstart * @fires Player#firstplay * @listens Tech#loadstart * @private */ Player.prototype.handleTechLoadStart_ = function handleTechLoadStart_() { // TODO: Update to use `emptied` event instead. See #1277. this.removeClass('vjs-ended'); this.removeClass('vjs-seeking'); // reset the error state this.error(null); // If it's already playing we want to trigger a firstplay event now. // The firstplay event relies on both the play and loadstart events // which can happen in any order for a new source if (!this.paused()) { /** * Fired when the user agent begins looking for media data * * @event Player#loadstart * @type {EventTarget~Event} */ this.trigger('loadstart'); this.trigger('firstplay'); } else { // reset the hasStarted state this.hasStarted(false); this.trigger('loadstart'); } }; /** * Add/remove the vjs-has-started class * * @fires Player#firstplay * * @param {boolean} hasStarted * - true: adds the class * - false: remove the class * * @return {boolean} * the boolean value of hasStarted */ Player.prototype.hasStarted = function hasStarted(_hasStarted) { if (_hasStarted !== undefined) { // only update if this is a new value if (this.hasStarted_ !== _hasStarted) { this.hasStarted_ = _hasStarted; if (_hasStarted) { this.addClass('vjs-has-started'); // trigger the firstplay event if this newly has played this.trigger('firstplay'); } else { this.removeClass('vjs-has-started'); } } return this; } return !!this.hasStarted_; }; /** * Fired whenever the media begins or resumes playback * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play} * @fires Player#play * @listens Tech#play * @private */ Player.prototype.handleTechPlay_ = function handleTechPlay_() { this.removeClass('vjs-ended'); this.removeClass('vjs-paused'); this.addClass('vjs-playing'); // hide the poster when the user hits play this.hasStarted(true); /** * Triggered whenever an {@link Tech#play} event happens. Indicates that * playback has started or resumed. * * @event Player#play * @type {EventTarget~Event} */ this.trigger('play'); }; /** * Retrigger the `waiting` event that was triggered by the {@link Tech}. * * @fires Player#waiting * @listens Tech#waiting * @private */ Player.prototype.handleTechWaiting_ = function handleTechWaiting_() { var _this3 = this; this.addClass('vjs-waiting'); /** * A readyState change on the DOM element has caused playback to stop. * * @event Player#waiting * @type {EventTarget~Event} */ this.trigger('waiting'); this.one('timeupdate', function () { return _this3.removeClass('vjs-waiting'); }); }; /** * Retrigger the `canplay` event that was triggered by the {@link Tech}. * > Note: This is not consistent between browsers. See #1351 * * @fires Player#canplay * @listens Tech#canplay * @private */ Player.prototype.handleTechCanPlay_ = function handleTechCanPlay_() { this.removeClass('vjs-waiting'); /** * The media has a readyState of HAVE_FUTURE_DATA or greater. * * @event Player#canplay * @type {EventTarget~Event} */ this.trigger('canplay'); }; /** * Retrigger the `canplaythrough` event that was triggered by the {@link Tech}. * * @fires Player#canplaythrough * @listens Tech#canplaythrough * @private */ Player.prototype.handleTechCanPlayThrough_ = function handleTechCanPlayThrough_() { this.removeClass('vjs-waiting'); /** * The media has a readyState of HAVE_ENOUGH_DATA or greater. This means that the * entire media file can be played without buffering. * * @event Player#canplaythrough * @type {EventTarget~Event} */ this.trigger('canplaythrough'); }; /** * Retrigger the `playing` event that was triggered by the {@link Tech}. * * @fires Player#playing * @listens Tech#playing * @private */ Player.prototype.handleTechPlaying_ = function handleTechPlaying_() { this.removeClass('vjs-waiting'); /** * The media is no longer blocked from playback, and has started playing. * * @event Player#playing * @type {EventTarget~Event} */ this.trigger('playing'); }; /** * Retrigger the `seeking` event that was triggered by the {@link Tech}. * * @fires Player#seeking * @listens Tech#seeking * @private */ Player.prototype.handleTechSeeking_ = function handleTechSeeking_() { this.addClass('vjs-seeking'); /** * Fired whenever the player is jumping to a new time * * @event Player#seeking * @type {EventTarget~Event} */ this.trigger('seeking'); }; /** * Retrigger the `seeked` event that was triggered by the {@link Tech}. * * @fires Player#seeked * @listens Tech#seeked * @private */ Player.prototype.handleTechSeeked_ = function handleTechSeeked_() { this.removeClass('vjs-seeking'); /** * Fired when the player has finished jumping to a new time * * @event Player#seeked * @type {EventTarget~Event} */ this.trigger('seeked'); }; /** * Retrigger the `firstplay` event that was triggered by the {@link Tech}. * * @fires Player#firstplay * @listens Tech#firstplay * @deprecated As of 6.0 passing the `starttime` option to the player will be deprecated * @private */ Player.prototype.handleTechFirstPlay_ = function handleTechFirstPlay_() { // If the first starttime attribute is specified // then we will start at the given offset in seconds if (this.options_.starttime) { _log2['default'].warn('Passing the `starttime` option to the player will be deprecated in 6.0'); this.currentTime(this.options_.starttime); } this.addClass('vjs-has-started'); /** * Fired the first time a video is played. Not part of the HLS spec, and this is * probably not the best implementation yet, so use sparingly. If you don't have a * reason to prevent playback, use `myPlayer.one('play');` instead. * * @event Player#firstplay * @type {EventTarget~Event} */ this.trigger('firstplay'); }; /** * Retrigger the `pause` event that was triggered by the {@link Tech}. * * @fires Player#pause * @listens Tech#pause * @private */ Player.prototype.handleTechPause_ = function handleTechPause_() { this.removeClass('vjs-playing'); this.addClass('vjs-paused'); /** * Fired whenever the media has been paused * * @event Player#pause * @type {EventTarget~Event} */ this.trigger('pause'); }; /** * Retrigger the `ended` event that was triggered by the {@link Tech}. * * @fires Player#ended * @listens Tech#ended * @private */ Player.prototype.handleTechEnded_ = function handleTechEnded_() { this.addClass('vjs-ended'); if (this.options_.loop) { this.currentTime(0); this.play(); } else if (!this.paused()) { this.pause(); } /** * Fired when the end of the media resource is reached (currentTime == duration) * * @event Player#ended * @type {EventTarget~Event} */ this.trigger('ended'); }; /** * Fired when the duration of the media resource is first known or changed * * @listens Tech#durationchange * @private */ Player.prototype.handleTechDurationChange_ = function handleTechDurationChange_() { this.duration(this.techGet_('duration')); }; /** * Handle a click on the media element to play/pause * * @param {EventTarget~Event} event * the event that caused this function to trigger * * @listens Tech#mousedown * @private */ Player.prototype.handleTechClick_ = function handleTechClick_(event) { // We're using mousedown to detect clicks thanks to Flash, but mousedown // will also be triggered with right-clicks, so we need to prevent that if (event.button !== 0) { return; } // When controls are disabled a click should not toggle playback because // the click is considered a control if (this.controls()) { if (this.paused()) { this.play(); } else { this.pause(); } } }; /** * Handle a tap on the media element. It will toggle the user * activity state, which hides and shows the controls. * * @listens Tech#tap * @private */ Player.prototype.handleTechTap_ = function handleTechTap_() { this.userActive(!this.userActive()); }; /** * Handle touch to start * * @listens Tech#touchstart * @private */ Player.prototype.handleTechTouchStart_ = function handleTechTouchStart_() { this.userWasActive = this.userActive(); }; /** * Handle touch to move * * @listens Tech#touchmove * @private */ Player.prototype.handleTechTouchMove_ = function handleTechTouchMove_() { if (this.userWasActive) { this.reportUserActivity(); } }; /** * Handle touch to end * * @param {EventTarget~Event} event * the touchend event that triggered * this function * * @listens Tech#touchend * @private */ Player.prototype.handleTechTouchEnd_ = function handleTechTouchEnd_(event) { // Stop the mouse events from also happening event.preventDefault(); }; /** * Fired when the player switches in or out of fullscreen mode * * @private * @listens Player#fullscreenchange */ Player.prototype.handleFullscreenChange_ = function handleFullscreenChange_() { if (this.isFullscreen()) { this.addClass('vjs-fullscreen'); } else { this.removeClass('vjs-fullscreen'); } }; /** * native click events on the SWF aren't triggered on IE11, Win8.1RT * use stageclick events triggered from inside the SWF instead * * @private * @listens stageclick */ Player.prototype.handleStageClick_ = function handleStageClick_() { this.reportUserActivity(); }; /** * Handle Tech Fullscreen Change * * @param {EventTarget~Event} event * the fullscreenchange event that triggered this function * * @param {Object} data * the data that was sent with the event * * @private * @listens Tech#fullscreenchange * @fires Player#fullscreenchange */ Player.prototype.handleTechFullscreenChange_ = function handleTechFullscreenChange_(event, data) { if (data) { this.isFullscreen(data.isFullscreen); } /** * Fired when going in and out of fullscreen. * * @event Player#fullscreenchange * @type {EventTarget~Event} */ this.trigger('fullscreenchange'); }; /** * Fires when an error occurred during the loading of an audio/video. * * @private * @listens Tech#error */ Player.prototype.handleTechError_ = function handleTechError_() { var error = this.tech_.error(); this.error(error); }; /** * Retrigger the `textdata` event that was triggered by the {@link Tech}. * * @fires Player#textdata * @listens Tech#textdata * @private */ Player.prototype.handleTechTextData_ = function handleTechTextData_() { var data = null; if (arguments.length > 1) { data = arguments[1]; } /** * Fires when we get a textdata event from tech * * @event Player#textdata * @type {EventTarget~Event} */ this.trigger('textdata', data); }; /** * Get object for cached values. * * @return {Object} * get the current object cache */ Player.prototype.getCache = function getCache() { return this.cache_; }; /** * Pass values to the playback tech * * @param {string} [method] * the method to call * * @param {Object} arg * the argument to pass * * @private */ Player.prototype.techCall_ = function techCall_(method, arg) { // If it's not ready yet, call method when it is if (this.tech_ && !this.tech_.isReady_) { this.tech_.ready(function () { this[method](arg); }, true); // Otherwise call method now } else { try { if (this.tech_) { this.tech_[method](arg); } } catch (e) { (0, _log2['default'])(e); throw e; } } }; /** * Get calls can't wait for the tech, and sometimes don't need to. * * @param {string} method * Tech method * * @return {Function|undefined} * the method or undefined * * @private */ Player.prototype.techGet_ = function techGet_(method) { if (this.tech_ && this.tech_.isReady_) { // Flash likes to die and reload when you hide or reposition it. // In these cases the object methods go away and we get errors. // When that happens we'll catch the errors and inform tech that it's not ready any more. try { return this.tech_[method](); } catch (e) { // When building additional tech libs, an expected method may not be defined yet if (this.tech_[method] === undefined) { (0, _log2['default'])('Video.js: ' + method + ' method not defined for ' + this.techName_ + ' playback technology.', e); // When a method isn't available on the object it throws a TypeError } else if (e.name === 'TypeError') { (0, _log2['default'])('Video.js: ' + method + ' unavailable on ' + this.techName_ + ' playback technology element.', e); this.tech_.isReady_ = false; } else { (0, _log2['default'])(e); } throw e; } } return; }; /** * start media playback * * @return {Player} * A reference to the player object this function was called on */ Player.prototype.play = function play() { // Only calls the tech's play if we already have a src loaded if (this.src() || this.currentSrc()) { this.techCall_('play'); } else { this.tech_.one('loadstart', function () { this.play(); }); } return this; }; /** * Pause the video playback * * @return {Player} * A reference to the player object this function was called on */ Player.prototype.pause = function pause() { this.techCall_('pause'); return this; }; /** * Check if the player is paused or has yet to play * * @return {boolean} * - false: if the media is currently playing * - true: if media is not currently playing */ Player.prototype.paused = function paused() { // The initial state of paused should be true (in Safari it's actually false) return this.techGet_('paused') === false ? false : true; }; /** * Returns whether or not the user is "scrubbing". Scrubbing is * when the user has clicked the progress bar handle and is * dragging it along the progress bar. * * @param {boolean} [isScrubbing] * wether the user is or is not scrubbing * * @return {boolean|Player} * A instance of the player that called this function when setting, * and the value of scrubbing when getting */ Player.prototype.scrubbing = function scrubbing(isScrubbing) { if (isScrubbing !== undefined) { this.scrubbing_ = !!isScrubbing; if (isScrubbing) { this.addClass('vjs-scrubbing'); } else { this.removeClass('vjs-scrubbing'); } return this; } return this.scrubbing_; }; /** * Get or set the current time (in seconds) * * @param {number|string} [seconds] * The time to seek to in seconds * * @return {Player|number} * - the current time in seconds when getting * - a reference to the current player object when setting */ Player.prototype.currentTime = function currentTime(seconds) { if (seconds !== undefined) { this.techCall_('setCurrentTime', seconds); return this; } // cache last currentTime and return. default to 0 seconds // // Caching the currentTime is meant to prevent a massive amount of reads on the tech's // currentTime when scrubbing, but may not provide much performance benefit afterall. // Should be tested. Also something has to read the actual current time or the cache will // never get updated. this.cache_.currentTime = this.techGet_('currentTime') || 0; return this.cache_.currentTime; }; /** * Normally gets the length in time of the video in seconds; * in all but the rarest use cases an argument will NOT be passed to the method * * > **NOTE**: The video must have started loading before the duration can be * known, and in the case of Flash, may not be known until the video starts * playing. * * @fires Player#durationchange * * @param {number} [seconds] * The duration of the video to set in seconds * * @return {number|Player} * - The duration of the video in seconds when getting * - A reference to the player that called this function * when setting */ Player.prototype.duration = function duration(seconds) { if (seconds === undefined) { return this.cache_.duration || 0; } seconds = parseFloat(seconds) || 0; // Standardize on Inifity for signaling video is live if (seconds < 0) { seconds = Infinity; } if (seconds !== this.cache_.duration) { // Cache the last set value for optimized scrubbing (esp. Flash) this.cache_.duration = seconds; if (seconds === Infinity) { this.addClass('vjs-live'); } else { this.removeClass('vjs-live'); } /** * @event Player#durationchange * @type {EventTarget~Event} */ this.trigger('durationchange'); } return this; }; /** * Calculates how much time is left in the video. Not part * of the native video API. * * @return {number} * The time remaining in seconds */ Player.prototype.remainingTime = function remainingTime() { return this.duration() - this.currentTime(); }; // // Kind of like an array of portions of the video that have been downloaded. /** * Get a TimeRange object with an array of the times of the video * that have been downloaded. If you just want the percent of the * video that's been downloaded, use bufferedPercent. * * @see [Buffered Spec]{@link http://dev.w3.org/html5/spec/video.html#dom-media-buffered} * * @return {TimeRange} * A mock TimeRange object (following HTML spec) */ Player.prototype.buffered = function buffered() { var buffered = this.techGet_('buffered'); if (!buffered || !buffered.length) { buffered = (0, _timeRanges.createTimeRange)(0, 0); } return buffered; }; /** * Get the percent (as a decimal) of the video that's been downloaded. * This method is not a part of the native HTML video API. * * @return {number} * A decimal between 0 and 1 representing the percent * that is bufferred 0 being 0% and 1 being 100% */ Player.prototype.bufferedPercent = function bufferedPercent() { return (0, _buffer.bufferedPercent)(this.buffered(), this.duration()); }; /** * Get the ending time of the last buffered time range * This is used in the progress bar to encapsulate all time ranges. * * @return {number} * The end of the last buffered time range */ Player.prototype.bufferedEnd = function bufferedEnd() { var buffered = this.buffered(); var duration = this.duration(); var end = buffered.end(buffered.length - 1); if (end > duration) { end = duration; } return end; }; /** * Get or set the current volume of the media * * @param {number} [percentAsDecimal] * The new volume as a decimal percent: * - 0 is muted/0%/off * - 1.0 is 100%/full * - 0.5 is half volume or 50% * * @return {Player|number} * a reference to the calling player when setting and the * current volume as a percent when getting */ Player.prototype.volume = function volume(percentAsDecimal) { var vol = void 0; if (percentAsDecimal !== undefined) { // Force value to between 0 and 1 vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal))); this.cache_.volume = vol; this.techCall_('setVolume', vol); return this; } // Default to 1 when returning current volume. vol = parseFloat(this.techGet_('volume')); return isNaN(vol) ? 1 : vol; }; /** * Get the current muted state, or turn mute on or off * * @param {boolean} [muted] * - true to mute * - false to unmute * * @return {boolean|Player} * - true if mute is on and getting * - false if mute is off and getting * - A reference to the current player when setting */ Player.prototype.muted = function muted(_muted) { if (_muted !== undefined) { this.techCall_('setMuted', _muted); return this; } return this.techGet_('muted') || false; }; /** * Check if current tech can support native fullscreen * (e.g. with built in controls like iOS, so not our flash swf) * * @return {boolean} * if native fullscreen is supported */ Player.prototype.supportsFullScreen = function supportsFullScreen() { return this.techGet_('supportsFullScreen') || false; }; /** * Check if the player is in fullscreen mode or tell the player that it * is or is not in fullscreen mode. * * > NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official * property and instead document.fullscreenElement is used. But isFullscreen is * still a valuable property for internal player workings. * * @param {boolean} [isFS] * Set the players current fullscreen state * * @return {boolean|Player} * - true if fullscreen is on and getting * - false if fullscreen is off and getting * - A reference to the current player when setting */ Player.prototype.isFullscreen = function isFullscreen(isFS) { if (isFS !== undefined) { this.isFullscreen_ = !!isFS; return this; } return !!this.isFullscreen_; }; /** * Increase the size of the video to full screen * In some browsers, full screen is not supported natively, so it enters * "full window mode", where the video fills the browser window. * In browsers and devices that support native full screen, sometimes the * browser's default controls will be shown, and not the Video.js custom skin. * This includes most mobile devices (iOS, Android) and older versions of * Safari. * * @fires Player#fullscreenchange * @return {Player} * A reference to the current player */ Player.prototype.requestFullscreen = function requestFullscreen() { var fsApi = _fullscreenApi2['default']; this.isFullscreen(true); if (fsApi.requestFullscreen) { // the browser supports going fullscreen at the element level so we can // take the controls fullscreen as well as the video // Trigger fullscreenchange event after change // We have to specifically add this each time, and remove // when canceling fullscreen. Otherwise if there's multiple // players on a page, they would all be reacting to the same fullscreen // events Events.on(_document2['default'], fsApi.fullscreenchange, Fn.bind(this, function documentFullscreenChange(e) { this.isFullscreen(_document2['default'][fsApi.fullscreenElement]); // If cancelling fullscreen, remove event listener. if (this.isFullscreen() === false) { Events.off(_document2['default'], fsApi.fullscreenchange, documentFullscreenChange); } /** * @event Player#fullscreenchange * @type {EventTarget~Event} */ this.trigger('fullscreenchange'); })); this.el_[fsApi.requestFullscreen](); } else if (this.tech_.supportsFullScreen()) { // we can't take the video.js controls fullscreen but we can go fullscreen // with native controls this.techCall_('enterFullScreen'); } else { // fullscreen isn't supported so we'll just stretch the video element to // fill the viewport this.enterFullWindow(); /** * @event Player#fullscreenchange * @type {EventTarget~Event} */ this.trigger('fullscreenchange'); } return this; }; /** * Return the video to its normal size after having been in full screen mode * * @fires Player#fullscreenchange * * @return {Player} * A reference to the current player */ Player.prototype.exitFullscreen = function exitFullscreen() { var fsApi = _fullscreenApi2['default']; this.isFullscreen(false); // Check for browser element fullscreen support if (fsApi.requestFullscreen) { _document2['default'][fsApi.exitFullscreen](); } else if (this.tech_.supportsFullScreen()) { this.techCall_('exitFullScreen'); } else { this.exitFullWindow(); /** * @event Player#fullscreenchange * @type {EventTarget~Event} */ this.trigger('fullscreenchange'); } return this; }; /** * When fullscreen isn't supported we can stretch the * video container to as wide as the browser will let us. * * @fires Player#enterFullWindow */ Player.prototype.enterFullWindow = function enterFullWindow() { this.isFullWindow = true; // Storing original doc overflow value to return to when fullscreen is off this.docOrigOverflow = _document2['default'].documentElement.style.overflow; // Add listener for esc key to exit fullscreen Events.on(_document2['default'], 'keydown', Fn.bind(this, this.fullWindowOnEscKey)); // Hide any scroll bars _document2['default'].documentElement.style.overflow = 'hidden'; // Apply fullscreen styles Dom.addElClass(_document2['default'].body, 'vjs-full-window'); /** * @event Player#enterFullWindow * @type {EventTarget~Event} */ this.trigger('enterFullWindow'); }; /** * Check for call to either exit full window or * full screen on ESC key * * @param {string} event * Event to check for key press */ Player.prototype.fullWindowOnEscKey = function fullWindowOnEscKey(event) { if (event.keyCode === 27) { if (this.isFullscreen() === true) { this.exitFullscreen(); } else { this.exitFullWindow(); } } }; /** * Exit full window * * @fires Player#exitFullWindow */ Player.prototype.exitFullWindow = function exitFullWindow() { this.isFullWindow = false; Events.off(_document2['default'], 'keydown', this.fullWindowOnEscKey); // Unhide scroll bars. _document2['default'].documentElement.style.overflow = this.docOrigOverflow; // Remove fullscreen styles Dom.removeElClass(_document2['default'].body, 'vjs-full-window'); // Resize the box, controller, and poster to original sizes // this.positionAll(); /** * @event Player#exitFullWindow * @type {EventTarget~Event} */ this.trigger('exitFullWindow'); }; /** * Check whether the player can play a given mimetype * * @see https://www.w3.org/TR/2011/WD-html5-20110113/video.html#dom-navigator-canplaytype * * @param {string} type * The mimetype to check * * @return {string} * 'probably', 'maybe', or '' (empty string) */ Player.prototype.canPlayType = function canPlayType(type) { var can = void 0; // Loop through each playback technology in the options order for (var i = 0, j = this.options_.techOrder; i < j.length; i++) { var techName = (0, _toTitleCase2['default'])(j[i]); var tech = _tech2['default'].getTech(techName); // Support old behavior of techs being registered as components. // Remove once that deprecated behavior is removed. if (!tech) { tech = _component2['default'].getComponent(techName); } // Check if the current tech is defined before continuing if (!tech) { _log2['default'].error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.'); continue; } // Check if the browser supports this technology if (tech.isSupported()) { can = tech.canPlayType(type); if (can) { return can; } } } return ''; }; /** * Select source based on tech-order or source-order * Uses source-order selection if `options.sourceOrder` is truthy. Otherwise, * defaults to tech-order selection * * @param {Array} sources * The sources for a media asset * * @return {Object|boolean} * Object of source and tech order or false */ Player.prototype.selectSource = function selectSource(sources) { var _this4 = this; // Get only the techs specified in `techOrder` that exist and are supported by the // current platform var techs = this.options_.techOrder.map(_toTitleCase2['default']).map(function (techName) { // `Component.getComponent(...)` is for support of old behavior of techs // being registered as components. // Remove once that deprecated behavior is removed. return [techName, _tech2['default'].getTech(techName) || _component2['default'].getComponent(techName)]; }).filter(function (_ref) { var techName = _ref[0], tech = _ref[1]; // Check if the current tech is defined before continuing if (tech) { // Check if the browser supports this technology return tech.isSupported(); } _log2['default'].error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.'); return false; }); // Iterate over each `innerArray` element once per `outerArray` element and execute // `tester` with both. If `tester` returns a non-falsy value, exit early and return // that value. var findFirstPassingTechSourcePair = function findFirstPassingTechSourcePair(outerArray, innerArray, tester) { var found = void 0; outerArray.some(function (outerChoice) { return innerArray.some(function (innerChoice) { found = tester(outerChoice, innerChoice); if (found) { return true; } }); }); return found; }; var foundSourceAndTech = void 0; var flip = function flip(fn) { return function (a, b) { return fn(b, a); }; }; var finder = function finder(_ref2, source) { var techName = _ref2[0], tech = _ref2[1]; if (tech.canPlaySource(source, _this4.options_[techName.toLowerCase()])) { return { source: source, tech: techName }; } }; // Depending on the truthiness of `options.sourceOrder`, we swap the order of techs and sources // to select from them based on their priority. if (this.options_.sourceOrder) { // Source-first ordering foundSourceAndTech = findFirstPassingTechSourcePair(sources, techs, flip(finder)); } else { // Tech-first ordering foundSourceAndTech = findFirstPassingTechSourcePair(techs, sources, finder); } return foundSourceAndTech || false; }; /** * The source function updates the video source * There are three types of variables you can pass as the argument. * **URL string**: A URL to the the video file. Use this method if you are sure * the current playback technology (HTML5/Flash) can support the source you * provide. Currently only MP4 files can be used in both HTML5 and Flash. * * @param {Tech~SourceObject|Tech~SourceObject[]} [source] * One SourceObject or an array of SourceObjects * * @return {string|Player} * - The current video source when getting * - The player when setting */ Player.prototype.src = function src(source) { if (source === undefined) { return this.techGet_('src'); } var currentTech = _tech2['default'].getTech(this.techName_); // Support old behavior of techs being registered as components. // Remove once that deprecated behavior is removed. if (!currentTech) { currentTech = _component2['default'].getComponent(this.techName_); } // case: Array of source objects to choose from and pick the best to play if (Array.isArray(source)) { this.sourceList_(source); // case: URL String (http://myvideo...) } else if (typeof source === 'string') { // create a source object from the string this.src({ src: source }); // case: Source object { src: '', type: '' ... } } else if (source instanceof Object) { // check if the source has a type and the loaded tech cannot play the source // if there's no type we'll just try the current tech if (source.type && !currentTech.canPlaySource(source, this.options_[this.techName_.toLowerCase()])) { // create a source list with the current source and send through // the tech loop to check for a compatible technology this.sourceList_([source]); } else { this.cache_.sources = null; this.cache_.source = source; this.cache_.src = source.src; this.currentType_ = source.type || ''; // wait until the tech is ready to set the source this.ready(function () { // The setSource tech method was added with source handlers // so older techs won't support it // We need to check the direct prototype for the case where subclasses // of the tech do not support source handlers if (currentTech.prototype.hasOwnProperty('setSource')) { this.techCall_('setSource', source); } else { this.techCall_('src', source.src); } if (this.options_.preload === 'auto') { this.load(); } if (this.options_.autoplay) { this.play(); } // Set the source synchronously if possible (#2326) }, true); } } return this; }; /** * Handle an array of source objects * * @param {Tech~SourceObject[]} sources * Array of source objects * * @private */ Player.prototype.sourceList_ = function sourceList_(sources) { var sourceTech = this.selectSource(sources); if (sourceTech) { if (sourceTech.tech === this.techName_) { // if this technology is already loaded, set the source this.src(sourceTech.source); } else { // load this technology with the chosen source this.loadTech_(sourceTech.tech, sourceTech.source); } this.cache_.sources = sources; } else { // We need to wrap this in a timeout to give folks a chance to add error event handlers this.setTimeout(function () { this.error({ code: 4, message: this.localize(this.options_.notSupportedMessage) }); }, 0); // we could not find an appropriate tech, but let's still notify the delegate that this is it // this needs a better comment about why this is needed this.triggerReady(); } }; /** * Begin loading the src data. * * @return {Player} * A reference to the player */ Player.prototype.load = function load() { this.techCall_('load'); return this; }; /** * Reset the player. Loads the first tech in the techOrder, * and calls `reset` on the tech`. * * @return {Player} * A reference to the player */ Player.prototype.reset = function reset() { this.loadTech_((0, _toTitleCase2['default'])(this.options_.techOrder[0]), null); this.techCall_('reset'); return this; }; /** * Returns all of the current source objects. * * @return {Tech~SourceObject[]} * The current source objects */ Player.prototype.currentSources = function currentSources() { var source = this.currentSource(); var sources = []; // assume `{}` or `{ src }` if (Object.keys(source).length !== 0) { sources.push(source); } return this.cache_.sources || sources; }; /** * Returns the current source object. * * @return {Tech~SourceObject} * The current source object */ Player.prototype.currentSource = function currentSource() { var source = {}; var src = this.currentSrc(); if (src) { source.src = src; } return this.cache_.source || source; }; /** * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4 * Can be used in conjuction with `currentType` to assist in rebuilding the current source object. * * @return {string} * The current source */ Player.prototype.currentSrc = function currentSrc() { return this.techGet_('currentSrc') || this.cache_.src || ''; }; /** * Get the current source type e.g. video/mp4 * This can allow you rebuild the current source object so that you could load the same * source and tech later * * @return {string} * The source MIME type */ Player.prototype.currentType = function currentType() { return this.currentType_ || ''; }; /** * Get or set the preload attribute * * @param {boolean} [value] * - true means that we should preload * - false maens that we should not preload * * @return {string|Player} * - the preload attribute value when getting * - the player when setting */ Player.prototype.preload = function preload(value) { if (value !== undefined) { this.techCall_('setPreload', value); this.options_.preload = value; return this; } return this.techGet_('preload'); }; /** * Get or set the autoplay attribute. * * @param {boolean} [value] * - true means that we should autoplay * - false maens that we should not autoplay * * @return {string|Player} * - the current value of autoplay * - the player when setting */ Player.prototype.autoplay = function autoplay(value) { if (value !== undefined) { this.techCall_('setAutoplay', value); this.options_.autoplay = value; return this; } return this.techGet_('autoplay', value); }; /** * Get or set the loop attribute on the video element. * * @param {boolean} [value] * - true means that we should loop the video * - false means that we should not loop the video * * @return {string|Player} * - the current value of loop when getting * - the player when setting */ Player.prototype.loop = function loop(value) { if (value !== undefined) { this.techCall_('setLoop', value); this.options_.loop = value; return this; } return this.techGet_('loop'); }; /** * Get or set the poster image source url * * @fires Player#posterchange * * @param {string} [src] * Poster image source URL * * @return {string|Player} * - the current value of poster when getting * - the player when setting */ Player.prototype.poster = function poster(src) { if (src === undefined) { return this.poster_; } // The correct way to remove a poster is to set as an empty string // other falsey values will throw errors if (!src) { src = ''; } // update the internal poster variable this.poster_ = src; // update the tech's poster this.techCall_('setPoster', src); // alert components that the poster has been set /** * This event fires when the poster image is changed on the player. * * @event Player#posterchange * @type {EventTarget~Event} */ this.trigger('posterchange'); return this; }; /** * Some techs (e.g. YouTube) can provide a poster source in an * asynchronous way. We want the poster component to use this * poster source so that it covers up the tech's controls. * (YouTube's play button). However we only want to use this * soruce if the player user hasn't set a poster through * the normal APIs. * * @fires Player#posterchange * @listens Tech#posterchange * @private */ Player.prototype.handleTechPosterChange_ = function handleTechPosterChange_() { if (!this.poster_ && this.tech_ && this.tech_.poster) { this.poster_ = this.tech_.poster() || ''; // Let components know the poster has changed this.trigger('posterchange'); } }; /** * Get or set whether or not the controls are showing. * * @fires Player#controlsenabled * * @param {boolean} [bool] * - true to turn controls on * - false to turn controls off * * @return {boolean|Player} * - the current value of controls when getting * - the player when setting */ Player.prototype.controls = function controls(bool) { if (bool !== undefined) { bool = !!bool; // Don't trigger a change event unless it actually changed if (this.controls_ !== bool) { this.controls_ = bool; if (this.usingNativeControls()) { this.techCall_('setControls', bool); } if (bool) { this.removeClass('vjs-controls-disabled'); this.addClass('vjs-controls-enabled'); /** * @event Player#controlsenabled * @type {EventTarget~Event} */ this.trigger('controlsenabled'); if (!this.usingNativeControls()) { this.addTechControlsListeners_(); } } else { this.removeClass('vjs-controls-enabled'); this.addClass('vjs-controls-disabled'); /** * @event Player#controlsdisabled * @type {EventTarget~Event} */ this.trigger('controlsdisabled'); if (!this.usingNativeControls()) { this.removeTechControlsListeners_(); } } } return this; } return !!this.controls_; }; /** * Toggle native controls on/off. Native controls are the controls built into * devices (e.g. default iPhone controls), Flash, or other techs * (e.g. Vimeo Controls) * **This should only be set by the current tech, because only the tech knows * if it can support native controls** * * @fires Player#usingnativecontrols * @fires Player#usingcustomcontrols * * @param {boolean} [bool] * - true to turn native controls on * - false to turn native controls off * * @return {boolean|Player} * - the current value of native controls when getting * - the player when setting */ Player.prototype.usingNativeControls = function usingNativeControls(bool) { if (bool !== undefined) { bool = !!bool; // Don't trigger a change event unless it actually changed if (this.usingNativeControls_ !== bool) { this.usingNativeControls_ = bool; if (bool) { this.addClass('vjs-using-native-controls'); /** * player is using the native device controls * * @event Player#usingnativecontrols * @type {EventTarget~Event} */ this.trigger('usingnativecontrols'); } else { this.removeClass('vjs-using-native-controls'); /** * player is using the custom HTML controls * * @event Player#usingcustomcontrols * @type {EventTarget~Event} */ this.trigger('usingcustomcontrols'); } } return this; } return !!this.usingNativeControls_; }; /** * Set or get the current MediaError * * @fires Player#error * * @param {MediaError|string|number} [err] * A MediaError or a string/number to be turned * into a MediaError * * @return {MediaError|null|Player} * - The current MediaError when getting (or null) * - The player when setting */ Player.prototype.error = function error(err) { if (err === undefined) { return this.error_ || null; } // restoring to default if (err === null) { this.error_ = err; this.removeClass('vjs-error'); if (this.errorDisplay) { this.errorDisplay.close(); } return this; } this.error_ = new _mediaError2['default'](err); // add the vjs-error classname to the player this.addClass('vjs-error'); // log the name of the error type and any message // ie8 just logs "[object object]" if you just log the error object _log2['default'].error('(CODE:' + this.error_.code + ' ' + _mediaError2['default'].errorTypes[this.error_.code] + ')', this.error_.message, this.error_); /** * @event Player#error * @type {EventTarget~Event} */ this.trigger('error'); return this; }; /** * Report user activity * * @param {Object} event * Event object */ Player.prototype.reportUserActivity = function reportUserActivity(event) { this.userActivity_ = true; }; /** * Get/set if user is active * * @fires Player#useractive * @fires Player#userinactive * * @param {boolean} [bool] * - true if the user is active * - false if the user is inactive * @return {boolean|Player} * - the current value of userActive when getting * - the player when setting */ Player.prototype.userActive = function userActive(bool) { if (bool !== undefined) { bool = !!bool; if (bool !== this.userActive_) { this.userActive_ = bool; if (bool) { // If the user was inactive and is now active we want to reset the // inactivity timer this.userActivity_ = true; this.removeClass('vjs-user-inactive'); this.addClass('vjs-user-active'); /** * @event Player#useractive * @type {EventTarget~Event} */ this.trigger('useractive'); } else { // We're switching the state to inactive manually, so erase any other // activity this.userActivity_ = false; // Chrome/Safari/IE have bugs where when you change the cursor it can // trigger a mousemove event. This causes an issue when you're hiding // the cursor when the user is inactive, and a mousemove signals user // activity. Making it impossible to go into inactive mode. Specifically // this happens in fullscreen when we really need to hide the cursor. // // When this gets resolved in ALL browsers it can be removed // https://code.google.com/p/chromium/issues/detail?id=103041 if (this.tech_) { this.tech_.one('mousemove', function (e) { e.stopPropagation(); e.preventDefault(); }); } this.removeClass('vjs-user-active'); this.addClass('vjs-user-inactive'); /** * @event Player#userinactive * @type {EventTarget~Event} */ this.trigger('userinactive'); } } return this; } return this.userActive_; }; /** * Listen for user activity based on timeout value * * @private */ Player.prototype.listenForUserActivity_ = function listenForUserActivity_() { var mouseInProgress = void 0; var lastMoveX = void 0; var lastMoveY = void 0; var handleActivity = Fn.bind(this, this.reportUserActivity); var handleMouseMove = function handleMouseMove(e) { // #1068 - Prevent mousemove spamming // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970 if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) { lastMoveX = e.screenX; lastMoveY = e.screenY; handleActivity(); } }; var handleMouseDown = function handleMouseDown() { handleActivity(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(mouseInProgress); // Setting userActivity=true now and setting the interval to the same time // as the activityCheck interval (250) should ensure we never miss the // next activityCheck mouseInProgress = this.setInterval(handleActivity, 250); }; var handleMouseUp = function handleMouseUp(event) { handleActivity(); // Stop the interval that maintains activity if the mouse/touch is down this.clearInterval(mouseInProgress); }; // Any mouse movement will be considered user activity this.on('mousedown', handleMouseDown); this.on('mousemove', handleMouseMove); this.on('mouseup', handleMouseUp); // Listen for keyboard navigation // Shouldn't need to use inProgress interval because of key repeat this.on('keydown', handleActivity); this.on('keyup', handleActivity); // Run an interval every 250 milliseconds instead of stuffing everything into // the mousemove/touchmove function itself, to prevent performance degradation. // `this.reportUserActivity` simply sets this.userActivity_ to true, which // then gets picked up by this loop // http://ejohn.org/blog/learning-from-twitter/ var inactivityTimeout = void 0; this.setInterval(function () { // Check to see if mouse/touch activity has happened if (this.userActivity_) { // Reset the activity tracker this.userActivity_ = false; // If the user state was inactive, set the state to active this.userActive(true); // Clear any existing inactivity timeout to start the timer over this.clearTimeout(inactivityTimeout); var timeout = this.options_.inactivityTimeout; if (timeout > 0) { // In <timeout> milliseconds, if no more activity has occurred the // user will be considered inactive inactivityTimeout = this.setTimeout(function () { // Protect against the case where the inactivityTimeout can trigger just // before the next user activity is picked up by the activity check loop // causing a flicker if (!this.userActivity_) { this.userActive(false); } }, timeout); } } }, 250); }; /** * Gets or sets the current playback rate. A playback rate of * 1.0 represents normal speed and 0.5 would indicate half-speed * playback, for instance. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate * * @param {number} [rate] * New playback rate to set. * * @return {number|Player} * - The current playback rate when getting or 1.0 * - the player when setting */ Player.prototype.playbackRate = function playbackRate(rate) { if (rate !== undefined) { this.techCall_('setPlaybackRate', rate); return this; } if (this.tech_ && this.tech_.featuresPlaybackRate) { return this.techGet_('playbackRate'); } return 1.0; }; /** * Gets or sets the audio flag * * @param {boolean} bool * - true signals that this is an audio player * - false signals that this is not an audio player * * @return {Player|boolean} * - the current value of isAudio when getting * - the player if setting */ Player.prototype.isAudio = function isAudio(bool) { if (bool !== undefined) { this.isAudio_ = !!bool; return this; } return !!this.isAudio_; }; /** * Get the {@link VideoTrackList} * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist * * @return {VideoTrackList} * the current video track list */ Player.prototype.videoTracks = function videoTracks() { // if we have not yet loadTech_, we create videoTracks_ // these will be passed to the tech during loading if (!this.tech_) { this.videoTracks_ = this.videoTracks_ || new _videoTrackList2['default'](); return this.videoTracks_; } return this.tech_.videoTracks(); }; /** * Get the {@link AudioTrackList} * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist * * @return {AudioTrackList} * the current audio track list */ Player.prototype.audioTracks = function audioTracks() { // if we have not yet loadTech_, we create videoTracks_ // these will be passed to the tech during loading if (!this.tech_) { this.audioTracks_ = this.audioTracks_ || new _audioTrackList2['default'](); return this.audioTracks_; } return this.tech_.audioTracks(); }; /** * Get the {@link TextTrackList} * * Text tracks are tracks of timed text events. * - Captions: text displayed over the video * for the hearing impaired * - Subtitles: text displayed over the video for * those who don't understand language in the video * - Chapters: text displayed in a menu allowing the user to jump * to particular points (chapters) in the video * - Descriptions: (not yet implemented) audio descriptions that are read back to * the user by a screen reading device * * @see http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks * * @return {TextTrackList|undefined} * The current TextTrackList or undefined if * or undefined if we don't have a tech */ Player.prototype.textTracks = function textTracks() { // cannot use techGet_ directly because it checks to see whether the tech is ready. // Flash is unlikely to be ready in time but textTracks should still work. if (this.tech_) { return this.tech_.textTracks(); } }; /** * Get the "remote" {@link TextTrackList}. Remote Text Tracks * are tracks that were added to the HTML video element and can * be removed, whereas normal texttracks cannot be removed. * * * @return {TextTrackList|undefined} * The current remote text track list or undefined * if we don't have a tech */ Player.prototype.remoteTextTracks = function remoteTextTracks() { if (this.tech_) { return this.tech_.remoteTextTracks(); } }; /** * Get the "remote" {@link HTMLTrackElementList}. * This gives the user all of the DOM elements that match up * with the remote {@link TextTrackList}. * * @return {HTMLTrackElementList} * The current remote text track list elements * or undefined if we don't have a tech */ Player.prototype.remoteTextTrackEls = function remoteTextTrackEls() { if (this.tech_) { return this.tech_.remoteTextTrackEls(); } }; /** * A helper method for adding a {@link TextTrack} to our * {@link TextTrackList}. * * In addition to the W3C settings we allow adding additional info through options. * * @see http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack * * @param {string} [kind] * the kind of TextTrack you are adding * * @param {string} [label] * the label to give the TextTrack label * * @param {string} [language] * the language to set on the TextTrack * * @return {TextTrack|undefined} * the TextTrack that was added or undefined * if there is no tech */ Player.prototype.addTextTrack = function addTextTrack(kind, label, language) { if (this.tech_) { return this.tech_.addTextTrack(kind, label, language); } }; /** * Create a remote {@link TextTrack} and an {@link HTMLTrackElement}. It will * automatically removed from the video element whenever the source changes, unless * manualCleanup is set to false. * * @param {Object} options * Options to pass to {@link HTMLTrackElement} during creation. See * {@link HTMLTrackElement} for object properties that you should use. * * @param {boolean} [manualCleanup=true] if set to false, the TextTrack will be * * @return {HTMLTrackElement} * the HTMLTrackElement that was created and added * to the HTMLTrackElementList and the remote * TextTrackList * * @deprecated The default value of the "manualCleanup" parameter will default * to "false" in upcoming versions of Video.js */ Player.prototype.addRemoteTextTrack = function addRemoteTextTrack(options, manualCleanup) { if (this.tech_) { return this.tech_.addRemoteTextTrack(options, manualCleanup); } }; /** * Remove a remote {@link TextTrack} from the respective * {@link TextTrackList} and {@link HTMLTrackElementList}. * * @param {Object} track * Remote {@link TextTrack} to remove * * @return {undefined} * does not return anything */ Player.prototype.removeRemoteTextTrack = function removeRemoteTextTrack() { var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref3$track = _ref3.track, track = _ref3$track === undefined ? arguments[0] : _ref3$track; // destructure the input into an object with a track argument, defaulting to arguments[0] // default the whole argument to an empty object if nothing was passed in if (this.tech_) { return this.tech_.removeRemoteTextTrack(track); } }; /** * Get video width * * @return {number} * current video width */ Player.prototype.videoWidth = function videoWidth() { return this.tech_ && this.tech_.videoWidth && this.tech_.videoWidth() || 0; }; /** * Get video height * * @return {number} * current video height */ Player.prototype.videoHeight = function videoHeight() { return this.tech_ && this.tech_.videoHeight && this.tech_.videoHeight() || 0; }; // Methods to add support for // initialTime: function() { return this.techCall_('initialTime'); }, // startOffsetTime: function() { return this.techCall_('startOffsetTime'); }, // played: function() { return this.techCall_('played'); }, // defaultPlaybackRate: function() { return this.techCall_('defaultPlaybackRate'); }, // defaultMuted: function() { return this.techCall_('defaultMuted'); } /** * The player's language code * NOTE: The language should be set in the player options if you want the * the controls to be built with a specific language. Changing the lanugage * later will not update controls text. * * @param {string} [code] * the language code to set the player to * * @return {string|Player} * - The current language code when getting * - A reference to the player when setting */ Player.prototype.language = function language(code) { if (code === undefined) { return this.language_; } this.language_ = String(code).toLowerCase(); return this; }; /** * Get the player's language dictionary * Merge every time, because a newly added plugin might call videojs.addLanguage() at any time * Languages specified directly in the player options have precedence * * @return {Array} * An array of of supported languages */ Player.prototype.languages = function languages() { return (0, _mergeOptions2['default'])(Player.prototype.options_.languages, this.languages_); }; /** * returns a JavaScript object reperesenting the current track * information. **DOES not return it as JSON** * * @return {Object} * Object representing the current of track info */ Player.prototype.toJSON = function toJSON() { var options = (0, _mergeOptions2['default'])(this.options_); var tracks = options.tracks; options.tracks = []; for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; // deep merge tracks and null out player so no circular references track = (0, _mergeOptions2['default'])(track); track.player = undefined; options.tracks[i] = track; } return options; }; /** * Creates a simple modal dialog (an instance of the {@link ModalDialog} * component) that immediately overlays the player with arbitrary * content and removes itself when closed. * * @param {string|Function|Element|Array|null} content * Same as {@link ModalDialog#content}'s param of the same name. * The most straight-forward usage is to provide a string or DOM * element. * * @param {Object} [options] * Extra options which will be passed on to the {@link ModalDialog}. * * @return {ModalDialog} * the {@link ModalDialog} that was created */ Player.prototype.createModal = function createModal(content, options) { var _this5 = this; options = options || {}; options.content = content || ''; var modal = new _modalDialog2['default'](this, options); this.addChild(modal); modal.on('dispose', function () { _this5.removeChild(modal); }); return modal.open(); }; /** * Gets tag settings * * @param {Element} tag * The player tag * * @return {Object} * An object containing all of the settings * for a player tag */ Player.getTagSettings = function getTagSettings(tag) { var baseOptions = { sources: [], tracks: [] }; var tagOptions = Dom.getElAttributes(tag); var dataSetup = tagOptions['data-setup']; if (Dom.hasElClass(tag, 'vjs-fluid')) { tagOptions.fluid = true; } // Check if data-setup attr exists. if (dataSetup !== null) { // Parse options JSON // If empty string, make it a parsable json object. var _safeParseTuple = (0, _tuple2['default'])(dataSetup || '{}'), err = _safeParseTuple[0], data = _safeParseTuple[1]; if (err) { _log2['default'].error(err); } (0, _obj.assign)(tagOptions, data); } (0, _obj.assign)(baseOptions, tagOptions); // Get tag children settings if (tag.hasChildNodes()) { var children = tag.childNodes; for (var i = 0, j = children.length; i < j; i++) { var child = children[i]; // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/ var childName = child.nodeName.toLowerCase(); if (childName === 'source') { baseOptions.sources.push(Dom.getElAttributes(child)); } else if (childName === 'track') { baseOptions.tracks.push(Dom.getElAttributes(child)); } } } return baseOptions; }; /** * Determine wether or not flexbox is supported * * @return {boolean} * - true if flexbox is supported * - false if flexbox is not supported */ Player.prototype.flexNotSupported_ = function flexNotSupported_() { var elem = _document2['default'].createElement('i'); // Note: We don't actually use flexBasis (or flexOrder), but it's one of the more // common flex features that we can rely on when checking for flex support. return !('flexBasis' in elem.style || 'webkitFlexBasis' in elem.style || 'mozFlexBasis' in elem.style || 'msFlexBasis' in elem.style || // IE10-specific (2012 flex spec) 'msFlexOrder' in elem.style); }; return Player; }(_component2['default']); /** * Global player list * * @type {Object} */ Player.players = {}; var navigator = _window2['default'].navigator; /* * Player instance options, surfaced using options * options = Player.prototype.options_ * Make changes in options, not here. * * @type {Object} * @private */ Player.prototype.options_ = { // Default order of fallback technology techOrder: ['html5', 'flash'], // techOrder: ['flash','html5'], html5: {}, flash: {}, // defaultVolume: 0.85, defaultVolume: 0.00, // default inactivity timeout inactivityTimeout: 2000, // default playback rates playbackRates: [], // Add playback rate selection by adding rates // 'playbackRates': [0.5, 1, 1.5, 2], // Included control sets children: ['mediaLoader', 'posterImage', 'textTrackDisplay', 'loadingSpinner', 'bigPlayButton', 'controlBar', 'errorDisplay', 'textTrackSettings'], language: navigator && (navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language) || 'en', // locales and their language translations languages: {}, // Default message to show when a video cannot be played. notSupportedMessage: 'No compatible source was found for this media.' }; [ /** * Returns whether or not the player is in the "ended" state. * * @return {Boolean} True if the player is in the ended state, false if not. * @method Player#ended */ 'ended', /** * Returns whether or not the player is in the "seeking" state. * * @return {Boolean} True if the player is in the seeking state, false if not. * @method Player#seeking */ 'seeking', /** * Returns the TimeRanges of the media that are currently available * for seeking to. * * @return {TimeRanges} the seekable intervals of the media timeline * @method Player#seekable */ 'seekable', /** * Returns the current state of network activity for the element, from * the codes in the list below. * - NETWORK_EMPTY (numeric value 0) * The element has not yet been initialised. All attributes are in * their initial states. * - NETWORK_IDLE (numeric value 1) * The element's resource selection algorithm is active and has * selected a resource, but it is not actually using the network at * this time. * - NETWORK_LOADING (numeric value 2) * The user agent is actively trying to download data. * - NETWORK_NO_SOURCE (numeric value 3) * The element's resource selection algorithm is active, but it has * not yet found a resource to use. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states * @return {number} the current network activity state * @method Player#networkState */ 'networkState', /** * Returns a value that expresses the current state of the element * with respect to rendering the current playback position, from the * codes in the list below. * - HAVE_NOTHING (numeric value 0) * No information regarding the media resource is available. * - HAVE_METADATA (numeric value 1) * Enough of the resource has been obtained that the duration of the * resource is available. * - HAVE_CURRENT_DATA (numeric value 2) * Data for the immediate current playback position is available. * - HAVE_FUTURE_DATA (numeric value 3) * Data for the immediate current playback position is available, as * well as enough data for the user agent to advance the current * playback position in the direction of playback. * - HAVE_ENOUGH_DATA (numeric value 4) * The user agent estimates that enough data is available for * playback to proceed uninterrupted. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate * @return {number} the current playback rendering state * @method Player#readyState */ 'readyState'].forEach(function (fn) { Player.prototype[fn] = function () { return this.techGet_(fn); }; }); TECH_EVENTS_RETRIGGER.forEach(function (event) { Player.prototype['handleTech' + (0, _toTitleCase2['default'])(event) + '_'] = function () { return this.trigger(event); }; }); /** * Fired when the player has initial duration and dimension information * * @event Player#loadedmetadata * @type {EventTarget~Event} */ /** * Fired when the player has downloaded data at the current playback position * * @event Player#loadeddata * @type {EventTarget~Event} */ /** * Fired when the current playback position has changed * * During playback this is fired every 15-250 milliseconds, depending on the * playback technology in use. * * @event Player#timeupdate * @type {EventTarget~Event} */ /** * Fired when the volume changes * * @event Player#volumechange * @type {EventTarget~Event} */ _component2['default'].registerComponent('Player', Player); exports['default'] = Player; },{"1":1,"4":4,"41":41,"44":44,"45":45,"46":46,"5":5,"50":50,"55":55,"59":59,"60":60,"61":61,"62":62,"63":63,"68":68,"69":69,"71":71,"76":76,"78":78,"79":79,"8":8,"81":81,"82":82,"83":83,"85":85,"86":86,"87":87,"88":88,"89":89,"90":90,"91":91,"94":94,"95":95,"97":97}],52:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _player = _dereq_(51); var _player2 = _interopRequireDefault(_player); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * The method for registering a video.js plugin. {@link videojs:videojs.registerPlugin]. * * @param {string} name * The name of the plugin that is being registered * * @param {plugins:PluginFn} init * The function that gets run when a `Player` initializes. */ var plugin = function plugin(name, init) { _player2['default'].prototype[name] = init; }; /** * @file plugins.js * @module plugins */ exports['default'] = plugin; },{"51":51}],53:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _clickableComponent = _dereq_(3); var _clickableComponent2 = _interopRequireDefault(_clickableComponent); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file popup-button.js */ /** * A button class for use with {@link Popup} controls * * @extends ClickableComponent */ var PopupButton = function (_ClickableComponent) { _inherits(PopupButton, _ClickableComponent); /** * Create an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function PopupButton(player) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; _classCallCheck(this, PopupButton); var _this = _possibleConstructorReturn(this, _ClickableComponent.call(this, player, options)); _this.update(); return _this; } /** * Update the `Popup` that this button is attached to. */ PopupButton.prototype.update = function update() { var popup = this.createPopup(); if (this.popup) { this.removeChild(this.popup); } this.popup = popup; this.addChild(popup); if (this.items && this.items.length === 0) { this.hide(); } else if (this.items && this.items.length > 1) { this.show(); } }; /** * Create a `Popup`. - Override with specific functionality for component * * @abstract */ PopupButton.prototype.createPopup = function createPopup() {}; /** * Create the `PopupButton`s DOM element. * * @return {Element} * The element that gets created. */ PopupButton.prototype.createEl = function createEl() { return _ClickableComponent.prototype.createEl.call(this, 'div', { className: this.buildCSSClass() }); }; /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ PopupButton.prototype.buildCSSClass = function buildCSSClass() { var menuButtonClass = 'vjs-menu-button'; // If the inline option is passed, we want to use different styles altogether. if (this.options_.inline === true) { menuButtonClass += '-inline'; } else { menuButtonClass += '-popup'; } return 'vjs-menu-button ' + menuButtonClass + ' ' + _ClickableComponent.prototype.buildCSSClass.call(this); }; return PopupButton; }(_clickableComponent2['default']); _component2['default'].registerComponent('PopupButton', PopupButton); exports['default'] = PopupButton; },{"3":3,"5":5}],54:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(81); var Dom = _interopRequireWildcard(_dom); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); var _events = _dereq_(82); var Events = _interopRequireWildcard(_events); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file popup.js */ /** * The Popup component is used to build pop up controls. * * @extends Component */ var Popup = function (_Component) { _inherits(Popup, _Component); function Popup() { _classCallCheck(this, Popup); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } /** * Add a popup item to the popup * * @param {Object|string} component * Component or component type to add * */ Popup.prototype.addItem = function addItem(component) { this.addChild(component); component.on('click', Fn.bind(this, function () { this.unlockShowing(); })); }; /** * Create the `PopupButton`s DOM element. * * @return {Element} * The element that gets created. */ Popup.prototype.createEl = function createEl() { var contentElType = this.options_.contentElType || 'ul'; this.contentEl_ = Dom.createEl(contentElType, { className: 'vjs-menu-content' }); var el = _Component.prototype.createEl.call(this, 'div', { append: this.contentEl_, className: 'vjs-menu' }); el.appendChild(this.contentEl_); // Prevent clicks from bubbling up. Needed for Popup Buttons, // where a click on the parent is significant Events.on(el, 'click', function (event) { event.preventDefault(); event.stopImmediatePropagation(); }); return el; }; return Popup; }(_component2['default']); _component2['default'].registerComponent('Popup', Popup); exports['default'] = Popup; },{"5":5,"81":81,"82":82,"83":83}],55:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _clickableComponent = _dereq_(3); var _clickableComponent2 = _interopRequireDefault(_clickableComponent); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); var _dom = _dereq_(81); var Dom = _interopRequireWildcard(_dom); var _browser = _dereq_(78); var browser = _interopRequireWildcard(_browser); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file poster-image.js */ /** * A `ClickableComponent` that handles showing the poster image for the player. * * @extends ClickableComponent */ var PosterImage = function (_ClickableComponent) { _inherits(PosterImage, _ClickableComponent); /** * Create an instance of this class. * * @param {Player} player * The `Player` that this class should attach to. * * @param {Object} [options] * The key/value store of player options. */ function PosterImage(player, options) { _classCallCheck(this, PosterImage); var _this = _possibleConstructorReturn(this, _ClickableComponent.call(this, player, options)); _this.update(); player.on('posterchange', Fn.bind(_this, _this.update)); return _this; } /** * Clean up and dispose of the `PosterImage`. */ PosterImage.prototype.dispose = function dispose() { this.player().off('posterchange', this.update); _ClickableComponent.prototype.dispose.call(this); }; /** * Create the `PosterImage`s DOM element. * * @return {Element} * The element that gets created. */ PosterImage.prototype.createEl = function createEl() { var el = Dom.createEl('div', { className: 'vjs-poster', // Don't want poster to be tabbable. tabIndex: -1 }); // To ensure the poster image resizes while maintaining its original aspect // ratio, use a div with `background-size` when available. For browsers that // do not support `background-size` (e.g. IE8), fall back on using a regular // img element. if (!browser.BACKGROUND_SIZE_SUPPORTED) { this.fallbackImg_ = Dom.createEl('img'); el.appendChild(this.fallbackImg_); } return el; }; /** * An {@link EventTarget~EventListener} for {@link Player#posterchange} events. * * @listens Player#posterchange * * @param {EventTarget~Event} [event] * The `Player#posterchange` event that triggered this function. */ PosterImage.prototype.update = function update(event) { var url = this.player().poster(); this.setSrc(url); // If there's no poster source we should display:none on this component // so it's not still clickable or right-clickable if (url) { this.show(); } else { this.hide(); } }; /** * Set the source of the `PosterImage` depending on the display method. * * @param {string} url * The URL to the source for the `PosterImage`. */ PosterImage.prototype.setSrc = function setSrc(url) { if (this.fallbackImg_) { this.fallbackImg_.src = url; } else { var backgroundImage = ''; // Any falsey values should stay as an empty string, otherwise // this will throw an extra error if (url) { backgroundImage = 'url("' + url + '")'; } this.el_.style.backgroundImage = backgroundImage; } }; /** * An {@link EventTarget~EventListener} for clicks on the `PosterImage`. See * {@link ClickableComponent#handleClick} for instances where this will be triggered. * * @listens tap * @listens click * @listens keydown * * @param {EventTarget~Event} event + The `click`, `tap` or `keydown` event that caused this function to be called. */ PosterImage.prototype.handleClick = function handleClick(event) { // We don't want a click to trigger playback when controls are disabled if (!this.player_.controls()) { return; } if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } }; return PosterImage; }(_clickableComponent2['default']); _component2['default'].registerComponent('PosterImage', PosterImage); exports['default'] = PosterImage; },{"3":3,"5":5,"78":78,"81":81,"83":83}],56:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.hasLoaded = exports.autoSetupTimeout = exports.autoSetup = undefined; var _dom = _dereq_(81); var Dom = _interopRequireWildcard(_dom); var _events = _dereq_(82); var Events = _interopRequireWildcard(_events); var _document = _dereq_(94); var _document2 = _interopRequireDefault(_document); var _window = _dereq_(95); var _window2 = _interopRequireDefault(_window); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } /** * @file setup.js - Functions for setting up a player without * user interaction based on the data-setup `attribute` of the video tag. * * @module setup */ var _windowLoaded = false; var videojs = void 0; /** * Set up any tags that have a data-setup `attribute` when the player is started. */ var autoSetup = function autoSetup() { // Protect against breakage in non-browser environments. if (!Dom.isReal()) { return; } // One day, when we stop supporting IE8, go back to this, but in the meantime...*hack hack hack* // var vids = Array.prototype.slice.call(document.getElementsByTagName('video')); // var audios = Array.prototype.slice.call(document.getElementsByTagName('audio')); // var mediaEls = vids.concat(audios); // Because IE8 doesn't support calling slice on a node list, we need to loop // through each list of elements to build up a new, combined list of elements. var vids = _document2['default'].getElementsByTagName('video'); var audios = _document2['default'].getElementsByTagName('audio'); var mediaEls = []; if (vids && vids.length > 0) { for (var i = 0, e = vids.length; i < e; i++) { mediaEls.push(vids[i]); } } if (audios && audios.length > 0) { for (var _i = 0, _e = audios.length; _i < _e; _i++) { mediaEls.push(audios[_i]); } } // Check if any media elements exist if (mediaEls && mediaEls.length > 0) { for (var _i2 = 0, _e2 = mediaEls.length; _i2 < _e2; _i2++) { var mediaEl = mediaEls[_i2]; // Check if element exists, has getAttribute func. // IE seems to consider typeof el.getAttribute == 'object' instead of // 'function' like expected, at least when loading the player immediately. if (mediaEl && mediaEl.getAttribute) { // Make sure this player hasn't already been set up. if (mediaEl.player === undefined) { var options = mediaEl.getAttribute('data-setup'); // Check if data-setup attr exists. // We only auto-setup if they've added the data-setup attr. if (options !== null) { // Create new video.js instance. videojs(mediaEl); } } // If getAttribute isn't defined, we need to wait for the DOM. } else { autoSetupTimeout(1); break; } } // No videos were found, so keep looping unless page is finished loading. } else if (!_windowLoaded) { autoSetupTimeout(1); } }; /** * Wait until the page is loaded before running autoSetup. This will be called in * autoSetup if `hasLoaded` returns false. * * @param {number} wait * How long to wait in ms * * @param {videojs} [vjs] * The videojs library function */ function autoSetupTimeout(wait, vjs) { if (vjs) { videojs = vjs; } _window2['default'].setTimeout(autoSetup, wait); } if (Dom.isReal() && _document2['default'].readyState === 'complete') { _windowLoaded = true; } else { /** * Listen for the load event on window, and set _windowLoaded to true. * * @listens load */ Events.one(_window2['default'], 'load', function () { _windowLoaded = true; }); } /** * check if the document has been loaded */ var hasLoaded = function hasLoaded() { return _windowLoaded; }; exports.autoSetup = autoSetup; exports.autoSetupTimeout = autoSetupTimeout; exports.hasLoaded = hasLoaded; },{"81":81,"82":82,"94":94,"95":95}],57:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(81); var Dom = _interopRequireWildcard(_dom); var _obj = _dereq_(88); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file slider.js */ /** * The base functionality for a slider. Can be vertical or horizontal. * For instance the volume bar or the seek bar on a video is a slider. * * @extends Component */ var Slider = function (_Component) { _inherits(Slider, _Component); /** * Create an instance of this class * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function Slider(player, options) { _classCallCheck(this, Slider); // Set property names to bar to match with the child Slider class is looking for var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.bar = _this.getChild(_this.options_.barName); // Set a horizontal or vertical class on the slider depending on the slider type _this.vertical(!!_this.options_.vertical); _this.on('mousedown', _this.handleMouseDown); _this.on('touchstart', _this.handleMouseDown); _this.on('focus', _this.handleFocus); _this.on('blur', _this.handleBlur); _this.on('click', _this.handleClick); _this.on(player, 'controlsvisible', _this.update); _this.on(player, _this.playerEvent, _this.update); return _this; } /** * Create the `Button`s DOM element. * * @param {string} type * Type of element to create. * * @param {Object} [props={}] * List of properties in Object form. * * @param {Object} [attributes={}] * list of attributes in Object form. * * @return {Element} * The element that gets created. */ Slider.prototype.createEl = function createEl(type) { var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var attributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; // Add the slider element class to all sub classes props.className = props.className + ' vjs-slider'; props = (0, _obj.assign)({ tabIndex: 0 }, props); attributes = (0, _obj.assign)({ 'role': 'slider', 'aria-valuenow': 0, 'aria-valuemin': 0, 'aria-valuemax': 100, 'tabIndex': 0 }, attributes); return _Component.prototype.createEl.call(this, type, props, attributes); }; /** * Handle `mousedown` or `touchstart` events on the `Slider`. * * @param {EventTarget~Event} event * `mousedown` or `touchstart` event that triggered this function * * @listens mousedown * @listens touchstart * @fires Slider#slideractive */ Slider.prototype.handleMouseDown = function handleMouseDown(event) { var doc = this.bar.el_.ownerDocument; event.preventDefault(); Dom.blockTextSelection(); this.addClass('vjs-sliding'); /** * Triggered when the slider is in an active state * * @event Slider#slideractive * @type {EventTarget~Event} */ this.trigger('slideractive'); this.on(doc, 'mousemove', this.handleMouseMove); this.on(doc, 'mouseup', this.handleMouseUp); this.on(doc, 'touchmove', this.handleMouseMove); this.on(doc, 'touchend', this.handleMouseUp); this.handleMouseMove(event); }; /** * Handle the `mousemove`, `touchmove`, and `mousedown` events on this `Slider`. * The `mousemove` and `touchmove` events will only only trigger this function during * `mousedown` and `touchstart`. This is due to {@link Slider#handleMouseDown} and * {@link Slider#handleMouseUp}. * * @param {EventTarget~Event} event * `mousedown`, `mousemove`, `touchstart`, or `touchmove` event that triggered * this function * * @listens mousemove * @listens touchmove */ Slider.prototype.handleMouseMove = function handleMouseMove(event) {}; /** * Handle `mouseup` or `touchend` events on the `Slider`. * * @param {EventTarget~Event} event * `mouseup` or `touchend` event that triggered this function. * * @listens touchend * @listens mouseup * @fires Slider#sliderinactive */ Slider.prototype.handleMouseUp = function handleMouseUp() { var doc = this.bar.el_.ownerDocument; Dom.unblockTextSelection(); this.removeClass('vjs-sliding'); /** * Triggered when the slider is no longer in an active state. * * @event Slider#sliderinactive * @type {EventTarget~Event} */ this.trigger('sliderinactive'); this.off(doc, 'mousemove', this.handleMouseMove); this.off(doc, 'mouseup', this.handleMouseUp); this.off(doc, 'touchmove', this.handleMouseMove); this.off(doc, 'touchend', this.handleMouseUp); this.update(); }; /** * Update the progress bar of the `Slider`. */ Slider.prototype.update = function update() { // In VolumeBar init we have a setTimeout for update that pops and update to the end of the // execution stack. The player is destroyed before then update will cause an error if (!this.el_) { return; } // If scrubbing, we could use a cached value to make the handle keep up with the user's mouse. // On HTML5 browsers scrubbing is really smooth, but some flash players are slow, so we might want to utilize this later. // var progress = (this.player_.scrubbing()) ? this.player_.getCache().currentTime / this.player_.duration() : this.player_.currentTime() / this.player_.duration(); var progress = this.getPercent(); var bar = this.bar; // If there's no bar... if (!bar) { return; } // Protect against no duration and other division issues if (typeof progress !== 'number' || progress !== progress || progress < 0 || progress === Infinity) { progress = 0; } // Convert to a percentage for setting var percentage = (progress * 100).toFixed(2) + '%'; // Set the new bar width or height if (this.vertical()) { bar.el().style.height = percentage; } else { bar.el().style.width = percentage; } }; /** * Calculate distance for slider * * @param {EventTarget~Event} event * The event that caused this function to run. * * @return {number} * The current position of the Slider. * - postition.x for vertical `Slider`s * - postition.y for horizontal `Slider`s */ Slider.prototype.calculateDistance = function calculateDistance(event) { var position = Dom.getPointerPosition(this.el_, event); if (this.vertical()) { return position.y; } return position.x; }; /** * Handle a `focus` event on this `Slider`. * * @param {EventTarget~Event} event * The `focus` event that caused this function to run. * * @listens focus */ Slider.prototype.handleFocus = function handleFocus() { this.on(this.bar.el_.ownerDocument, 'keydown', this.handleKeyPress); }; /** * Handle a `keydown` event on the `Slider`. Watches for left, rigth, up, and down * arrow keys. This function will only be called when the slider has focus. See * {@link Slider#handleFocus} and {@link Slider#handleBlur}. * * @param {EventTarget~Event} event * the `keydown` event that caused this function to run. * * @listens keydown */ Slider.prototype.handleKeyPress = function handleKeyPress(event) { // Left and Down Arrows if (event.which === 37 || event.which === 40) { event.preventDefault(); this.stepBack(); // Up and Right Arrows } else if (event.which === 38 || event.which === 39) { event.preventDefault(); this.stepForward(); } }; /** * Handle a `blur` event on this `Slider`. * * @param {EventTarget~Event} event * The `blur` event that caused this function to run. * * @listens blur */ Slider.prototype.handleBlur = function handleBlur() { this.off(this.bar.el_.ownerDocument, 'keydown', this.handleKeyPress); }; /** * Listener for click events on slider, used to prevent clicks * from bubbling up to parent elements like button menus. * * @param {Object} event * Event that caused this object to run */ Slider.prototype.handleClick = function handleClick(event) { event.stopImmediatePropagation(); event.preventDefault(); }; /** * Get/set if slider is horizontal for vertical * * @param {boolean} [bool] * - true if slider is vertical, * - false is horizontal * * @return {boolean|Slider} * - true if slider is vertical, and getting * - false is horizontal, and getting * - a reference to this object when setting */ Slider.prototype.vertical = function vertical(bool) { if (bool === undefined) { return this.vertical_ || false; } this.vertical_ = !!bool; if (this.vertical_) { this.addClass('vjs-slider-vertical'); } else { this.addClass('vjs-slider-horizontal'); } return this; }; return Slider; }(_component2['default']); _component2['default'].registerComponent('Slider', Slider); exports['default'] = Slider; },{"5":5,"81":81,"88":88}],58:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; /** * @file flash-rtmp.js * @module flash-rtmp */ /** * Add RTMP properties to the {@link Flash} Tech. * * @param {Flash} Flash * The flash tech class. * * @mixin FlashRtmpDecorator */ function FlashRtmpDecorator(Flash) { Flash.streamingFormats = { 'rtmp/mp4': 'MP4', 'rtmp/flv': 'FLV' }; /** * Join connection and stream with an ampersand. * * @param {string} connection * The connection string. * * @param {string} stream * The stream string. */ Flash.streamFromParts = function (connection, stream) { return connection + '&' + stream; }; /** * The flash parts object that contains connection and stream info. * * @typedef {Object} Flash~PartsObject * * @property {string} connection * The connection string of a source, defaults to an empty string. * * @property {string} stream * The stream string of the source, defaults to an empty string. */ /** * Convert a source url into a stream and connection parts. * * @param {string} src * the source url * * @return {Flash~PartsObject} * The parts object that contains a connection and a stream */ Flash.streamToParts = function (src) { var parts = { connection: '', stream: '' }; if (!src) { return parts; } // Look for the normal URL separator we expect, '&'. // If found, we split the URL into two pieces around the // first '&'. var connEnd = src.search(/&(?!\w+=)/); var streamBegin = void 0; if (connEnd !== -1) { streamBegin = connEnd + 1; } else { // If there's not a '&', we use the last '/' as the delimiter. connEnd = streamBegin = src.lastIndexOf('/') + 1; if (connEnd === 0) { // really, there's not a '/'? connEnd = streamBegin = src.length; } } parts.connection = src.substring(0, connEnd); parts.stream = src.substring(streamBegin, src.length); return parts; }; /** * Check if the source type is a streaming type. * * @param {string} srcType * The mime type to check. * * @return {boolean} * - True if the source type is a streaming type. * - False if the source type is not a streaming type. */ Flash.isStreamingType = function (srcType) { return srcType in Flash.streamingFormats; }; // RTMP has four variations, any string starting // with one of these protocols should be valid /** * Regular expression used to check if the source is an rtmp source. * * @property {RegExp} Flash.RTMP_RE */ Flash.RTMP_RE = /^rtmp[set]?:\/\//i; /** * Check if the source itself is a streaming type. * * @param {string} src * The url to the source. * * @return {boolean} * - True if the source url indicates that the source is streaming. * - False if the shource url indicates that the source url is not streaming. */ Flash.isStreamingSrc = function (src) { return Flash.RTMP_RE.test(src); }; /** * A source handler for RTMP urls * @type {Object} */ Flash.rtmpSourceHandler = {}; /** * Check if Flash can play the given mime type. * * @param {string} type * The mime type to check * * @return {string} * 'maybe', or '' (empty string) */ Flash.rtmpSourceHandler.canPlayType = function (type) { if (Flash.isStreamingType(type)) { return 'maybe'; } return ''; }; /** * Check if Flash can handle the source natively * * @param {Object} source * The source object * * @param {Object} [options] * The options passed to the tech * * @return {string} * 'maybe', or '' (empty string) */ Flash.rtmpSourceHandler.canHandleSource = function (source, options) { var can = Flash.rtmpSourceHandler.canPlayType(source.type); if (can) { return can; } if (Flash.isStreamingSrc(source.src)) { return 'maybe'; } return ''; }; /** * Pass the source to the flash object. * * @param {Object} source * The source object * * @param {Flash} tech * The instance of the Flash tech * * @param {Object} [options] * The options to pass to the source */ Flash.rtmpSourceHandler.handleSource = function (source, tech, options) { var srcParts = Flash.streamToParts(source.src); tech.setRtmpConnection(srcParts.connection); tech.setRtmpStream(srcParts.stream); }; // Register the native source handler Flash.registerSourceHandler(Flash.rtmpSourceHandler); return Flash; } exports['default'] = FlashRtmpDecorator; },{}],59:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _tech = _dereq_(62); var _tech2 = _interopRequireDefault(_tech); var _dom = _dereq_(81); var Dom = _interopRequireWildcard(_dom); var _url = _dereq_(92); var Url = _interopRequireWildcard(_url); var _timeRanges = _dereq_(90); var _flashRtmp = _dereq_(58); var _flashRtmp2 = _interopRequireDefault(_flashRtmp); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _window = _dereq_(95); var _window2 = _interopRequireDefault(_window); var _obj = _dereq_(88); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file flash.js * VideoJS-SWF - Custom Flash Player with HTML5-ish API * https://github.com/zencoder/video-js-swf * Not using setupTriggers. Using global onEvent func to distribute events */ var navigator = _window2['default'].navigator; /** * Flash Media Controller - Wrapper for Flash Media API * * @mixes FlashRtmpDecorator * @mixes Tech~SouceHandlerAdditions * @extends Tech */ var Flash = function (_Tech) { _inherits(Flash, _Tech); /** * Create an instance of this Tech. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} ready * Callback function to call when the `Flash` Tech is ready. */ function Flash(options, ready) { _classCallCheck(this, Flash); // Set the source when ready var _this = _possibleConstructorReturn(this, _Tech.call(this, options, ready)); if (options.source) { _this.ready(function () { this.setSource(options.source); }, true); } // Having issues with Flash reloading on certain page actions (hide/resize/fullscreen) in certain browsers // This allows resetting the playhead when we catch the reload if (options.startTime) { _this.ready(function () { this.load(); this.play(); this.currentTime(options.startTime); }, true); } // Add global window functions that the swf expects // A 4.x workflow we weren't able to solve for in 5.0 // because of the need to hard code these functions // into the swf for security reasons _window2['default'].videojs = _window2['default'].videojs || {}; _window2['default'].videojs.Flash = _window2['default'].videojs.Flash || {}; _window2['default'].videojs.Flash.onReady = Flash.onReady; _window2['default'].videojs.Flash.onEvent = Flash.onEvent; _window2['default'].videojs.Flash.onError = Flash.onError; _this.on('seeked', function () { this.lastSeekTarget_ = undefined; }); return _this; } /** * Create the `Flash` Tech's DOM element. * * @return {Element} * The element that gets created. */ Flash.prototype.createEl = function createEl() { var options = this.options_; // If video.js is hosted locally you should also set the location // for the hosted swf, which should be relative to the page (not video.js) // Otherwise this adds a CDN url. // The CDN also auto-adds a swf URL for that specific version. if (!options.swf) { var ver = '5.3.0'; options.swf = '//vjs.zencdn.net/swf/' + ver + '/video-js.swf'; } // Generate ID for swf object var objId = options.techId; // Merge default flashvars with ones passed in to init var flashVars = (0, _obj.assign)({ // SWF Callback Functions readyFunction: 'videojs.Flash.onReady', eventProxyFunction: 'videojs.Flash.onEvent', errorEventProxyFunction: 'videojs.Flash.onError', // Player Settings autoplay: options.autoplay, preload: options.preload, loop: options.loop, muted: options.muted }, options.flashVars); // Merge default parames with ones passed in var params = (0, _obj.assign)({ // Opaque is needed to overlay controls, but can affect playback performance wmode: 'opaque', // Using bgcolor prevents a white flash when the object is loading bgcolor: '#000000' }, options.params); // Merge default attributes with ones passed in var attributes = (0, _obj.assign)({ // Both ID and Name needed or swf to identify itself id: objId, name: objId, 'class': 'vjs-tech' }, options.attributes); this.el_ = Flash.embed(options.swf, flashVars, params, attributes); this.el_.tech = this; return this.el_; }; /** * Called by {@link Player#play} to play using the `Flash` `Tech`. */ Flash.prototype.play = function play() { if (this.ended()) { this.setCurrentTime(0); } this.el_.vjs_play(); }; /** * Called by {@link Player#pause} to pause using the `Flash` `Tech`. */ Flash.prototype.pause = function pause() { this.el_.vjs_pause(); }; /** * A getter/setter for the `Flash` Tech's source object. * > Note: Please use {@link Flash#setSource} * * @param {Tech~SourceObject} [src] * The source object you want to set on the `Flash` techs. * * @return {Tech~SourceObject|undefined} * - The current source object when a source is not passed in. * - undefined when setting * * @deprecated Since version 5. */ Flash.prototype.src = function src(_src) { if (_src === undefined) { return this.currentSrc(); } // Setting src through `src` not `setSrc` will be deprecated return this.setSrc(_src); }; /** * A getter/setter for the `Flash` Tech's source object. * * @param {Tech~SourceObject} [src] * The source object you want to set on the `Flash` techs. * * @return {Tech~SourceObject|undefined} * - The current source object when a source is not passed in. * - undefined when setting */ Flash.prototype.setSrc = function setSrc(src) { var _this2 = this; // Make sure source URL is absolute. src = Url.getAbsoluteURL(src); this.el_.vjs_src(src); // Currently the SWF doesn't autoplay if you load a source later. // e.g. Load player w/ no source, wait 2s, set src. if (this.autoplay()) { this.setTimeout(function () { return _this2.play(); }, 0); } }; /** * Indicates whether the media is currently seeking to a new position or not. * * @return {boolean} * - True if seeking to a new position * - False otherwise */ Flash.prototype.seeking = function seeking() { return this.lastSeekTarget_ !== undefined; }; /** * Returns the current time in seconds that the media is at in playback. * * @param {number} time * Current playtime of the media in seconds. */ Flash.prototype.setCurrentTime = function setCurrentTime(time) { var seekable = this.seekable(); if (seekable.length) { // clamp to the current seekable range time = time > seekable.start(0) ? time : seekable.start(0); time = time < seekable.end(seekable.length - 1) ? time : seekable.end(seekable.length - 1); this.lastSeekTarget_ = time; this.trigger('seeking'); this.el_.vjs_setProperty('currentTime', time); _Tech.prototype.setCurrentTime.call(this); } }; /** * Get the current playback time in seconds * * @return {number} * The current time of playback in seconds. */ Flash.prototype.currentTime = function currentTime() { // when seeking make the reported time keep up with the requested time // by reading the time we're seeking to if (this.seeking()) { return this.lastSeekTarget_ || 0; } return this.el_.vjs_getProperty('currentTime'); }; /** * Get the current source * * @method currentSrc * @return {Tech~SourceObject} * The current source */ Flash.prototype.currentSrc = function currentSrc() { if (this.currentSource_) { return this.currentSource_.src; } return this.el_.vjs_getProperty('currentSrc'); }; /** * Get the total duration of the current media. * * @return {number} 8 The total duration of the current media. */ Flash.prototype.duration = function duration() { if (this.readyState() === 0) { return NaN; } var duration = this.el_.vjs_getProperty('duration'); return duration >= 0 ? duration : Infinity; }; /** * Load media into Tech. */ Flash.prototype.load = function load() { this.el_.vjs_load(); }; /** * Get the poster image that was set on the tech. */ Flash.prototype.poster = function poster() { this.el_.vjs_getProperty('poster'); }; /** * Poster images are not handled by the Flash tech so make this is a no-op. */ Flash.prototype.setPoster = function setPoster() {}; /** * Determine the time ranges that can be seeked to in the media. * * @return {TimeRange} * Returns the time ranges that can be seeked to. */ Flash.prototype.seekable = function seekable() { var duration = this.duration(); if (duration === 0) { return (0, _timeRanges.createTimeRange)(); } return (0, _timeRanges.createTimeRange)(0, duration); }; /** * Get and create a `TimeRange` object for buffering. * * @return {TimeRange} * The time range object that was created. */ Flash.prototype.buffered = function buffered() { var ranges = this.el_.vjs_getProperty('buffered'); if (ranges.length === 0) { return (0, _timeRanges.createTimeRange)(); } return (0, _timeRanges.createTimeRange)(ranges[0][0], ranges[0][1]); }; /** * Get fullscreen support - * * Flash does not allow fullscreen through javascript * so this always returns false. * * @return {boolean} * The Flash tech does not support fullscreen, so it will always return false. */ Flash.prototype.supportsFullScreen = function supportsFullScreen() { // Flash does not allow fullscreen through javascript return false; }; /** * Flash does not allow fullscreen through javascript * so this always returns false. * * @return {boolean} * The Flash tech does not support fullscreen, so it will always return false. */ Flash.prototype.enterFullScreen = function enterFullScreen() { return false; }; return Flash; }(_tech2['default']); // Create setters and getters for attributes var _api = Flash.prototype; var _readWrite = 'rtmpConnection,rtmpStream,preload,defaultPlaybackRate,playbackRate,autoplay,loop,mediaGroup,controller,controls,volume,muted,defaultMuted'.split(','); var _readOnly = 'networkState,readyState,initialTime,startOffsetTime,paused,ended,videoWidth,videoHeight'.split(','); function _createSetter(attr) { var attrUpper = attr.charAt(0).toUpperCase() + attr.slice(1); _api['set' + attrUpper] = function (val) { return this.el_.vjs_setProperty(attr, val); }; } function _createGetter(attr) { _api[attr] = function () { return this.el_.vjs_getProperty(attr); }; } // Create getter and setters for all read/write attributes for (var i = 0; i < _readWrite.length; i++) { _createGetter(_readWrite[i]); _createSetter(_readWrite[i]); } // Create getters for read-only attributes for (var _i = 0; _i < _readOnly.length; _i++) { _createGetter(_readOnly[_i]); } /** ------------------------------ Getters ------------------------------ **/ /** * Get the value of `rtmpConnection` from the swf. * * @method Flash#rtmpConnection * @return {string} * The current value of `rtmpConnection` on the swf. */ /** * Get the value of `rtmpStream` from the swf. * * @method Flash#rtmpStream * @return {string} * The current value of `rtmpStream` on the swf. */ /** * Get the value of `preload` from the swf. `preload` indicates * what should download before the media is interacted with. It can have the following * values: * - none: nothing should be downloaded * - metadata: poster and the first few frames of the media may be downloaded to get * media dimensions and other metadata * - auto: allow the media and metadata for the media to be downloaded before * interaction * * @method Flash#preload * @return {string} * The value of `preload` from the swf. Will be 'none', 'metadata', * or 'auto'. */ /** * Get the value of `defaultPlaybackRate` from the swf. * * @method Flash#defaultPlaybackRate * @return {number} * The current value of `defaultPlaybackRate` on the swf. */ /** * Get the value of `playbackRate` from the swf. `playbackRate` indicates * the rate at which the media is currently playing back. Examples: * - if playbackRate is set to 2, media will play twice as fast. * - if playbackRate is set to 0.5, media will play half as fast. * * @method Flash#playbackRate * @return {number} * The value of `playbackRate` from the swf. A number indicating * the current playback speed of the media, where 1 is normal speed. */ /** * Get the value of `autoplay` from the swf. `autoplay` indicates * that the media should start to play as soon as the page is ready. * * @method Flash#autoplay * @return {boolean} * - The value of `autoplay` from the swf. * - True indicates that the media ashould start as soon as the page loads. * - False indicates that the media should not start as soon as the page loads. */ /** * Get the value of `loop` from the swf. `loop` indicates * that the media should return to the start of the media and continue playing once * it reaches the end. * * @method Flash#loop * @return {boolean} * - The value of `loop` from the swf. * - True indicates that playback should seek back to start once * the end of a media is reached. * - False indicates that playback should not loop back to the start when the * end of the media is reached. */ /** * Get the value of `mediaGroup` from the swf. * * @method Flash#mediaGroup * @return {string} * The current value of `mediaGroup` on the swf. */ /** * Get the value of `controller` from the swf. * * @method Flash#controller * @return {string} * The current value of `controller` on the swf. */ /** * Get the value of `controls` from the swf. `controls` indicates * whether the native flash controls should be shown or hidden. * * @method Flash#controls * @return {boolean} * - The value of `controls` from the swf. * - True indicates that native controls should be showing. * - False indicates that native controls should be hidden. */ /** * Get the value of the `volume` from the swf. `volume` indicates the current * audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and * so on. * * @method Flash#volume * @return {number} * The volume percent as a decimal. Value will be between 0-1. */ /** * Get the value of the `muted` from the swf. `muted` indicates the current * audio level should be silent. * * @method Flash#muted * @return {boolean} * - True if the audio should be set to silent * - False otherwise */ /** * Get the value of `defaultMuted` from the swf. `defaultMuted` indicates * whether the media should start muted or not. Only changes the default state of the * media. `muted` and `defaultMuted` can have different values. `muted` indicates the * current state. * * @method Flash#defaultMuted * @return {boolean} * - The value of `defaultMuted` from the swf. * - True indicates that the media should start muted. * - False indicates that the media should not start muted. */ /** * Get the value of `networkState` from the swf. `networkState` indicates * the current network state. It returns an enumeration from the following list: * - 0: NETWORK_EMPTY * - 1: NEWORK_IDLE * - 2: NETWORK_LOADING * - 3: NETWORK_NO_SOURCE * * @method Flash#networkState * @return {number} * The value of `networkState` from the swf. This will be a number * from the list in the description. */ /** * Get the value of `readyState` from the swf. `readyState` indicates * the current state of the media element. It returns an enumeration from the * following list: * - 0: HAVE_NOTHING * - 1: HAVE_METADATA * - 2: HAVE_CURRENT_DATA * - 3: HAVE_FUTURE_DATA * - 4: HAVE_ENOUGH_DATA * * @method Flash#readyState * @return {number} * The value of `readyState` from the swf. This will be a number * from the list in the description. */ /** * Get the value of `readyState` from the swf. `readyState` indicates * the current state of the media element. It returns an enumeration from the * following list: * - 0: HAVE_NOTHING * - 1: HAVE_METADATA * - 2: HAVE_CURRENT_DATA * - 3: HAVE_FUTURE_DATA * - 4: HAVE_ENOUGH_DATA * * @method Flash#readyState * @return {number} * The value of `readyState` from the swf. This will be a number * from the list in the description. */ /** * Get the value of `initialTime` from the swf. * * @method Flash#initialTime * @return {number} * The `initialTime` proprety on the swf. */ /** * Get the value of `startOffsetTime` from the swf. * * @method Flash#startOffsetTime * @return {number} * The `startOffsetTime` proprety on the swf. */ /** * Get the value of `paused` from the swf. `paused` indicates whether the swf * is current paused or not. * * @method Flash#paused * @return {boolean} * The value of `paused` from the swf. */ /** * Get the value of `ended` from the swf. `ended` indicates whether * the media has reached the end or not. * * @method Flash#ended * @return {boolean} * - True indicates that the media has ended. * - False indicates that the media has not ended. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-ended} */ /** * Get the value of `videoWidth` from the swf. `videoWidth` indicates * the current width of the media in css pixels. * * @method Flash#videoWidth * @return {number} * The value of `videoWidth` from the swf. This will be a number * in css pixels. */ /** * Get the value of `videoHeight` from the swf. `videoHeigth` indicates * the current height of the media in css pixels. * * @method Flassh.prototype.videoHeight * @return {number} * The value of `videoHeight` from the swf. This will be a number * in css pixels. */ /** ------------------------------ Setters ------------------------------ **/ /** * Set the value of `rtmpConnection` on the swf. * * @method Flash#setRtmpConnection * @param {string} rtmpConnection * New value to set the `rtmpConnection` property to. */ /** * Set the value of `rtmpStream` on the swf. * * @method Flash#setRtmpStream * @param {string} rtmpStream * New value to set the `rtmpStream` property to. */ /** * Set the value of `preload` on the swf. `preload` indicates * what should download before the media is interacted with. It can have the following * values: * - none: nothing should be downloaded * - metadata: poster and the first few frames of the media may be downloaded to get * media dimensions and other metadata * - auto: allow the media and metadata for the media to be downloaded before * interaction * * @method Flash#setPreload * @param {string} preload * The value of `preload` to set on the swf. Should be 'none', 'metadata', * or 'auto'. */ /** * Set the value of `defaultPlaybackRate` on the swf. * * @method Flash#setDefaultPlaybackRate * @param {number} defaultPlaybackRate * New value to set the `defaultPlaybackRate` property to. */ /** * Set the value of `playbackRate` on the swf. `playbackRate` indicates * the rate at which the media is currently playing back. Examples: * - if playbackRate is set to 2, media will play twice as fast. * - if playbackRate is set to 0.5, media will play half as fast. * * @method Flash#setPlaybackRate * @param {number} playbackRate * New value of `playbackRate` on the swf. A number indicating * the current playback speed of the media, where 1 is normal speed. */ /** * Set the value of `autoplay` on the swf. `autoplay` indicates * that the media should start to play as soon as the page is ready. * * @method Flash#setAutoplay * @param {boolean} autoplay * - The value of `autoplay` from the swf. * - True indicates that the media ashould start as soon as the page loads. * - False indicates that the media should not start as soon as the page loads. */ /** * Set the value of `loop` on the swf. `loop` indicates * that the media should return to the start of the media and continue playing once * it reaches the end. * * @method Flash#setLoop * @param {boolean} loop * - True indicates that playback should seek back to start once * the end of a media is reached. * - False indicates that playback should not loop back to the start when the * end of the media is reached. */ /** * Set the value of `mediaGroup` on the swf. * * @method Flash#setMediaGroup * @param {string} mediaGroup * New value of `mediaGroup` to set on the swf. */ /** * Set the value of `controller` on the swf. * * @method Flash#setController * @param {string} controller * New value the current value of `controller` on the swf. */ /** * Get the value of `controls` from the swf. `controls` indicates * whether the native flash controls should be shown or hidden. * * @method Flash#controls * @return {boolean} * - The value of `controls` from the swf. * - True indicates that native controls should be showing. * - False indicates that native controls should be hidden. */ /** * Set the value of the `volume` on the swf. `volume` indicates the current * audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and * so on. * * @method Flash#setVolume * @param {number} percentAsDecimal * The volume percent as a decimal. Value will be between 0-1. */ /** * Set the value of the `muted` on the swf. `muted` indicates that the current * audio level should be silent. * * @method Flash#setMuted * @param {boolean} muted * - True if the audio should be set to silent * - False otherwise */ /** * Set the value of `defaultMuted` on the swf. `defaultMuted` indicates * whether the media should start muted or not. Only changes the default state of the * media. `muted` and `defaultMuted` can have different values. `muted` indicates the * current state. * * @method Flash#setDefaultMuted * @param {boolean} defaultMuted * - True indicates that the media should start muted. * - False indicates that the media should not start muted. */ /* Flash Support Testing -------------------------------------------------------- */ /** * Check if the Flash tech is currently supported. * * @return {boolean} * - True if the flash tech is supported. * - False otherwise. */ Flash.isSupported = function () { return Flash.version()[0] >= 10; // return swfobject.hasFlashPlayerVersion('10'); }; // Add Source Handler pattern functions to this tech _tech2['default'].withSourceHandlers(Flash); /* * Native source handler for flash, simply passes the source to the swf element. * * @property {Tech~SourceObject} source * The source object * * @property {Flash} tech * The instance of the Flash tech */ Flash.nativeSourceHandler = {}; /** * Check if the Flash can play the given mime type. * * @param {string} type * The mimetype to check * * @return {string} * 'maybe', or '' (empty string) */ Flash.nativeSourceHandler.canPlayType = function (type) { if (type in Flash.formats) { return 'maybe'; } return ''; }; /** * Check if the media element can handle a source natively. * * @param {Tech~SourceObject} source * The source object * * @param {Object} [options] * Options to be passed to the tech. * * @return {string} * 'maybe', or '' (empty string). */ Flash.nativeSourceHandler.canHandleSource = function (source, options) { var type = void 0; function guessMimeType(src) { var ext = Url.getFileExtension(src); if (ext) { return 'video/' + ext; } return ''; } if (!source.type) { type = guessMimeType(source.src); } else { // Strip code information from the type because we don't get that specific type = source.type.replace(/;.*/, '').toLowerCase(); } return Flash.nativeSourceHandler.canPlayType(type); }; /** * Pass the source to the swf. * * @param {Tech~SourceObject} source * The source object * * @param {Flash} tech * The instance of the Flash tech * * @param {Object} [options] * The options to pass to the source */ Flash.nativeSourceHandler.handleSource = function (source, tech, options) { tech.setSrc(source.src); }; /** * noop for native source handler dispose, as cleanup will happen automatically. */ Flash.nativeSourceHandler.dispose = function () {}; // Register the native source handler Flash.registerSourceHandler(Flash.nativeSourceHandler); /** * Flash supported mime types. * * @constant {Object} */ Flash.formats = { 'video/flv': 'FLV', 'video/x-flv': 'FLV', 'video/mp4': 'MP4', 'video/m4v': 'MP4' }; /** * Called when the the swf is "ready", and makes sure that the swf is really * ready using {@link Flash#checkReady} */ Flash.onReady = function (currSwf) { var el = Dom.getEl(currSwf); var tech = el && el.tech; // if there is no el then the tech has been disposed // and the tech element was removed from the player div if (tech && tech.el()) { // check that the flash object is really ready Flash.checkReady(tech); } }; /** * The SWF isn't always ready when it says it is. Sometimes the API functions still * need to be added to the object. If it's not ready, we set a timeout to check again * shortly. * * @param {Flash} tech * The instance of the flash tech to check. */ Flash.checkReady = function (tech) { // stop worrying if the tech has been disposed if (!tech.el()) { return; } // check if API property exists if (tech.el().vjs_getProperty) { // tell tech it's ready tech.triggerReady(); } else { // wait longer this.setTimeout(function () { Flash.checkReady(tech); }, 50); } }; /** * Trigger events from the swf on the Flash Tech. * * @param {number} swfID * The id of the swf that had the event * * @param {string} eventName * The name of the event to trigger */ Flash.onEvent = function (swfID, eventName) { var tech = Dom.getEl(swfID).tech; var args = Array.prototype.slice.call(arguments, 2); // dispatch Flash events asynchronously for two reasons: // - Flash swallows any exceptions generated by javascript it // invokes // - Flash is suspended until the javascript returns which may cause // playback performance issues tech.setTimeout(function () { tech.trigger(eventName, args); }, 1); }; /** * Log errors from the swf on the Flash tech. * * @param {number} swfID * The id of the swf that had an error. * * @param {string} The error string * The error to set on the Flash Tech. * * @return {MediaError|undefined} * - Returns a MediaError when err is 'srcnotfound' * - Returns undefined otherwise. */ Flash.onError = function (swfID, err) { var tech = Dom.getEl(swfID).tech; // trigger MEDIA_ERR_SRC_NOT_SUPPORTED if (err === 'srcnotfound') { return tech.error(4); } // trigger a custom error tech.error('FLASH: ' + err); }; /** * Get the current version of Flash that is in use on the page. * * @return {Array} * an array of versions that are available. */ Flash.version = function () { var version = '0,0,0'; // IE try { version = new _window2['default'].ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; // other browsers } catch (e) { try { if (navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin) { version = (navigator.plugins['Shockwave Flash 2.0'] || navigator.plugins['Shockwave Flash']).description.replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; } } catch (err) { // satisfy linter } } return version.split(','); }; /** * Only use for non-iframe embeds. * * @param {Object} swf * The videojs-swf object. * * @param {Object} flashVars * Names and values to use as flash option variables. * * @param {Object} params * Style parameters to set on the object. * * @param {Object} attributes * Attributes to set on the element. * * @return {Element} * The embeded Flash DOM element. */ Flash.embed = function (swf, flashVars, params, attributes) { var code = Flash.getEmbedCode(swf, flashVars, params, attributes); // Get element by embedding code and retrieving created element var obj = Dom.createEl('div', { innerHTML: code }).childNodes[0]; return obj; }; /** * Only use for non-iframe embeds. * * @param {Object} swf * The videojs-swf object. * * @param {Object} flashVars * Names and values to use as flash option variables. * * @param {Object} params * Style parameters to set on the object. * * @param {Object} attributes * Attributes to set on the element. * * @return {Element} * The embeded Flash DOM element. */ Flash.getEmbedCode = function (swf, flashVars, params, attributes) { var objTag = '<object type="application/x-shockwave-flash" '; var flashVarsString = ''; var paramsString = ''; var attrsString = ''; // Convert flash vars to string if (flashVars) { Object.getOwnPropertyNames(flashVars).forEach(function (key) { flashVarsString += key + '=' + flashVars[key] + '&amp;'; }); } // Add swf, flashVars, and other default params params = (0, _obj.assign)({ movie: swf, flashvars: flashVarsString, // Required to talk to swf allowScriptAccess: 'always', // All should be default, but having security issues. allowNetworking: 'all' }, params); // Create param tags string Object.getOwnPropertyNames(params).forEach(function (key) { paramsString += '<param name="' + key + '" value="' + params[key] + '" />'; }); attributes = (0, _obj.assign)({ // Add swf to attributes (need both for IE and Others to work) data: swf, // Default to 100% width/height width: '100%', height: '100%' }, attributes); // Create Attributes string Object.getOwnPropertyNames(attributes).forEach(function (key) { attrsString += key + '="' + attributes[key] + '" '; }); return '' + objTag + attrsString + '>' + paramsString + '</object>'; }; // Run Flash through the RTMP decorator (0, _flashRtmp2['default'])(Flash); _component2['default'].registerComponent('Flash', Flash); _tech2['default'].registerTech('Flash', Flash); exports['default'] = Flash; },{"5":5,"58":58,"62":62,"81":81,"88":88,"90":90,"92":92,"95":95}],60:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _templateObject = _taggedTemplateLiteralLoose(['Text Tracks are being loaded from another origin but the crossorigin attribute isn\'t used.\n This may prevent text tracks from loading.'], ['Text Tracks are being loaded from another origin but the crossorigin attribute isn\'t used.\n This may prevent text tracks from loading.']); var _tech = _dereq_(62); var _tech2 = _interopRequireDefault(_tech); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(81); var Dom = _interopRequireWildcard(_dom); var _url = _dereq_(92); var Url = _interopRequireWildcard(_url); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); var _log = _dereq_(86); var _log2 = _interopRequireDefault(_log); var _tsml = _dereq_(98); var _tsml2 = _interopRequireDefault(_tsml); var _browser = _dereq_(78); var browser = _interopRequireWildcard(_browser); var _document = _dereq_(94); var _document2 = _interopRequireDefault(_document); var _window = _dereq_(95); var _window2 = _interopRequireDefault(_window); var _obj = _dereq_(88); var _mergeOptions = _dereq_(87); var _mergeOptions2 = _interopRequireDefault(_mergeOptions); var _toTitleCase = _dereq_(91); var _toTitleCase2 = _interopRequireDefault(_toTitleCase); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _taggedTemplateLiteralLoose(strings, raw) { strings.raw = raw; return strings; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file html5.js */ /** * HTML5 Media Controller - Wrapper for HTML5 Media API * * @mixes Tech~SouceHandlerAdditions * @extends Tech */ var Html5 = function (_Tech) { _inherits(Html5, _Tech); /** * Create an instance of this Tech. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} ready * Callback function to call when the `HTML5` Tech is ready. */ function Html5(options, ready) { _classCallCheck(this, Html5); var _this = _possibleConstructorReturn(this, _Tech.call(this, options, ready)); var source = options.source; var crossoriginTracks = false; // Set the source if one is provided // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted) // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source // anyway so the error gets fired. if (source && (_this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) { _this.setSource(source); } else { _this.handleLateInit_(_this.el_); } if (_this.el_.hasChildNodes()) { var nodes = _this.el_.childNodes; var nodesLength = nodes.length; var removeNodes = []; while (nodesLength--) { var node = nodes[nodesLength]; var nodeName = node.nodeName.toLowerCase(); if (nodeName === 'track') { if (!_this.featuresNativeTextTracks) { // Empty video tag tracks so the built-in player doesn't use them also. // This may not be fast enough to stop HTML5 browsers from reading the tags // so we'll need to turn off any default tracks if we're manually doing // captions and subtitles. videoElement.textTracks removeNodes.push(node); } else { // store HTMLTrackElement and TextTrack to remote list _this.remoteTextTrackEls().addTrackElement_(node); _this.remoteTextTracks().addTrack_(node.track); if (!crossoriginTracks && !_this.el_.hasAttribute('crossorigin') && Url.isCrossOrigin(node.src)) { crossoriginTracks = true; } } } } for (var i = 0; i < removeNodes.length; i++) { _this.el_.removeChild(removeNodes[i]); } } // TODO: add text tracks into this list var trackTypes = ['audio', 'video']; // ProxyNative Video/Audio Track trackTypes.forEach(function (type) { var elTracks = _this.el()[type + 'Tracks']; var techTracks = _this[type + 'Tracks'](); var capitalType = (0, _toTitleCase2['default'])(type); if (!_this['featuresNative' + capitalType + 'Tracks'] || !elTracks || !elTracks.addEventListener) { return; } _this['handle' + capitalType + 'TrackChange_'] = function (e) { techTracks.trigger({ type: 'change', target: techTracks, currentTarget: techTracks, srcElement: techTracks }); }; _this['handle' + capitalType + 'TrackAdd_'] = function (e) { return techTracks.addTrack(e.track); }; _this['handle' + capitalType + 'TrackRemove_'] = function (e) { return techTracks.removeTrack(e.track); }; elTracks.addEventListener('change', _this['handle' + capitalType + 'TrackChange_']); elTracks.addEventListener('addtrack', _this['handle' + capitalType + 'TrackAdd_']); elTracks.addEventListener('removetrack', _this['handle' + capitalType + 'TrackRemove_']); _this['removeOld' + capitalType + 'Tracks_'] = function (e) { return _this.removeOldTracks_(techTracks, elTracks); }; // Remove (native) tracks that are not used anymore _this.on('loadstart', _this['removeOld' + capitalType + 'Tracks_']); }); if (_this.featuresNativeTextTracks) { if (crossoriginTracks) { _log2['default'].warn((0, _tsml2['default'])(_templateObject)); } _this.handleTextTrackChange_ = Fn.bind(_this, _this.handleTextTrackChange); _this.handleTextTrackAdd_ = Fn.bind(_this, _this.handleTextTrackAdd); _this.handleTextTrackRemove_ = Fn.bind(_this, _this.handleTextTrackRemove); _this.proxyNativeTextTracks_(); } // Determine if native controls should be used // Our goal should be to get the custom controls on mobile solid everywhere // so we can remove this all together. Right now this will block custom // controls on touch enabled laptops like the Chrome Pixel if ((browser.TOUCH_ENABLED || browser.IS_IPHONE || browser.IS_NATIVE_ANDROID) && options.nativeControlsForTouch === true) { _this.setControls(true); } // on iOS, we want to proxy `webkitbeginfullscreen` and `webkitendfullscreen` // into a `fullscreenchange` event _this.proxyWebkitFullscreen_(); _this.triggerReady(); return _this; } /** * Dispose of `HTML5` media element and remove all tracks. */ Html5.prototype.dispose = function dispose() { var _this2 = this; // Un-ProxyNativeTracks ['audio', 'video', 'text'].forEach(function (type) { var capitalType = (0, _toTitleCase2['default'])(type); var tl = _this2.el_[type + 'Tracks']; if (tl && tl.removeEventListener) { tl.removeEventListener('change', _this2['handle' + capitalType + 'TrackChange_']); tl.removeEventListener('addtrack', _this2['handle' + capitalType + 'TrackAdd_']); tl.removeEventListener('removetrack', _this2['handle' + capitalType + 'TrackRemove_']); } // Stop removing old text tracks if (tl) { _this2.off('loadstart', _this2['removeOld' + capitalType + 'Tracks_']); } }); Html5.disposeMediaElement(this.el_); // tech will handle clearing of the emulated track list _Tech.prototype.dispose.call(this); }; /** * Create the `Html5` Tech's DOM element. * * @return {Element} * The element that gets created. */ Html5.prototype.createEl = function createEl() { var el = this.options_.tag; // Check if this browser supports moving the element into the box. // On the iPhone video will break if you move the element, // So we have to create a brand new element. // If we ingested the player div, we do not need to move the media element. if (!el || !(this.options_.playerElIngest || this.movingMediaElementInDOM)) { // If the original tag is still there, clone and remove it. if (el) { var clone = el.cloneNode(true); if (el.parentNode) { el.parentNode.insertBefore(clone, el); } Html5.disposeMediaElement(el); el = clone; } else { el = _document2['default'].createElement('video'); // determine if native controls should be used var tagAttributes = this.options_.tag && Dom.getElAttributes(this.options_.tag); var attributes = (0, _mergeOptions2['default'])({}, tagAttributes); if (!browser.TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) { delete attributes.controls; } Dom.setElAttributes(el, (0, _obj.assign)(attributes, { id: this.options_.techId, 'class': 'vjs-tech' })); } el.playerId = this.options_.playerId; } // Update specific tag settings, in case they were overridden var settingsAttrs = ['autoplay', 'preload', 'loop', 'muted']; for (var i = settingsAttrs.length - 1; i >= 0; i--) { var attr = settingsAttrs[i]; var overwriteAttrs = {}; if (typeof this.options_[attr] !== 'undefined') { overwriteAttrs[attr] = this.options_[attr]; } Dom.setElAttributes(el, overwriteAttrs); } return el; }; /** * This will be triggered if the loadstart event has already fired, before videojs was * ready. Two known examples of when this can happen are: * 1. If we're loading the playback object after it has started loading * 2. The media is already playing the (often with autoplay on) then * * This function will fire another loadstart so that videojs can catchup. * * @fires Tech#loadstart * * @return {undefined} * returns nothing. */ Html5.prototype.handleLateInit_ = function handleLateInit_(el) { if (el.networkState === 0 || el.networkState === 3) { // The video element hasn't started loading the source yet // or didn't find a source return; } if (el.readyState === 0) { // NetworkState is set synchronously BUT loadstart is fired at the // end of the current stack, usually before setInterval(fn, 0). // So at this point we know loadstart may have already fired or is // about to fire, and either way the player hasn't seen it yet. // We don't want to fire loadstart prematurely here and cause a // double loadstart so we'll wait and see if it happens between now // and the next loop, and fire it if not. // HOWEVER, we also want to make sure it fires before loadedmetadata // which could also happen between now and the next loop, so we'll // watch for that also. var loadstartFired = false; var setLoadstartFired = function setLoadstartFired() { loadstartFired = true; }; this.on('loadstart', setLoadstartFired); var triggerLoadstart = function triggerLoadstart() { // We did miss the original loadstart. Make sure the player // sees loadstart before loadedmetadata if (!loadstartFired) { this.trigger('loadstart'); } }; this.on('loadedmetadata', triggerLoadstart); this.ready(function () { this.off('loadstart', setLoadstartFired); this.off('loadedmetadata', triggerLoadstart); if (!loadstartFired) { // We did miss the original native loadstart. Fire it now. this.trigger('loadstart'); } }); return; } // From here on we know that loadstart already fired and we missed it. // The other readyState events aren't as much of a problem if we double // them, so not going to go to as much trouble as loadstart to prevent // that unless we find reason to. var eventsToTrigger = ['loadstart']; // loadedmetadata: newly equal to HAVE_METADATA (1) or greater eventsToTrigger.push('loadedmetadata'); // loadeddata: newly increased to HAVE_CURRENT_DATA (2) or greater if (el.readyState >= 2) { eventsToTrigger.push('loadeddata'); } // canplay: newly increased to HAVE_FUTURE_DATA (3) or greater if (el.readyState >= 3) { eventsToTrigger.push('canplay'); } // canplaythrough: newly equal to HAVE_ENOUGH_DATA (4) if (el.readyState >= 4) { eventsToTrigger.push('canplaythrough'); } // We still need to give the player time to add event listeners this.ready(function () { eventsToTrigger.forEach(function (type) { this.trigger(type); }, this); }); }; /** * Add event listeners to native text track events. This adds the native text tracks * to our emulated {@link TextTrackList}. */ Html5.prototype.proxyNativeTextTracks_ = function proxyNativeTextTracks_() { var tt = this.el().textTracks; if (tt) { // Add tracks - if player is initialised after DOM loaded, textTracks // will not trigger addtrack for (var i = 0; i < tt.length; i++) { this.textTracks().addTrack_(tt[i]); } if (tt.addEventListener) { tt.addEventListener('change', this.handleTextTrackChange_); tt.addEventListener('addtrack', this.handleTextTrackAdd_); tt.addEventListener('removetrack', this.handleTextTrackRemove_); } // Remove (native) texttracks that are not used anymore this.on('loadstart', this.removeOldTextTracks_); } }; /** * Handle any {@link TextTrackList} `change` event. * * @param {EventTarget~Event} e * The `change` event that caused this to run. * * @listens TextTrackList#change */ Html5.prototype.handleTextTrackChange = function handleTextTrackChange(e) { var tt = this.textTracks(); this.textTracks().trigger({ type: 'change', target: tt, currentTarget: tt, srcElement: tt }); }; /** * Handle any {@link TextTrackList} `addtrack` event. * * @param {EventTarget~Event} e * The `addtrack` event that caused this to run. * * @listens TextTrackList#addtrack */ Html5.prototype.handleTextTrackAdd = function handleTextTrackAdd(e) { this.textTracks().addTrack_(e.track); }; /** * Handle any {@link TextTrackList} `removetrack` event. * * @param {EventTarget~Event} e * The `removetrack` event that caused this to run. * * @listens TextTrackList#removetrack */ Html5.prototype.handleTextTrackRemove = function handleTextTrackRemove(e) { this.textTracks().removeTrack_(e.track); }; /** * This function removes any {@link AudioTrack}s, {@link VideoTrack}s, or * {@link TextTrack}s that are not in the media elements TrackList. * * @param {TrackList} techTracks * HTML5 Tech's TrackList to search through * * @param {TrackList} elTracks * HTML5 media elements TrackList to search trough. * * @private */ Html5.prototype.removeOldTracks_ = function removeOldTracks_(techTracks, elTracks) { // This will loop over the techTracks and check if they are still used by the HTML5 media element // If not, they will be removed from the emulated list var removeTracks = []; if (!elTracks) { return; } for (var i = 0; i < techTracks.length; i++) { var techTrack = techTracks[i]; var found = false; for (var j = 0; j < elTracks.length; j++) { if (elTracks[j] === techTrack) { found = true; break; } } if (!found) { removeTracks.push(techTrack); } } for (var _i = 0; _i < removeTracks.length; _i++) { var track = removeTracks[_i]; techTracks.removeTrack_(track); } }; /** * Remove {@link TextTrack}s that dont exist in the native track list from our * emulated {@link TextTrackList}. * * @listens Tech#loadstart */ Html5.prototype.removeOldTextTracks_ = function removeOldTextTracks_(e) { var techTracks = this.textTracks(); var elTracks = this.el().textTracks; this.removeOldTracks_(techTracks, elTracks); }; /** * Called by {@link Player#play} to play using the `Html5` `Tech`. */ Html5.prototype.play = function play() { var playPromise = this.el_.play(); // Catch/silence error when a pause interrupts a play request // on browsers which return a promise if (playPromise !== undefined && typeof playPromise.then === 'function') { playPromise.then(null, function (e) {}); } }; /** * Set current time for the `HTML5` tech. * * @param {number} seconds * Set the current time of the media to this. */ Html5.prototype.setCurrentTime = function setCurrentTime(seconds) { try { this.el_.currentTime = seconds; } catch (e) { (0, _log2['default'])(e, 'Video is not ready. (Video.js)'); // this.warning(VideoJS.warnings.videoNotReady); } }; /** * Get the current duration of the HTML5 media element. * * @return {number} * The duration of the media or 0 if there is no duration. */ Html5.prototype.duration = function duration() { var _this3 = this; // Android Chrome will report duration as Infinity for VOD HLS until after // playback has started, which triggers the live display erroneously. // Return NaN if playback has not started and trigger a durationupdate once // the duration can be reliably known. if (this.el_.duration === Infinity && browser.IS_ANDROID && browser.IS_CHROME) { if (this.el_.currentTime === 0) { // Wait for the first `timeupdate` with currentTime > 0 - there may be // several with 0 var checkProgress = function checkProgress() { if (_this3.el_.currentTime > 0) { // Trigger durationchange for genuinely live video if (_this3.el_.duration === Infinity) { _this3.trigger('durationchange'); } _this3.off('timeupdate', checkProgress); } }; this.on('timeupdate', checkProgress); return NaN; } } return this.el_.duration || NaN; }; /** * Get the current width of the HTML5 media element. * * @return {number} * The width of the HTML5 media element. */ Html5.prototype.width = function width() { return this.el_.offsetWidth; }; /** * Get the current height of the HTML5 media element. * * @return {number} * The heigth of the HTML5 media element. */ Html5.prototype.height = function height() { return this.el_.offsetHeight; }; /** * Proxy iOS `webkitbeginfullscreen` and `webkitendfullscreen` into * `fullscreenchange` event. * * @private * @fires fullscreenchange * @listens webkitendfullscreen * @listens webkitbeginfullscreen * @listens webkitbeginfullscreen */ Html5.prototype.proxyWebkitFullscreen_ = function proxyWebkitFullscreen_() { var _this4 = this; if (!('webkitDisplayingFullscreen' in this.el_)) { return; } var endFn = function endFn() { this.trigger('fullscreenchange', { isFullscreen: false }); }; var beginFn = function beginFn() { this.one('webkitendfullscreen', endFn); this.trigger('fullscreenchange', { isFullscreen: true }); }; this.on('webkitbeginfullscreen', beginFn); this.on('dispose', function () { _this4.off('webkitbeginfullscreen', beginFn); _this4.off('webkitendfullscreen', endFn); }); }; /** * Check if fullscreen is supported on the current playback device. * * @return {boolean} * - True if fullscreen is supported. * - False if fullscreen is not supported. */ Html5.prototype.supportsFullScreen = function supportsFullScreen() { if (typeof this.el_.webkitEnterFullScreen === 'function') { var userAgent = _window2['default'].navigator && _window2['default'].navigator.userAgent || ''; // Seems to be broken in Chromium/Chrome && Safari in Leopard if (/Android/.test(userAgent) || !/Chrome|Mac OS X 10.5/.test(userAgent)) { return true; } } return false; }; /** * Request that the `HTML5` Tech enter fullscreen. */ Html5.prototype.enterFullScreen = function enterFullScreen() { var video = this.el_; if (video.paused && video.networkState <= video.HAVE_METADATA) { // attempt to prime the video element for programmatic access // this isn't necessary on the desktop but shouldn't hurt this.el_.play(); // playing and pausing synchronously during the transition to fullscreen // can get iOS ~6.1 devices into a play/pause loop this.setTimeout(function () { video.pause(); video.webkitEnterFullScreen(); }, 0); } else { video.webkitEnterFullScreen(); } }; /** * Request that the `HTML5` Tech exit fullscreen. */ Html5.prototype.exitFullScreen = function exitFullScreen() { this.el_.webkitExitFullScreen(); }; /** * A getter/setter for the `Html5` Tech's source object. * > Note: Please use {@link Html5#setSource} * * @param {Tech~SourceObject} [src] * The source object you want to set on the `HTML5` techs element. * * @return {Tech~SourceObject|undefined} * - The current source object when a source is not passed in. * - undefined when setting * * @deprecated Since version 5. */ Html5.prototype.src = function src(_src) { if (_src === undefined) { return this.el_.src; } // Setting src through `src` instead of `setSrc` will be deprecated this.setSrc(_src); }; /** * Reset the tech by removing all sources and then calling * {@link Html5.resetMediaElement}. */ Html5.prototype.reset = function reset() { Html5.resetMediaElement(this.el_); }; /** * Get the current source on the `HTML5` Tech. Falls back to returning the source from * the HTML5 media element. * * @return {Tech~SourceObject} * The current source object from the HTML5 tech. With a fallback to the * elements source. */ Html5.prototype.currentSrc = function currentSrc() { if (this.currentSource_) { return this.currentSource_.src; } return this.el_.currentSrc; }; /** * Set controls attribute for the HTML5 media Element. * * @param {string} val * Value to set the controls attribute to */ Html5.prototype.setControls = function setControls(val) { this.el_.controls = !!val; }; /** * Create and returns a remote {@link TextTrack} object. * * @param {string} kind * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata) * * @param {string} [label] * Label to identify the text track * * @param {string} [language] * Two letter language abbreviation * * @return {TextTrack} * The TextTrack that gets created. */ Html5.prototype.addTextTrack = function addTextTrack(kind, label, language) { if (!this.featuresNativeTextTracks) { return _Tech.prototype.addTextTrack.call(this, kind, label, language); } return this.el_.addTextTrack(kind, label, language); }; /** * Creates either native TextTrack or an emulated TextTrack depending * on the value of `featuresNativeTextTracks` * * @param {Object} options * The object should contain the options to intialize the TextTrack with. * * @param {string} [options.kind] * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata). * * @param {string} [options.label]. * Label to identify the text track * * @param {string} [options.language] * Two letter language abbreviation. * * @param {boolean} [options.default] * Default this track to on. * * @param {string} [options.id] * The internal id to assign this track. * * @param {string} [options.src] * A source url for the track. * * @return {HTMLTrackElement} * The track element that gets created. */ Html5.prototype.createRemoteTextTrack = function createRemoteTextTrack(options) { if (!this.featuresNativeTextTracks) { return _Tech.prototype.createRemoteTextTrack.call(this, options); } var htmlTrackElement = _document2['default'].createElement('track'); if (options.kind) { htmlTrackElement.kind = options.kind; } if (options.label) { htmlTrackElement.label = options.label; } if (options.language || options.srclang) { htmlTrackElement.srclang = options.language || options.srclang; } if (options['default']) { htmlTrackElement['default'] = options['default']; } if (options.id) { htmlTrackElement.id = options.id; } if (options.src) { htmlTrackElement.src = options.src; } return htmlTrackElement; }; /** * Creates a remote text track object and returns an html track element. * * @param {Object} options The object should contain values for * kind, language, label, and src (location of the WebVTT file) * @param {Boolean} [manualCleanup=true] if set to false, the TextTrack will be * automatically removed from the video element whenever the source changes * @return {HTMLTrackElement} An Html Track Element. * This can be an emulated {@link HTMLTrackElement} or a native one. * @deprecated The default value of the "manualCleanup" parameter will default * to "false" in upcoming versions of Video.js */ Html5.prototype.addRemoteTextTrack = function addRemoteTextTrack(options, manualCleanup) { var htmlTrackElement = _Tech.prototype.addRemoteTextTrack.call(this, options, manualCleanup); if (this.featuresNativeTextTracks) { this.el().appendChild(htmlTrackElement); } return htmlTrackElement; }; /** * Remove remote `TextTrack` from `TextTrackList` object * * @param {TextTrack} track * `TextTrack` object to remove */ Html5.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) { _Tech.prototype.removeRemoteTextTrack.call(this, track); if (this.featuresNativeTextTracks) { var tracks = this.$$('track'); var i = tracks.length; while (i--) { if (track === tracks[i] || track === tracks[i].track) { this.el().removeChild(tracks[i]); } } } }; return Html5; }(_tech2['default']); /* HTML5 Support Testing ---------------------------------------------------- */ if (Dom.isReal()) { /** * Element for testing browser HTML5 media capabilities * * @type {Element} * @constant * @private */ Html5.TEST_VID = _document2['default'].createElement('video'); var track = _document2['default'].createElement('track'); track.kind = 'captions'; track.srclang = 'en'; track.label = 'English'; Html5.TEST_VID.appendChild(track); } /** * Check if HTML5 media is supported by this browser/device. * * @return {boolean} * - True if HTML5 media is supported. * - False if HTML5 media is not supported. */ Html5.isSupported = function () { // IE9 with no Media Player is a LIAR! (#984) try { Html5.TEST_VID.volume = 0.5; } catch (e) { return false; } return !!(Html5.TEST_VID && Html5.TEST_VID.canPlayType); }; /** * Check if the volume can be changed in this browser/device. * Volume cannot be changed in a lot of mobile devices. * Specifically, it can't be changed from 1 on iOS. * * @return {boolean} * - True if volume can be controlled * - False otherwise */ Html5.canControlVolume = function () { // IE will error if Windows Media Player not installed #3315 try { var volume = Html5.TEST_VID.volume; Html5.TEST_VID.volume = volume / 2 + 0.1; return volume !== Html5.TEST_VID.volume; } catch (e) { return false; } }; /** * Check if the playback rate can be changed in this browser/device. * * @return {boolean} * - True if playback rate can be controlled * - False otherwise */ Html5.canControlPlaybackRate = function () { // Playback rate API is implemented in Android Chrome, but doesn't do anything // https://github.com/videojs/video.js/issues/3180 if (browser.IS_ANDROID && browser.IS_CHROME) { return false; } // IE will error if Windows Media Player not installed #3315 try { var playbackRate = Html5.TEST_VID.playbackRate; Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1; return playbackRate !== Html5.TEST_VID.playbackRate; } catch (e) { return false; } }; /** * Check to see if native `TextTrack`s are supported by this browser/device. * * @return {boolean} * - True if native `TextTrack`s are supported. * - False otherwise */ Html5.supportsNativeTextTracks = function () { return browser.IS_ANY_SAFARI; }; /** * Check to see if native `VideoTrack`s are supported by this browser/device * * @return {boolean} * - True if native `VideoTrack`s are supported. * - False otherwise */ Html5.supportsNativeVideoTracks = function () { return !!(Html5.TEST_VID && Html5.TEST_VID.videoTracks); }; /** * Check to see if native `AudioTrack`s are supported by this browser/device * * @return {boolean} * - True if native `AudioTrack`s are supported. * - False otherwise */ Html5.supportsNativeAudioTracks = function () { return !!(Html5.TEST_VID && Html5.TEST_VID.audioTracks); }; /** * An array of events available on the Html5 tech. * * @private * @type {Array} */ Html5.Events = ['loadstart', 'suspend', 'abort', 'error', 'emptied', 'stalled', 'loadedmetadata', 'loadeddata', 'canplay', 'canplaythrough', 'playing', 'waiting', 'seeking', 'seeked', 'ended', 'durationchange', 'timeupdate', 'progress', 'play', 'pause', 'ratechange', 'volumechange']; /** * Boolean indicating whether the `Tech` supports volume control. * * @type {boolean} * @default {@link Html5.canControlVolume} */ Html5.prototype.featuresVolumeControl = Html5.canControlVolume(); /** * Boolean indicating whether the `Tech` supports changing the speed at which the media * plays. Examples: * - Set player to play 2x (twice) as fast * - Set player to play 0.5x (half) as fast * * @type {boolean} * @default {@link Html5.canControlPlaybackRate} */ Html5.prototype.featuresPlaybackRate = Html5.canControlPlaybackRate(); /** * Boolean indicating whether the `HTML5` tech currently supports the media element * moving in the DOM. iOS breaks if you move the media element, so this is set this to * false there. Everywhere else this should be true. * * @type {boolean} * @default */ Html5.prototype.movingMediaElementInDOM = !browser.IS_IOS; // TODO: Previous comment: No longer appears to be used. Can probably be removed. // Is this true? /** * Boolean indicating whether the `HTML5` tech currently supports automatic media resize * when going into fullscreen. * * @type {boolean} * @default */ Html5.prototype.featuresFullscreenResize = true; /** * Boolean indicating whether the `HTML5` tech currently supports the progress event. * If this is false, manual `progress` events will be triggred instead. * * @type {boolean} * @default */ Html5.prototype.featuresProgressEvents = true; /** * Boolean indicating whether the `HTML5` tech currently supports the timeupdate event. * If this is false, manual `timeupdate` events will be triggred instead. * * @default */ Html5.prototype.featuresTimeupdateEvents = true; /** * Boolean indicating whether the `HTML5` tech currently supports native `TextTrack`s. * * @type {boolean} * @default {@link Html5.supportsNativeTextTracks} */ Html5.prototype.featuresNativeTextTracks = Html5.supportsNativeTextTracks(); /** * Boolean indicating whether the `HTML5` tech currently supports native `VideoTrack`s. * * @type {boolean} * @default {@link Html5.supportsNativeVideoTracks} */ Html5.prototype.featuresNativeVideoTracks = Html5.supportsNativeVideoTracks(); /** * Boolean indicating whether the `HTML5` tech currently supports native `AudioTrack`s. * * @type {boolean} * @default {@link Html5.supportsNativeAudioTracks} */ Html5.prototype.featuresNativeAudioTracks = Html5.supportsNativeAudioTracks(); // HTML5 Feature detection and Device Fixes --------------------------------- // var canPlayType = Html5.TEST_VID && Html5.TEST_VID.constructor.prototype.canPlayType; var mpegurlRE = /^application\/(?:x-|vnd\.apple\.)mpegurl/i; var mp4RE = /^video\/mp4/i; Html5.patchCanPlayType = function () { // Android 4.0 and above can play HLS to some extent but it reports being unable to do so if (browser.ANDROID_VERSION >= 4.0 && !browser.IS_FIREFOX) { Html5.TEST_VID.constructor.prototype.canPlayType = function (type) { if (type && mpegurlRE.test(type)) { return 'maybe'; } return canPlayType.call(this, type); }; // Override Android 2.2 and less canPlayType method which is broken } else if (browser.IS_OLD_ANDROID) { Html5.TEST_VID.constructor.prototype.canPlayType = function (type) { if (type && mp4RE.test(type)) { return 'maybe'; } return canPlayType.call(this, type); }; } }; Html5.unpatchCanPlayType = function () { var r = Html5.TEST_VID.constructor.prototype.canPlayType; Html5.TEST_VID.constructor.prototype.canPlayType = canPlayType; return r; }; // by default, patch the media element Html5.patchCanPlayType(); Html5.disposeMediaElement = function (el) { if (!el) { return; } if (el.parentNode) { el.parentNode.removeChild(el); } // remove any child track or source nodes to prevent their loading while (el.hasChildNodes()) { el.removeChild(el.firstChild); } // remove any src reference. not setting `src=''` because that causes a warning // in firefox el.removeAttribute('src'); // force the media element to update its loading state by calling load() // however IE on Windows 7N has a bug that throws an error so need a try/catch (#793) if (typeof el.load === 'function') { // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473) (function () { try { el.load(); } catch (e) { // not supported } })(); } }; Html5.resetMediaElement = function (el) { if (!el) { return; } var sources = el.querySelectorAll('source'); var i = sources.length; while (i--) { el.removeChild(sources[i]); } // remove any src reference. // not setting `src=''` because that throws an error el.removeAttribute('src'); if (typeof el.load === 'function') { // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473) (function () { try { el.load(); } catch (e) { // satisfy linter } })(); } }; /* Native HTML5 element property wrapping ----------------------------------- */ // Wrap native properties with a getter [ /** * Get the value of `paused` from the media element. `paused` indicates whether the media element * is currently paused or not. * * @method Html5#paused * @return {boolean} * The value of `paused` from the media element. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-paused} */ 'paused', /** * Get the value of `currentTime` from the media element. `currentTime` indicates * the current second that the media is at in playback. * * @method Html5#currentTime * @return {number} * The value of `currentTime` from the media element. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-currenttime} */ 'currentTime', /** * Get the value of `buffered` from the media element. `buffered` is a `TimeRange` * object that represents the parts of the media that are already downloaded and * available for playback. * * @method Html5#buffered * @return {TimeRange} * The value of `buffered` from the media element. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-buffered} */ 'buffered', /** * Get the value of `volume` from the media element. `volume` indicates * the current playback volume of audio for a media. `volume` will be a value from 0 * (silent) to 1 (loudest and default). * * @method Html5#volume * @return {number} * The value of `volume` from the media element. Value will be between 0-1. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume} */ 'volume', /** * Get the value of `muted` from the media element. `muted` indicates * that the volume for the media should be set to silent. This does not actually change * the `volume` attribute. * * @method Html5#muted * @return {boolean} * - True if the value of `volume` should be ignored and the audio set to silent. * - False if the value of `volume` should be used. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted} */ 'muted', /** * Get the value of `poster` from the media element. `poster` indicates * that the url of an image file that can/will be shown when no media data is available. * * @method Html5#poster * @return {string} * The value of `poster` from the media element. Value will be a url to an * image. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-video-poster} */ 'poster', /** * Get the value of `preload` from the media element. `preload` indicates * what should download before the media is interacted with. It can have the following * values: * - none: nothing should be downloaded * - metadata: poster and the first few frames of the media may be downloaded to get * media dimensions and other metadata * - auto: allow the media and metadata for the media to be downloaded before * interaction * * @method Html5#preload * @return {string} * The value of `preload` from the media element. Will be 'none', 'metadata', * or 'auto'. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload} */ 'preload', /** * Get the value of `autoplay` from the media element. `autoplay` indicates * that the media should start to play as soon as the page is ready. * * @method Html5#autoplay * @return {boolean} * - The value of `autoplay` from the media element. * - True indicates that the media should start as soon as the page loads. * - False indicates that the media should not start as soon as the page loads. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay} */ 'autoplay', /** * Get the value of `controls` from the media element. `controls` indicates * whether the native media controls should be shown or hidden. * * @method Html5#controls * @return {boolean} * - The value of `controls` from the media element. * - True indicates that native controls should be showing. * - False indicates that native controls should be hidden. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-controls} */ 'controls', /** * Get the value of `loop` from the media element. `loop` indicates * that the media should return to the start of the media and continue playing once * it reaches the end. * * @method Html5#loop * @return {boolean} * - The value of `loop` from the media element. * - True indicates that playback should seek back to start once * the end of a media is reached. * - False indicates that playback should not loop back to the start when the * end of the media is reached. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop} */ 'loop', /** * Get the value of the `error` from the media element. `error` indicates any * MediaError that may have occured during playback. If error returns null there is no * current error. * * @method Html5#error * @return {MediaError|null} * The value of `error` from the media element. Will be `MediaError` if there * is a current error and null otherwise. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-error} */ 'error', /** * Get the value of `seeking` from the media element. `seeking` indicates whether the * media is currently seeking to a new position or not. * * @method Html5#seeking * @return {boolean} * - The value of `seeking` from the media element. * - True indicates that the media is currently seeking to a new position. * - Flase indicates that the media is not seeking to a new position at this time. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seeking} */ 'seeking', /** * Get the value of `seekable` from the media element. `seekable` returns a * `TimeRange` object indicating ranges of time that can currently be `seeked` to. * * @method Html5#seekable * @return {TimeRange} * The value of `seekable` from the media element. A `TimeRange` object * indicating the current ranges of time that can be seeked to. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seekable} */ 'seekable', /** * Get the value of `ended` from the media element. `ended` indicates whether * the media has reached the end or not. * * @method Html5#ended * @return {boolean} * - The value of `ended` from the media element. * - True indicates that the media has ended. * - False indicates that the media has not ended. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-ended} */ 'ended', /** * Get the value of `defaultMuted` from the media element. `defaultMuted` indicates * whether the media should start muted or not. Only changes the default state of the * media. `muted` and `defaultMuted` can have different values. `muted` indicates the * current state. * * @method Html5#defaultMuted * @return {boolean} * - The value of `defaultMuted` from the media element. * - True indicates that the media should start muted. * - False indicates that the media should not start muted * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted} */ 'defaultMuted', /** * Get the value of `playbackRate` from the media element. `playbackRate` indicates * the rate at which the media is currently playing back. Examples: * - if playbackRate is set to 2, media will play twice as fast. * - if playbackRate is set to 0.5, media will play half as fast. * * @method Html5#playbackRate * @return {number} * The value of `playbackRate` from the media element. A number indicating * the current playback speed of the media, where 1 is normal speed. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate} */ 'playbackRate', /** * Get the value of `played` from the media element. `played` returns a `TimeRange` * object representing points in the media timeline that have been played. * * @method Html5#played * @return {TimeRange} * The value of `played` from the media element. A `TimeRange` object indicating * the ranges of time that have been played. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-played} */ 'played', /** * Get the value of `networkState` from the media element. `networkState` indicates * the current network state. It returns an enumeration from the following list: * - 0: NETWORK_EMPTY * - 1: NEWORK_IDLE * - 2: NETWORK_LOADING * - 3: NETWORK_NO_SOURCE * * @method Html5#networkState * @return {number} * The value of `networkState` from the media element. This will be a number * from the list in the description. * * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-networkstate} */ 'networkState', /** * Get the value of `readyState` from the media element. `readyState` indicates * the current state of the media element. It returns an enumeration from the * following list: * - 0: HAVE_NOTHING * - 1: HAVE_METADATA * - 2: HAVE_CURRENT_DATA * - 3: HAVE_FUTURE_DATA * - 4: HAVE_ENOUGH_DATA * * @method Html5#readyState * @return {number} * The value of `readyState` from the media element. This will be a number * from the list in the description. * * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#ready-states} */ 'readyState', /** * Get the value of `videoWidth` from the video element. `videoWidth` indicates * the current width of the video in css pixels. * * @method Html5#videoWidth * @return {number} * The value of `videoWidth` from the video element. This will be a number * in css pixels. * * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth} */ 'videoWidth', /** * Get the value of `videoHeight` from the video element. `videoHeigth` indicates * the current height of the video in css pixels. * * @method Html5#videoHeight * @return {number} * The value of `videoHeight` from the video element. This will be a number * in css pixels. * * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth} */ 'videoHeight'].forEach(function (prop) { Html5.prototype[prop] = function () { return this.el_[prop]; }; }); // Wrap native properties with a setter in this format: // set + toTitleCase(name) [ /** * Set the value of `volume` on the media element. `volume` indicates the current * audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and * so on. * * @method Html5#setVolume * @param {number} percentAsDecimal * The volume percent as a decimal. Valid range is from 0-1. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume} */ 'volume', /** * Set the value of `muted` on the media element. `muted` indicates the current * audio level should be silent. * * @method Html5#setMuted * @param {boolean} muted * - True if the audio should be set to silent * - False otherwise * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted} */ 'muted', /** * Set the value of `src` on the media element. `src` indicates the current * {@link Tech~SourceObject} for the media. * * @method Html5#setSrc * @param {Tech~SourceObject} src * The source object to set as the current source. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-src} */ 'src', /** * Set the value of `poster` on the media element. `poster` is the url to * an image file that can/will be shown when no media data is available. * * @method Html5#setPoster * @param {string} poster * The url to an image that should be used as the `poster` for the media * element. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-poster} */ 'poster', /** * Set the value of `preload` on the media element. `preload` indicates * what should download before the media is interacted with. It can have the following * values: * - none: nothing should be downloaded * - metadata: poster and the first few frames of the media may be downloaded to get * media dimensions and other metadata * - auto: allow the media and metadata for the media to be downloaded before * interaction * * @method Html5#setPreload * @param {string} preload * The value of `preload` to set on the media element. Must be 'none', 'metadata', * or 'auto'. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload} */ 'preload', /** * Set the value of `autoplay` on the media element. `autoplay` indicates * that the media should start to play as soon as the page is ready. * * @method Html5#setAutoplay * @param {boolean} autoplay * - True indicates that the media should start as soon as the page loads. * - False indicates that the media should not start as soon as the page loads. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay} */ 'autoplay', /** * Set the value of `loop` on the media element. `loop` indicates * that the media should return to the start of the media and continue playing once * it reaches the end. * * @method Html5#setLoop * @param {boolean} loop * - True indicates that playback should seek back to start once * the end of a media is reached. * - False indicates that playback should not loop back to the start when the * end of the media is reached. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop} */ 'loop', /** * Set the value of `playbackRate` on the media element. `playbackRate` indicates * the rate at which the media should play back. Examples: * - if playbackRate is set to 2, media will play twice as fast. * - if playbackRate is set to 0.5, media will play half as fast. * * @method Html5#setPlaybackRate * @return {number} * The value of `playbackRate` from the media element. A number indicating * the current playback speed of the media, where 1 is normal speed. * * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate} */ 'playbackRate'].forEach(function (prop) { Html5.prototype['set' + (0, _toTitleCase2['default'])(prop)] = function (v) { this.el_[prop] = v; }; }); // wrap native functions with a function [ /** * A wrapper around the media elements `pause` function. This will call the `HTML5` * media elements `pause` function. * * @method Html5#pause * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-pause} */ 'pause', /** * A wrapper around the media elements `load` function. This will call the `HTML5`s * media element `load` function. * * @method Html5#load * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-load} */ 'load'].forEach(function (prop) { Html5.prototype[prop] = function () { return this.el_[prop](); }; }); _tech2['default'].withSourceHandlers(Html5); /** * Native source handler for Html5, simply passes the source to the media element. * * @proprety {Tech~SourceObject} source * The source object * * @proprety {Html5} tech * The instance of the HTML5 tech. */ Html5.nativeSourceHandler = {}; /** * Check if the media element can play the given mime type. * * @param {string} type * The mimetype to check * * @return {string} * 'probably', 'maybe', or '' (empty string) */ Html5.nativeSourceHandler.canPlayType = function (type) { // IE9 on Windows 7 without MediaPlayer throws an error here // https://github.com/videojs/video.js/issues/519 try { return Html5.TEST_VID.canPlayType(type); } catch (e) { return ''; } }; /** * Check if the media element can handle a source natively. * * @param {Tech~SourceObject} source * The source object * * @param {Object} [options] * Options to be passed to the tech. * * @return {string} * 'probably', 'maybe', or '' (empty string). */ Html5.nativeSourceHandler.canHandleSource = function (source, options) { // If a type was provided we should rely on that if (source.type) { return Html5.nativeSourceHandler.canPlayType(source.type); // If no type, fall back to checking 'video/[EXTENSION]' } else if (source.src) { var ext = Url.getFileExtension(source.src); return Html5.nativeSourceHandler.canPlayType('video/' + ext); } return ''; }; /** * Pass the source to the native media element. * * @param {Tech~SourceObject} source * The source object * * @param {Html5} tech * The instance of the Html5 tech * * @param {Object} [options] * The options to pass to the source */ Html5.nativeSourceHandler.handleSource = function (source, tech, options) { tech.setSrc(source.src); }; /** * A noop for the native dispose function, as cleanup is not needed. */ Html5.nativeSourceHandler.dispose = function () {}; // Register the native source handler Html5.registerSourceHandler(Html5.nativeSourceHandler); _component2['default'].registerComponent('Html5', Html5); _tech2['default'].registerTech('Html5', Html5); exports['default'] = Html5; },{"5":5,"62":62,"78":78,"81":81,"83":83,"86":86,"87":87,"88":88,"91":91,"92":92,"94":94,"95":95,"98":98}],61:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _tech = _dereq_(62); var _tech2 = _interopRequireDefault(_tech); var _toTitleCase = _dereq_(91); var _toTitleCase2 = _interopRequireDefault(_toTitleCase); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file loader.js */ /** * The `MediaLoader` is the `Component` that decides which playback technology to load * when a player is initialized. * * @extends Component */ var MediaLoader = function (_Component) { _inherits(MediaLoader, _Component); /** * Create an instance of this class. * * @param {Player} player * The `Player` that this class should attach to. * * @param {Object} [options] * The key/value stroe of player options. * * @param {Component~ReadyCallback} [ready] * The function that is run when this component is ready. */ function MediaLoader(player, options, ready) { _classCallCheck(this, MediaLoader); // If there are no sources when the player is initialized, // load the first supported playback technology. var _this = _possibleConstructorReturn(this, _Component.call(this, player, options, ready)); if (!options.playerOptions.sources || options.playerOptions.sources.length === 0) { for (var i = 0, j = options.playerOptions.techOrder; i < j.length; i++) { var techName = (0, _toTitleCase2['default'])(j[i]); var tech = _tech2['default'].getTech(techName); // Support old behavior of techs being registered as components. // Remove once that deprecated behavior is removed. if (!techName) { tech = _component2['default'].getComponent(techName); } // Check if the browser supports this technology if (tech && tech.isSupported()) { player.loadTech_(techName); break; } } } else { // Loop through playback technologies (HTML5, Flash) and check for support. // Then load the best source. // A few assumptions here: // All playback technologies respect preload false. player.src(options.playerOptions.sources); } return _this; } return MediaLoader; }(_component2['default']); _component2['default'].registerComponent('MediaLoader', MediaLoader); exports['default'] = MediaLoader; },{"5":5,"62":62,"91":91}],62:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _htmlTrackElement = _dereq_(66); var _htmlTrackElement2 = _interopRequireDefault(_htmlTrackElement); var _htmlTrackElementList = _dereq_(65); var _htmlTrackElementList2 = _interopRequireDefault(_htmlTrackElementList); var _mergeOptions = _dereq_(87); var _mergeOptions2 = _interopRequireDefault(_mergeOptions); var _textTrack = _dereq_(72); var _textTrack2 = _interopRequireDefault(_textTrack); var _textTrackList = _dereq_(70); var _textTrackList2 = _interopRequireDefault(_textTrackList); var _videoTrackList = _dereq_(76); var _videoTrackList2 = _interopRequireDefault(_videoTrackList); var _audioTrackList = _dereq_(63); var _audioTrackList2 = _interopRequireDefault(_audioTrackList); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); var _log = _dereq_(86); var _log2 = _interopRequireDefault(_log); var _timeRanges = _dereq_(90); var _buffer = _dereq_(79); var _mediaError = _dereq_(46); var _mediaError2 = _interopRequireDefault(_mediaError); var _window = _dereq_(95); var _window2 = _interopRequireDefault(_window); var _document = _dereq_(94); var _document2 = _interopRequireDefault(_document); var _obj = _dereq_(88); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file tech.js */ /** * An Object containing a structure like: `{src: 'url', type: 'mimetype'}` or string * that just contains the src url alone. * * `var SourceObject = {src: 'http://ex.com/video.mp4', type: 'video/mp4'};` * `var SourceString = 'http://example.com/some-video.mp4';` * * @typedef {Object|string} Tech~SourceObject * * @property {string} src * The url to the source * * @property {string} type * The mime type of the source */ /** * A function used by {@link Tech} to create a new {@link TextTrack}. * * @param {Tech} self * An instance of the Tech class. * * @param {string} kind * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata) * * @param {string} [label] * Label to identify the text track * * @param {string} [language] * Two letter language abbreviation * * @param {Object} [options={}] * An object with additional text track options * * @return {TextTrack} * The text track that was created. */ function createTrackHelper(self, kind, label, language) { var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; var tracks = self.textTracks(); options.kind = kind; if (label) { options.label = label; } if (language) { options.language = language; } options.tech = self; var track = new _textTrack2['default'](options); tracks.addTrack_(track); return track; } /** * This is the base class for media playback technology controllers, such as * {@link Flash} and {@link HTML5} * * @extends Component */ var Tech = function (_Component) { _inherits(Tech, _Component); /** * Create an instance of this Tech. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} ready * Callback function to call when the `HTML5` Tech is ready. */ function Tech() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var ready = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {}; _classCallCheck(this, Tech); // we don't want the tech to report user activity automatically. // This is done manually in addControlsListeners options.reportTouchActivity = false; // keep track of whether the current source has played at all to // implement a very limited played() var _this = _possibleConstructorReturn(this, _Component.call(this, null, options, ready)); _this.hasStarted_ = false; _this.on('playing', function () { this.hasStarted_ = true; }); _this.on('loadstart', function () { this.hasStarted_ = false; }); _this.textTracks_ = options.textTracks; _this.videoTracks_ = options.videoTracks; _this.audioTracks_ = options.audioTracks; // Manually track progress in cases where the browser/flash player doesn't report it. if (!_this.featuresProgressEvents) { _this.manualProgressOn(); } // Manually track timeupdates in cases where the browser/flash player doesn't report it. if (!_this.featuresTimeupdateEvents) { _this.manualTimeUpdatesOn(); } ['Text', 'Audio', 'Video'].forEach(function (track) { if (options['native' + track + 'Tracks'] === false) { _this['featuresNative' + track + 'Tracks'] = false; } }); if (options.nativeCaptions === false) { _this.featuresNativeTextTracks = false; } if (!_this.featuresNativeTextTracks) { _this.emulateTextTracks(); } _this.autoRemoteTextTracks_ = new _textTrackList2['default'](); _this.initTextTrackListeners(); _this.initTrackListeners(); // Turn on component tap events only if not using native controls if (!options.nativeControlsForTouch) { _this.emitTapEvents(); } if (_this.constructor) { _this.name_ = _this.constructor.name || 'Unknown Tech'; } return _this; } /* Fallbacks for unsupported event types ================================================================================ */ /** * Polyfill the `progress` event for browsers that don't support it natively. * * @see {@link Tech#trackProgress} */ Tech.prototype.manualProgressOn = function manualProgressOn() { this.on('durationchange', this.onDurationChange); this.manualProgress = true; // Trigger progress watching when a source begins loading this.one('ready', this.trackProgress); }; /** * Turn off the polyfill for `progress` events that was created in * {@link Tech#manualProgressOn} */ Tech.prototype.manualProgressOff = function manualProgressOff() { this.manualProgress = false; this.stopTrackingProgress(); this.off('durationchange', this.onDurationChange); }; /** * This is used to trigger a `progress` event when the buffered percent changes. It * sets an interval function that will be called every 500 milliseconds to check if the * buffer end percent has changed. * * > This function is called by {@link Tech#manualProgressOn} * * @param {EventTarget~Event} event * The `ready` event that caused this to run. * * @listens Tech#ready * @fires Tech#progress */ Tech.prototype.trackProgress = function trackProgress(event) { this.stopTrackingProgress(); this.progressInterval = this.setInterval(Fn.bind(this, function () { // Don't trigger unless buffered amount is greater than last time var numBufferedPercent = this.bufferedPercent(); if (this.bufferedPercent_ !== numBufferedPercent) { /** * See {@link Player#progress} * * @event Tech#progress * @type {EventTarget~Event} */ this.trigger('progress'); } this.bufferedPercent_ = numBufferedPercent; if (numBufferedPercent === 1) { this.stopTrackingProgress(); } }), 500); }; /** * Update our internal duration on a `durationchange` event by calling * {@link Tech#duration}. * * @param {EventTarget~Event} event * The `durationchange` event that caused this to run. * * @listens Tech#durationchange */ Tech.prototype.onDurationChange = function onDurationChange(event) { this.duration_ = this.duration(); }; /** * Get and create a `TimeRange` object for buffering. * * @return {TimeRange} * The time range object that was created. */ Tech.prototype.buffered = function buffered() { return (0, _timeRanges.createTimeRange)(0, 0); }; /** * Get the percentage of the current video that is currently buffered. * * @return {number} * A number from 0 to 1 that represents the decimal percentage of the * video that is buffered. * */ Tech.prototype.bufferedPercent = function bufferedPercent() { return (0, _buffer.bufferedPercent)(this.buffered(), this.duration_); }; /** * Turn off the polyfill for `progress` events that was created in * {@link Tech#manualProgressOn} * Stop manually tracking progress events by clearing the interval that was set in * {@link Tech#trackProgress}. */ Tech.prototype.stopTrackingProgress = function stopTrackingProgress() { this.clearInterval(this.progressInterval); }; /** * Polyfill the `timeupdate` event for browsers that don't support it. * * @see {@link Tech#trackCurrentTime} */ Tech.prototype.manualTimeUpdatesOn = function manualTimeUpdatesOn() { this.manualTimeUpdates = true; this.on('play', this.trackCurrentTime); this.on('pause', this.stopTrackingCurrentTime); }; /** * Turn off the polyfill for `timeupdate` events that was created in * {@link Tech#manualTimeUpdatesOn} */ Tech.prototype.manualTimeUpdatesOff = function manualTimeUpdatesOff() { this.manualTimeUpdates = false; this.stopTrackingCurrentTime(); this.off('play', this.trackCurrentTime); this.off('pause', this.stopTrackingCurrentTime); }; /** * Sets up an interval function to track current time and trigger `timeupdate` every * 250 milliseconds. * * @listens Tech#play * @triggers Tech#timeupdate */ Tech.prototype.trackCurrentTime = function trackCurrentTime() { if (this.currentTimeInterval) { this.stopTrackingCurrentTime(); } this.currentTimeInterval = this.setInterval(function () { /** * Triggered at an interval of 250ms to indicated that time is passing in the video. * * @event Tech#timeupdate * @type {EventTarget~Event} */ this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15 }, 250); }; /** * Stop the interval function created in {@link Tech#trackCurrentTime} so that the * `timeupdate` event is no longer triggered. * * @listens {Tech#pause} */ Tech.prototype.stopTrackingCurrentTime = function stopTrackingCurrentTime() { this.clearInterval(this.currentTimeInterval); // #1002 - if the video ends right before the next timeupdate would happen, // the progress bar won't make it all the way to the end this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); }; /** * Turn off all event polyfills, clear the `Tech`s {@link AudioTrackList}, * {@link VideoTrackList}, and {@link TextTrackList}, and dispose of this Tech. * * @fires Component#dispose */ Tech.prototype.dispose = function dispose() { // clear out all tracks because we can't reuse them between techs this.clearTracks(['audio', 'video', 'text']); // Turn off any manual progress or timeupdate tracking if (this.manualProgress) { this.manualProgressOff(); } if (this.manualTimeUpdates) { this.manualTimeUpdatesOff(); } _Component.prototype.dispose.call(this); }; /** * Clear out a single `TrackList` or an array of `TrackLists` given their names. * * > Note: Techs without source handlers should call this between sources for `video` * & `audio` tracks. You don't want to use them between tracks! * * @param {string[]|string} types * TrackList names to clear, valid names are `video`, `audio`, and * `text`. */ Tech.prototype.clearTracks = function clearTracks(types) { var _this2 = this; types = [].concat(types); // clear out all tracks because we can't reuse them between techs types.forEach(function (type) { var list = _this2[type + 'Tracks']() || []; var i = list.length; while (i--) { var track = list[i]; if (type === 'text') { _this2.removeRemoteTextTrack(track); } list.removeTrack_(track); } }); }; /** * Remove any TextTracks added via addRemoteTextTrack that are * flagged for automatic garbage collection */ Tech.prototype.cleanupAutoTextTracks = function cleanupAutoTextTracks() { var list = this.autoRemoteTextTracks_ || []; var i = list.length; while (i--) { var track = list[i]; this.removeRemoteTextTrack(track); } }; /** * Reset the tech, which will removes all sources and reset the internal readyState. * * @abstract */ Tech.prototype.reset = function reset() {}; /** * Get or set an error on the Tech. * * @param {MediaError} [err] * Error to set on the Tech * * @return {MediaError|null} * The current error object on the tech, or null if there isn't one. */ Tech.prototype.error = function error(err) { if (err !== undefined) { this.error_ = new _mediaError2['default'](err); this.trigger('error'); } return this.error_; }; /** * Returns the `TimeRange`s that have been played through for the current source. * * > NOTE: This implementation is incomplete. It does not track the played `TimeRange`. * It only checks wether the source has played at all or not. * * @return {TimeRange} * - A single time range if this video has played * - An empty set of ranges if not. */ Tech.prototype.played = function played() { if (this.hasStarted_) { return (0, _timeRanges.createTimeRange)(0, 0); } return (0, _timeRanges.createTimeRange)(); }; /** * Causes a manual time update to occur if {@link Tech#manualTimeUpdatesOn} was * previously called. * * @fires Tech#timeupdate */ Tech.prototype.setCurrentTime = function setCurrentTime() { // improve the accuracy of manual timeupdates if (this.manualTimeUpdates) { /** * A manual `timeupdate` event. * * @event Tech#timeupdate * @type {EventTarget~Event} */ this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); } }; /** * Turn on listeners for {@link TextTrackList} events. This adds * {@link EventTarget~EventListeners} for `texttrackchange`, `addtrack` and * `removetrack`. * * @fires Tech#texttrackchange */ Tech.prototype.initTextTrackListeners = function initTextTrackListeners() { var textTrackListChanges = Fn.bind(this, function () { /** * Triggered when tracks are added or removed on the Tech {@link TextTrackList} * * @event Tech#texttrackchange * @type {EventTarget~Event} */ this.trigger('texttrackchange'); }); var tracks = this.textTracks(); if (!tracks) { return; } tracks.addEventListener('removetrack', textTrackListChanges); tracks.addEventListener('addtrack', textTrackListChanges); this.on('dispose', Fn.bind(this, function () { tracks.removeEventListener('removetrack', textTrackListChanges); tracks.removeEventListener('addtrack', textTrackListChanges); })); }; /** * Turn on listeners for {@link VideoTrackList} and {@link {AudioTrackList} events. * This adds {@link EventTarget~EventListeners} for `addtrack`, and `removetrack`. * * @fires Tech#audiotrackchange * @fires Tech#videotrackchange */ Tech.prototype.initTrackListeners = function initTrackListeners() { var _this3 = this; var trackTypes = ['video', 'audio']; trackTypes.forEach(function (type) { /** * Triggered when tracks are added or removed on the Tech {@link AudioTrackList} * * @event Tech#audiotrackchange * @type {EventTarget~Event} */ /** * Triggered when tracks are added or removed on the Tech {@link VideoTrackList} * * @event Tech#videotrackchange * @type {EventTarget~Event} */ var trackListChanges = function trackListChanges() { _this3.trigger(type + 'trackchange'); }; var tracks = _this3[type + 'Tracks'](); tracks.addEventListener('removetrack', trackListChanges); tracks.addEventListener('addtrack', trackListChanges); _this3.on('dispose', function () { tracks.removeEventListener('removetrack', trackListChanges); tracks.removeEventListener('addtrack', trackListChanges); }); }); }; /** * Emulate TextTracks using vtt.js if necessary * * @fires Tech#vttjsloaded * @fires Tech#vttjserror */ Tech.prototype.addWebVttScript_ = function addWebVttScript_() { var _this4 = this; if (_window2['default'].WebVTT) { return; } // Initially, Tech.el_ is a child of a dummy-div wait until the Component system // signals that the Tech is ready at which point Tech.el_ is part of the DOM // before inserting the WebVTT script if (_document2['default'].body.contains(this.el())) { var vtt = _dereq_(105); // load via require if available and vtt.js script location was not passed in // as an option. novtt builds will turn the above require call into an empty object // which will cause this if check to always fail. if (!this.options_['vtt.js'] && (0, _obj.isPlain)(vtt) && Object.keys(vtt).length > 0) { this.trigger('vttjsloaded'); return; } // load vtt.js via the script location option or the cdn of no location was // passed in var script = _document2['default'].createElement('script'); script.src = this.options_['vtt.js'] || 'https://vjs.zencdn.net/vttjs/0.12.3/vtt.min.js'; script.onload = function () { /** * Fired when vtt.js is loaded. * * @event Tech#vttjsloaded * @type {EventTarget~Event} */ _this4.trigger('vttjsloaded'); }; script.onerror = function () { /** * Fired when vtt.js was not loaded due to an error * * @event Tech#vttjsloaded * @type {EventTarget~Event} */ _this4.trigger('vttjserror'); }; this.on('dispose', function () { script.onload = null; script.onerror = null; }); // but have not loaded yet and we set it to true before the inject so that // we don't overwrite the injected window.WebVTT if it loads right away _window2['default'].WebVTT = true; this.el().parentNode.appendChild(script); } else { this.ready(this.addWebVttScript_); } }; /** * Emulate texttracks * * @method emulateTextTracks */ Tech.prototype.emulateTextTracks = function emulateTextTracks() { var _this5 = this; var tracks = this.textTracks(); if (!tracks) { return; } var remoteTracks = this.remoteTextTracks(); var handleAddTrack = function handleAddTrack(e) { return tracks.addTrack_(e.track); }; var handleRemoveTrack = function handleRemoveTrack(e) { return tracks.removeTrack_(e.track); }; remoteTracks.on('addtrack', handleAddTrack); remoteTracks.on('removetrack', handleRemoveTrack); this.addWebVttScript_(); var updateDisplay = function updateDisplay() { return _this5.trigger('texttrackchange'); }; var textTracksChanges = function textTracksChanges() { updateDisplay(); for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; track.removeEventListener('cuechange', updateDisplay); if (track.mode === 'showing') { track.addEventListener('cuechange', updateDisplay); } } }; textTracksChanges(); tracks.addEventListener('change', textTracksChanges); tracks.addEventListener('addtrack', textTracksChanges); tracks.addEventListener('removetrack', textTracksChanges); this.on('dispose', function () { remoteTracks.off('addtrack', handleAddTrack); remoteTracks.off('removetrack', handleRemoveTrack); tracks.removeEventListener('change', textTracksChanges); tracks.removeEventListener('addtrack', textTracksChanges); tracks.removeEventListener('removetrack', textTracksChanges); for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; track.removeEventListener('cuechange', updateDisplay); } }); }; /** * Get the `Tech`s {@link VideoTrackList}. * * @return {VideoTrackList} * The video track list that the Tech is currently using. */ Tech.prototype.videoTracks = function videoTracks() { this.videoTracks_ = this.videoTracks_ || new _videoTrackList2['default'](); return this.videoTracks_; }; /** * Get the `Tech`s {@link AudioTrackList}. * * @return {AudioTrackList} * The audio track list that the Tech is currently using. */ Tech.prototype.audioTracks = function audioTracks() { this.audioTracks_ = this.audioTracks_ || new _audioTrackList2['default'](); return this.audioTracks_; }; /** * Get the `Tech`s {@link TextTrackList}. * * @return {TextTrackList} * The text track list that the Tech is currently using. */ Tech.prototype.textTracks = function textTracks() { this.textTracks_ = this.textTracks_ || new _textTrackList2['default'](); return this.textTracks_; }; /** * Get the `Tech`s remote {@link TextTrackList}, which is created from elements * that were added to the DOM. * * @return {TextTrackList} * The remote text track list that the Tech is currently using. */ Tech.prototype.remoteTextTracks = function remoteTextTracks() { this.remoteTextTracks_ = this.remoteTextTracks_ || new _textTrackList2['default'](); return this.remoteTextTracks_; }; /** * Get The `Tech`s {HTMLTrackElementList}, which are the elements in the DOM that are * being used as TextTracks. * * @return {HTMLTrackElementList} * The current HTML track elements that exist for the tech. */ Tech.prototype.remoteTextTrackEls = function remoteTextTrackEls() { this.remoteTextTrackEls_ = this.remoteTextTrackEls_ || new _htmlTrackElementList2['default'](); return this.remoteTextTrackEls_; }; /** * Create and returns a remote {@link TextTrack} object. * * @param {string} kind * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata) * * @param {string} [label] * Label to identify the text track * * @param {string} [language] * Two letter language abbreviation * * @return {TextTrack} * The TextTrack that gets created. */ Tech.prototype.addTextTrack = function addTextTrack(kind, label, language) { if (!kind) { throw new Error('TextTrack kind is required but was not provided'); } return createTrackHelper(this, kind, label, language); }; /** * Create an emulated TextTrack for use by addRemoteTextTrack * * This is intended to be overridden by classes that inherit from * Tech in order to create native or custom TextTracks. * * @param {Object} options * The object should contain the options to initialize the TextTrack with. * * @param {string} [options.kind] * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata). * * @param {string} [options.label]. * Label to identify the text track * * @param {string} [options.language] * Two letter language abbreviation. * * @return {HTMLTrackElement} * The track element that gets created. */ Tech.prototype.createRemoteTextTrack = function createRemoteTextTrack(options) { var track = (0, _mergeOptions2['default'])(options, { tech: this }); return new _htmlTrackElement2['default'](track); }; /** * Creates a remote text track object and returns an html track element. * * > Note: This can be an emulated {@link HTMLTrackElement} or a native one. * * @param {Object} options * See {@link Tech#createRemoteTextTrack} for more detailed properties. * * @param {boolean} [manualCleanup=true] * - When false: the TextTrack will be automatically removed from the video * element whenever the source changes * - When True: The TextTrack will have to be cleaned up manually * * @return {HTMLTrackElement} * An Html Track Element. * * @deprecated The default functionality for this function will be equivalent * to "manualCleanup=false" in the future. The manualCleanup parameter will * also be removed. */ Tech.prototype.addRemoteTextTrack = function addRemoteTextTrack() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var manualCleanup = arguments[1]; var htmlTrackElement = this.createRemoteTextTrack(options); if (manualCleanup !== true && manualCleanup !== false) { // deprecation warning _log2['default'].warn('Calling addRemoteTextTrack without explicitly setting the "manualCleanup" parameter to `true` is deprecated and default to `false` in future version of video.js'); manualCleanup = true; } // store HTMLTrackElement and TextTrack to remote list this.remoteTextTrackEls().addTrackElement_(htmlTrackElement); this.remoteTextTracks().addTrack_(htmlTrackElement.track); if (manualCleanup !== true) { // create the TextTrackList if it doesn't exist this.autoRemoteTextTracks_.addTrack_(htmlTrackElement.track); } return htmlTrackElement; }; /** * Remove a remote text track from the remote `TextTrackList`. * * @param {TextTrack} track * `TextTrack` to remove from the `TextTrackList` */ Tech.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) { var trackElement = this.remoteTextTrackEls().getTrackElementByTrack_(track); // remove HTMLTrackElement and TextTrack from remote list this.remoteTextTrackEls().removeTrackElement_(trackElement); this.remoteTextTracks().removeTrack_(track); this.autoRemoteTextTracks_.removeTrack_(track); }; /** * A method to set a poster from a `Tech`. * * @abstract */ Tech.prototype.setPoster = function setPoster() {}; /* * Check if the tech can support the given mime-type. * * The base tech does not support any type, but source handlers might * overwrite this. * * @param {string} type * The mimetype to check for support * * @return {string} * 'probably', 'maybe', or empty string * * @see [Spec]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType} * * @abstract */ Tech.prototype.canPlayType = function canPlayType() { return ''; }; /* * Return whether the argument is a Tech or not. * Can be passed either a Class like `Html5` or a instance like `player.tech_` * * @param {Object} component * The item to check * * @return {boolean} * Whether it is a tech or not * - True if it is a tech * - False if it is not */ Tech.isTech = function isTech(component) { return component.prototype instanceof Tech || component instanceof Tech || component === Tech; }; /** * Registers a `Tech` into a shared list for videojs. * * @param {string} name * Name of the `Tech` to register. * * @param {Object} tech * The `Tech` class to register. */ Tech.registerTech = function registerTech(name, tech) { if (!Tech.techs_) { Tech.techs_ = {}; } if (!Tech.isTech(tech)) { throw new Error('Tech ' + name + ' must be a Tech'); } Tech.techs_[name] = tech; return tech; }; /** * Get a `Tech` from the shared list by name. * * @param {string} name * Name of the component to get * * @return {Tech|undefined} * The `Tech` or undefined if there was no tech with the name requsted. */ Tech.getTech = function getTech(name) { if (Tech.techs_ && Tech.techs_[name]) { return Tech.techs_[name]; } if (_window2['default'] && _window2['default'].videojs && _window2['default'].videojs[name]) { _log2['default'].warn('The ' + name + ' tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)'); return _window2['default'].videojs[name]; } }; return Tech; }(_component2['default']); /** * List of associated text tracks. * * @type {TextTrackList} * @private */ Tech.prototype.textTracks_; // eslint-disable-line /** * List of associated audio tracks. * * @type {AudioTrackList} * @private */ Tech.prototype.audioTracks_; // eslint-disable-line /** * List of associated video tracks. * * @type {VideoTrackList} * @private */ Tech.prototype.videoTracks_; // eslint-disable-line /** * Boolean indicating wether the `Tech` supports volume control. * * @type {boolean} * @default */ Tech.prototype.featuresVolumeControl = true; /** * Boolean indicating wether the `Tech` support fullscreen resize control. * Resizing plugins using request fullscreen reloads the plugin * * @type {boolean} * @default */ Tech.prototype.featuresFullscreenResize = false; /** * Boolean indicating wether the `Tech` supports changing the speed at which the video * plays. Examples: * - Set player to play 2x (twice) as fast * - Set player to play 0.5x (half) as fast * * @type {boolean} * @default */ Tech.prototype.featuresPlaybackRate = false; /** * Boolean indicating wether the `Tech` supports the `progress` event. This is currently * not triggered by video-js-swf. This will be used to determine if * {@link Tech#manualProgressOn} should be called. * * @type {boolean} * @default */ Tech.prototype.featuresProgressEvents = false; /** * Boolean indicating wether the `Tech` supports the `timeupdate` event. This is currently * not triggered by video-js-swf. This will be used to determine if * {@link Tech#manualTimeUpdates} should be called. * * @type {boolean} * @default */ Tech.prototype.featuresTimeupdateEvents = false; /** * Boolean indicating wether the `Tech` supports the native `TextTrack`s. * This will help us integrate with native `TextTrack`s if the browser supports them. * * @type {boolean} * @default */ Tech.prototype.featuresNativeTextTracks = false; /** * A functional mixin for techs that want to use the Source Handler pattern. * Source handlers are scripts for handling specific formats. * The source handler pattern is used for adaptive formats (HLS, DASH) that * manually load video data and feed it into a Source Buffer (Media Source Extensions) * Example: `Tech.withSourceHandlers.call(MyTech);` * * @param {Tech} _Tech * The tech to add source handler functions to. * * @mixes Tech~SourceHandlerAdditions */ Tech.withSourceHandlers = function (_Tech) { /** * Register a source handler * * @param {Function} handler * The source handler class * * @param {number} [index] * Register it at the following index */ _Tech.registerSourceHandler = function (handler, index) { var handlers = _Tech.sourceHandlers; if (!handlers) { handlers = _Tech.sourceHandlers = []; } if (index === undefined) { // add to the end of the list index = handlers.length; } handlers.splice(index, 0, handler); }; /** * Check if the tech can support the given type. Also checks the * Techs sourceHandlers. * * @param {string} type * The mimetype to check. * * @return {string} * 'probably', 'maybe', or '' (empty string) */ _Tech.canPlayType = function (type) { var handlers = _Tech.sourceHandlers || []; var can = void 0; for (var i = 0; i < handlers.length; i++) { can = handlers[i].canPlayType(type); if (can) { return can; } } return ''; }; /** * Returns the first source handler that supports the source. * * TODO: Answer question: should 'probably' be prioritized over 'maybe' * * @param {Tech~SourceObject} source * The source object * * @param {Object} options * The options passed to the tech * * @return {SourceHandler|null} * The first source handler that supports the source or null if * no SourceHandler supports the source */ _Tech.selectSourceHandler = function (source, options) { var handlers = _Tech.sourceHandlers || []; var can = void 0; for (var i = 0; i < handlers.length; i++) { can = handlers[i].canHandleSource(source, options); if (can) { return handlers[i]; } } return null; }; /** * Check if the tech can support the given source. * * @param {Tech~SourceObject} srcObj * The source object * * @param {Object} options * The options passed to the tech * * @return {string} * 'probably', 'maybe', or '' (empty string) */ _Tech.canPlaySource = function (srcObj, options) { var sh = _Tech.selectSourceHandler(srcObj, options); if (sh) { return sh.canHandleSource(srcObj, options); } return ''; }; /** * When using a source handler, prefer its implementation of * any function normally provided by the tech. */ var deferrable = ['seekable', 'duration']; /** * A wrapper around {@link Tech#seekable} that will call a `SourceHandler`s seekable * function if it exists, with a fallback to the Techs seekable function. * * @method _Tech.seekable */ /** * A wrapper around {@link Tech#duration} that will call a `SourceHandler`s duration * function if it exists, otherwise it will fallback to the techs duration function. * * @method _Tech.duration */ deferrable.forEach(function (fnName) { var originalFn = this[fnName]; if (typeof originalFn !== 'function') { return; } this[fnName] = function () { if (this.sourceHandler_ && this.sourceHandler_[fnName]) { return this.sourceHandler_[fnName].apply(this.sourceHandler_, arguments); } return originalFn.apply(this, arguments); }; }, _Tech.prototype); /** * Create a function for setting the source using a source object * and source handlers. * Should never be called unless a source handler was found. * * @param {Tech~SourceObject} source * A source object with src and type keys * * @return {Tech} * Returns itself; this method is chainable */ _Tech.prototype.setSource = function (source) { var sh = _Tech.selectSourceHandler(source, this.options_); if (!sh) { // Fall back to a native source hander when unsupported sources are // deliberately set if (_Tech.nativeSourceHandler) { sh = _Tech.nativeSourceHandler; } else { _log2['default'].error('No source hander found for the current source.'); } } // Dispose any existing source handler this.disposeSourceHandler(); this.off('dispose', this.disposeSourceHandler); if (sh !== _Tech.nativeSourceHandler) { this.currentSource_ = source; // Catch if someone replaced the src without calling setSource. // If they do, set currentSource_ to null and dispose our source handler. this.off(this.el_, 'loadstart', _Tech.prototype.firstLoadStartListener_); this.off(this.el_, 'loadstart', _Tech.prototype.successiveLoadStartListener_); this.one(this.el_, 'loadstart', _Tech.prototype.firstLoadStartListener_); } this.sourceHandler_ = sh.handleSource(source, this, this.options_); this.on('dispose', this.disposeSourceHandler); return this; }; /** * Called once for the first loadstart of a video. * * @listens Tech#loadstart */ _Tech.prototype.firstLoadStartListener_ = function () { this.one(this.el_, 'loadstart', _Tech.prototype.successiveLoadStartListener_); }; // On successive loadstarts when setSource has not been called again /** * Called after the first loadstart for a video occurs. * * @listens Tech#loadstart */ _Tech.prototype.successiveLoadStartListener_ = function () { this.disposeSourceHandler(); this.one(this.el_, 'loadstart', _Tech.prototype.successiveLoadStartListener_); }; /** * Clean up any existing SourceHandlers and listeners when the Tech is disposed. * * @listens Tech#dispose */ _Tech.prototype.disposeSourceHandler = function () { // if we have a source and get another one // then we are loading something new // than clear all of our current tracks if (this.currentSource_) { this.clearTracks(['audio', 'video']); this.currentSource_ = null; } // always clean up auto-text tracks this.cleanupAutoTextTracks(); if (this.sourceHandler_) { this.off(this.el_, 'loadstart', _Tech.prototype.firstLoadStartListener_); this.off(this.el_, 'loadstart', _Tech.prototype.successiveLoadStartListener_); if (this.sourceHandler_.dispose) { this.sourceHandler_.dispose(); } this.sourceHandler_ = null; } }; }; _component2['default'].registerComponent('Tech', Tech); // Old name for Tech // @deprecated _component2['default'].registerComponent('MediaTechController', Tech); Tech.registerTech('Tech', Tech); exports['default'] = Tech; },{"105":105,"46":46,"5":5,"63":63,"65":65,"66":66,"70":70,"72":72,"76":76,"79":79,"83":83,"86":86,"87":87,"88":88,"90":90,"94":94,"95":95}],63:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _trackList = _dereq_(74); var _trackList2 = _interopRequireDefault(_trackList); var _browser = _dereq_(78); var browser = _interopRequireWildcard(_browser); var _document = _dereq_(94); var _document2 = _interopRequireDefault(_document); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file audio-track-list.js */ /** * Anywhere we call this function we diverge from the spec * as we only support one enabled audiotrack at a time * * @param {AudioTrackList} list * list to work on * * @param {AudioTrack} track * The track to skip * * @private */ var disableOthers = function disableOthers(list, track) { for (var i = 0; i < list.length; i++) { if (track.id === list[i].id) { continue; } // another audio track is enabled, disable it list[i].enabled = false; } }; /** * The current list of {@link AudioTrack} for a media file. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist} * @extends TrackList */ var AudioTrackList = function (_TrackList) { _inherits(AudioTrackList, _TrackList); /** * Create an instance of this class. * * @param {AudioTrack[]} [tracks=[]] * A list of `AudioTrack` to instantiate the list with. */ function AudioTrackList() { var _this, _ret; var tracks = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; _classCallCheck(this, AudioTrackList); var list = void 0; // make sure only 1 track is enabled // sorted from last index to first index for (var i = tracks.length - 1; i >= 0; i--) { if (tracks[i].enabled) { disableOthers(tracks, tracks[i]); break; } } // IE8 forces us to implement inheritance ourselves // as it does not support Object.defineProperty properly if (browser.IS_IE8) { list = _document2['default'].createElement('custom'); for (var prop in _trackList2['default'].prototype) { if (prop !== 'constructor') { list[prop] = _trackList2['default'].prototype[prop]; } } for (var _prop in AudioTrackList.prototype) { if (_prop !== 'constructor') { list[_prop] = AudioTrackList.prototype[_prop]; } } } list = (_this = _possibleConstructorReturn(this, _TrackList.call(this, tracks, list)), _this); list.changing_ = false; return _ret = list, _possibleConstructorReturn(_this, _ret); } /** * Add an {@link AudioTrack} to the `AudioTrackList`. * * @param {AudioTrack} track * The AudioTrack to add to the list * * @fires Track#addtrack * @private */ AudioTrackList.prototype.addTrack_ = function addTrack_(track) { var _this2 = this; if (track.enabled) { disableOthers(this, track); } _TrackList.prototype.addTrack_.call(this, track); // native tracks don't have this if (!track.addEventListener) { return; } /** * @listens AudioTrack#enabledchange * @fires TrackList#change */ track.addEventListener('enabledchange', function () { // when we are disabling other tracks (since we don't support // more than one track at a time) we will set changing_ // to true so that we don't trigger additional change events if (_this2.changing_) { return; } _this2.changing_ = true; disableOthers(_this2, track); _this2.changing_ = false; _this2.trigger('change'); }); }; /** * Add an {@link AudioTrack} to the `AudioTrackList`. * * @param {AudioTrack} track * The AudioTrack to add to the list * * @fires Track#addtrack */ AudioTrackList.prototype.addTrack = function addTrack(track) { this.addTrack_(track); }; /** * Remove an {@link AudioTrack} from the `AudioTrackList`. * * @param {AudioTrack} track * The AudioTrack to remove from the list * * @fires Track#removetrack */ AudioTrackList.prototype.removeTrack = function removeTrack(track) { _TrackList.prototype.removeTrack_.call(this, track); }; return AudioTrackList; }(_trackList2['default']); exports['default'] = AudioTrackList; },{"74":74,"78":78,"94":94}],64:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _trackEnums = _dereq_(73); var _track = _dereq_(75); var _track2 = _interopRequireDefault(_track); var _mergeOptions = _dereq_(87); var _mergeOptions2 = _interopRequireDefault(_mergeOptions); var _browser = _dereq_(78); var browser = _interopRequireWildcard(_browser); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * A representation of a single `AudioTrack`. If it is part of an {@link AudioTrackList} * only one `AudioTrack` in the list will be enabled at a time. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotrack} * @extends Track */ var AudioTrack = function (_Track) { _inherits(AudioTrack, _Track); /** * Create an instance of this class. * * @param {Object} [options={}] * Object of option names and values * * @param {AudioTrack~Kind} [options.kind=''] * A valid audio track kind * * @param {string} [options.id='vjs_track_' + Guid.newGUID()] * A unique id for this AudioTrack. * * @param {string} [options.label=''] * The menu label for this track. * * @param {string} [options.language=''] * A valid two character language code. * * @param {boolean} [options.enabled] * If this track is the one that is currently playing. If this track is part of * an {@link AudioTrackList}, only one {@link AudioTrack} will be enabled. */ function AudioTrack() { var _this, _ret; var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, AudioTrack); var settings = (0, _mergeOptions2['default'])(options, { kind: _trackEnums.AudioTrackKind[options.kind] || '' }); // on IE8 this will be a document element // for every other browser this will be a normal object var track = (_this = _possibleConstructorReturn(this, _Track.call(this, settings)), _this); var enabled = false; if (browser.IS_IE8) { for (var prop in AudioTrack.prototype) { if (prop !== 'constructor') { track[prop] = AudioTrack.prototype[prop]; } } } /** * @member {boolean} enabled * If this `AudioTrack` is enabled or not. When setting this will * fire {@link AudioTrack#enabledchange} if the state of enabled is changed. * * @fires VideoTrack#selectedchange */ Object.defineProperty(track, 'enabled', { get: function get() { return enabled; }, set: function set(newEnabled) { // an invalid or unchanged value if (typeof newEnabled !== 'boolean' || newEnabled === enabled) { return; } enabled = newEnabled; /** * An event that fires when enabled changes on this track. This allows * the AudioTrackList that holds this track to act accordingly. * * > Note: This is not part of the spec! Native tracks will do * this internally without an event. * * @event AudioTrack#enabledchange * @type {EventTarget~Event} */ this.trigger('enabledchange'); } }); // if the user sets this track to selected then // set selected to that true value otherwise // we keep it false if (settings.enabled) { track.enabled = settings.enabled; } track.loaded_ = true; return _ret = track, _possibleConstructorReturn(_this, _ret); } return AudioTrack; }(_track2['default']); exports['default'] = AudioTrack; },{"73":73,"75":75,"78":78,"87":87}],65:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _browser = _dereq_(78); var browser = _interopRequireWildcard(_browser); var _document = _dereq_(94); var _document2 = _interopRequireDefault(_document); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * @file html-track-element-list.js */ /** * The current list of {@link HtmlTrackElement}s. */ var HtmlTrackElementList = function () { /** * Create an instance of this class. * * @param {HtmlTrackElement[]} [tracks=[]] * A list of `HtmlTrackElement` to instantiate the list with. */ function HtmlTrackElementList() { var trackElements = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; _classCallCheck(this, HtmlTrackElementList); var list = this; // eslint-disable-line if (browser.IS_IE8) { list = _document2['default'].createElement('custom'); for (var prop in HtmlTrackElementList.prototype) { if (prop !== 'constructor') { list[prop] = HtmlTrackElementList.prototype[prop]; } } } list.trackElements_ = []; /** * @member {number} length * The current number of `Track`s in the this Trackist. */ Object.defineProperty(list, 'length', { get: function get() { return this.trackElements_.length; } }); for (var i = 0, length = trackElements.length; i < length; i++) { list.addTrackElement_(trackElements[i]); } if (browser.IS_IE8) { return list; } } /** * Add an {@link HtmlTrackElement} to the `HtmlTrackElementList` * * @param {HtmlTrackElement} trackElement * The track element to add to the list. * * @private */ HtmlTrackElementList.prototype.addTrackElement_ = function addTrackElement_(trackElement) { var index = this.trackElements_.length; if (!('' + index in this)) { Object.defineProperty(this, index, { get: function get() { return this.trackElements_[index]; } }); } // Do not add duplicate elements if (this.trackElements_.indexOf(trackElement) === -1) { this.trackElements_.push(trackElement); } }; /** * Get an {@link HtmlTrackElement} from the `HtmlTrackElementList` given an * {@link TextTrack}. * * @param {TextTrack} track * The track associated with a track element. * * @return {HtmlTrackElement|undefined} * The track element that was found or undefined. * * @private */ HtmlTrackElementList.prototype.getTrackElementByTrack_ = function getTrackElementByTrack_(track) { var trackElement_ = void 0; for (var i = 0, length = this.trackElements_.length; i < length; i++) { if (track === this.trackElements_[i].track) { trackElement_ = this.trackElements_[i]; break; } } return trackElement_; }; /** * Remove a {@link HtmlTrackElement} from the `HtmlTrackElementList` * * @param {HtmlTrackElement} trackElement * The track element to remove from the list. * * @private */ HtmlTrackElementList.prototype.removeTrackElement_ = function removeTrackElement_(trackElement) { for (var i = 0, length = this.trackElements_.length; i < length; i++) { if (trackElement === this.trackElements_[i]) { this.trackElements_.splice(i, 1); break; } } }; return HtmlTrackElementList; }(); exports['default'] = HtmlTrackElementList; },{"78":78,"94":94}],66:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _browser = _dereq_(78); var browser = _interopRequireWildcard(_browser); var _document = _dereq_(94); var _document2 = _interopRequireDefault(_document); var _eventTarget = _dereq_(42); var _eventTarget2 = _interopRequireDefault(_eventTarget); var _textTrack = _dereq_(72); var _textTrack2 = _interopRequireDefault(_textTrack); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file html-track-element.js */ /** * @typedef {HTMLTrackElement~ReadyState} * @enum {number} */ var NONE = 0; var LOADING = 1; var LOADED = 2; var ERROR = 3; /** * A single track represented in the DOM. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#htmltrackelement} * @extends EventTarget */ var HTMLTrackElement = function (_EventTarget) { _inherits(HTMLTrackElement, _EventTarget); /** * Create an instance of this class. * * @param {Object} options={} * Object of option names and values * * @param {Tech} options.tech * A reference to the tech that owns this HTMLTrackElement. * * @param {TextTrack~Kind} [options.kind='subtitles'] * A valid text track kind. * * @param {TextTrack~Mode} [options.mode='disabled'] * A valid text track mode. * * @param {string} [options.id='vjs_track_' + Guid.newGUID()] * A unique id for this TextTrack. * * @param {string} [options.label=''] * The menu label for this track. * * @param {string} [options.language=''] * A valid two character language code. * * @param {string} [options.srclang=''] * A valid two character language code. An alternative, but deprioritized * vesion of `options.language` * * @param {string} [options.src] * A url to TextTrack cues. * * @param {boolean} [options.default] * If this track should default to on or off. */ function HTMLTrackElement() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, HTMLTrackElement); var _this = _possibleConstructorReturn(this, _EventTarget.call(this)); var readyState = void 0; var trackElement = _this; // eslint-disable-line if (browser.IS_IE8) { trackElement = _document2['default'].createElement('custom'); for (var prop in HTMLTrackElement.prototype) { if (prop !== 'constructor') { trackElement[prop] = HTMLTrackElement.prototype[prop]; } } } var track = new _textTrack2['default'](options); trackElement.kind = track.kind; trackElement.src = track.src; trackElement.srclang = track.language; trackElement.label = track.label; trackElement['default'] = track['default']; /** * @member {HTMLTrackElement~ReadyState} readyState * The current ready state of the track element. */ Object.defineProperty(trackElement, 'readyState', { get: function get() { return readyState; } }); /** * @member {TextTrack} track * The underlying TextTrack object. */ Object.defineProperty(trackElement, 'track', { get: function get() { return track; } }); readyState = NONE; /** * @listens TextTrack#loadeddata * @fires HTMLTrackElement#load */ track.addEventListener('loadeddata', function () { readyState = LOADED; trackElement.trigger({ type: 'load', target: trackElement }); }); if (browser.IS_IE8) { var _ret; return _ret = trackElement, _possibleConstructorReturn(_this, _ret); } return _this; } return HTMLTrackElement; }(_eventTarget2['default']); HTMLTrackElement.prototype.allowedEvents_ = { load: 'load' }; HTMLTrackElement.NONE = NONE; HTMLTrackElement.LOADING = LOADING; HTMLTrackElement.LOADED = LOADED; HTMLTrackElement.ERROR = ERROR; exports['default'] = HTMLTrackElement; },{"42":42,"72":72,"78":78,"94":94}],67:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _browser = _dereq_(78); var browser = _interopRequireWildcard(_browser); var _document = _dereq_(94); var _document2 = _interopRequireDefault(_document); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * @file text-track-cue-list.js */ /** * @typedef {Object} TextTrackCue * * @property {string} id * The unique id for this text track cue * * @property {number} startTime * The start time for this text track cue * * @property {number} endTime * The end time for this text track cue * * @property {boolean} pauseOnExit * Pause when the end time is reached if true. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcue} */ /** * A List of TextTrackCues. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist} */ var TextTrackCueList = function () { /** * Create an instance of this class.. * * @param {Array} cues * A list of cues to be initialized with */ function TextTrackCueList(cues) { _classCallCheck(this, TextTrackCueList); var list = this; // eslint-disable-line if (browser.IS_IE8) { list = _document2['default'].createElement('custom'); for (var prop in TextTrackCueList.prototype) { if (prop !== 'constructor') { list[prop] = TextTrackCueList.prototype[prop]; } } } TextTrackCueList.prototype.setCues_.call(list, cues); /** * @member {number} length * The current number of `TextTrackCue`s in the TextTrackCueList. */ Object.defineProperty(list, 'length', { get: function get() { return this.length_; } }); if (browser.IS_IE8) { return list; } } /** * A setter for cues in this list. Creates getters * an an index for the cues. * * @param {Array} cues * An array of cues to set * * @private */ TextTrackCueList.prototype.setCues_ = function setCues_(cues) { var oldLength = this.length || 0; var i = 0; var l = cues.length; this.cues_ = cues; this.length_ = cues.length; var defineProp = function defineProp(index) { if (!('' + index in this)) { Object.defineProperty(this, '' + index, { get: function get() { return this.cues_[index]; } }); } }; if (oldLength < l) { i = oldLength; for (; i < l; i++) { defineProp.call(this, i); } } }; /** * Get a `TextTrackCue` that is currently in the `TextTrackCueList` by id. * * @param {string} id * The id of the cue that should be searched for. * * @return {TextTrackCue|null} * A single cue or null if none was found. */ TextTrackCueList.prototype.getCueById = function getCueById(id) { var result = null; for (var i = 0, l = this.length; i < l; i++) { var cue = this[i]; if (cue.id === id) { result = cue; break; } } return result; }; return TextTrackCueList; }(); exports['default'] = TextTrackCueList; },{"78":78,"94":94}],68:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); var _window = _dereq_(95); var _window2 = _interopRequireDefault(_window); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file text-track-display.js */ var darkGray = '#222'; var lightGray = '#ccc'; var fontMap = { monospace: 'monospace', sansSerif: 'sans-serif', serif: 'serif', monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace', monospaceSerif: '"Courier New", monospace', proportionalSansSerif: 'sans-serif', proportionalSerif: 'serif', casual: '"Comic Sans MS", Impact, fantasy', script: '"Monotype Corsiva", cursive', smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif' }; /** * Construct an rgba color from a given hex color code. * * @param {number} color * Hex number for color, like #f0e. * * @param {number} opacity * Value for opacity, 0.0 - 1.0. * * @return {string} * The rgba color that was created, like 'rgba(255, 0, 0, 0.3)'. * * @private */ function constructColor(color, opacity) { return 'rgba(' + // color looks like "#f0e" parseInt(color[1] + color[1], 16) + ',' + parseInt(color[2] + color[2], 16) + ',' + parseInt(color[3] + color[3], 16) + ',' + opacity + ')'; } /** * Try to update the style of a DOM element. Some style changes will throw an error, * particularly in IE8. Those should be noops. * * @param {Element} el * The DOM element to be styled. * * @param {string} style * The CSS property on the element that should be styled. * * @param {string} rule * The style rule that should be applied to the property. */ function tryUpdateStyle(el, style, rule) { try { el.style[style] = rule; } catch (e) { // Satisfies linter. return; } } /** * The component for displaying text track cues. * * @extends Component */ var TextTrackDisplay = function (_Component) { _inherits(TextTrackDisplay, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} [ready] * The function to call when `TextTrackDisplay` is ready. */ function TextTrackDisplay(player, options, ready) { _classCallCheck(this, TextTrackDisplay); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options, ready)); player.on('loadstart', Fn.bind(_this, _this.toggleDisplay)); player.on('texttrackchange', Fn.bind(_this, _this.updateDisplay)); // This used to be called during player init, but was causing an error // if a track should show by default and the display hadn't loaded yet. // Should probably be moved to an external track loader when we support // tracks that don't need a display. player.ready(Fn.bind(_this, function () { if (player.tech_ && player.tech_.featuresNativeTextTracks) { this.hide(); return; } player.on('fullscreenchange', Fn.bind(this, this.updateDisplay)); var tracks = this.options_.playerOptions.tracks || []; for (var i = 0; i < tracks.length; i++) { this.player_.addRemoteTextTrack(tracks[i], true); } var modes = { captions: 1, subtitles: 1 }; var trackList = this.player_.textTracks(); var firstDesc = void 0; var firstCaptions = void 0; if (trackList) { for (var _i = 0; _i < trackList.length; _i++) { var track = trackList[_i]; if (track['default']) { if (track.kind === 'descriptions' && !firstDesc) { firstDesc = track; } else if (track.kind in modes && !firstCaptions) { firstCaptions = track; } } } // We want to show the first default track but captions and subtitles // take precedence over descriptions. // So, display the first default captions or subtitles track // and otherwise the first default descriptions track. if (firstCaptions) { firstCaptions.mode = 'showing'; } else if (firstDesc) { firstDesc.mode = 'showing'; } } })); return _this; } /** * Turn display of {@link TextTrack}'s from the current state into the other state. * There are only two states: * - 'shown' * - 'hidden' * * @listens Player#loadstart */ TextTrackDisplay.prototype.toggleDisplay = function toggleDisplay() { if (this.player_.tech_ && this.player_.tech_.featuresNativeTextTracks) { this.hide(); } else { this.show(); } }; /** * Create the {@link Component}'s DOM element. * * @return {Element} * The element that was created. */ TextTrackDisplay.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-text-track-display' }, { 'aria-live': 'off', 'aria-atomic': 'true' }); }; /** * Clear all displayed {@link TextTrack}s. */ TextTrackDisplay.prototype.clearDisplay = function clearDisplay() { if (typeof _window2['default'].WebVTT === 'function') { _window2['default'].WebVTT.processCues(_window2['default'], [], this.el_); } }; /** * Update the displayed TextTrack when a either a {@link Player#texttrackchange} or * a {@link Player#fullscreenchange} is fired. * * @listens Player#texttrackchange * @listens Player#fullscreenchange */ TextTrackDisplay.prototype.updateDisplay = function updateDisplay() { var tracks = this.player_.textTracks(); this.clearDisplay(); if (!tracks) { return; } // Track display prioritization model: if multiple tracks are 'showing', // display the first 'subtitles' or 'captions' track which is 'showing', // otherwise display the first 'descriptions' track which is 'showing' var descriptionsTrack = null; var captionsSubtitlesTrack = null; var i = tracks.length; while (i--) { var track = tracks[i]; if (track.mode === 'showing') { if (track.kind === 'descriptions') { descriptionsTrack = track; } else { captionsSubtitlesTrack = track; } } } if (captionsSubtitlesTrack) { if (this.getAttribute('aria-live') !== 'off') { this.setAttribute('aria-live', 'off'); } this.updateForTrack(captionsSubtitlesTrack); } else if (descriptionsTrack) { if (this.getAttribute('aria-live') !== 'assertive') { this.setAttribute('aria-live', 'assertive'); } this.updateForTrack(descriptionsTrack); } }; /** * Add an {@link Texttrack} to to the {@link Tech}s {@link TextTrackList}. * * @param {TextTrack} track * Text track object to be added to the list. */ TextTrackDisplay.prototype.updateForTrack = function updateForTrack(track) { if (typeof _window2['default'].WebVTT !== 'function' || !track.activeCues) { return; } var overrides = this.player_.textTrackSettings.getValues(); var cues = []; for (var _i2 = 0; _i2 < track.activeCues.length; _i2++) { cues.push(track.activeCues[_i2]); } _window2['default'].WebVTT.processCues(_window2['default'], cues, this.el_); var i = cues.length; while (i--) { var cue = cues[i]; if (!cue) { continue; } var cueDiv = cue.displayState; if (overrides.color) { cueDiv.firstChild.style.color = overrides.color; } if (overrides.textOpacity) { tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity)); } if (overrides.backgroundColor) { cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor; } if (overrides.backgroundOpacity) { tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity)); } if (overrides.windowColor) { if (overrides.windowOpacity) { tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity)); } else { cueDiv.style.backgroundColor = overrides.windowColor; } } if (overrides.edgeStyle) { if (overrides.edgeStyle === 'dropshadow') { cueDiv.firstChild.style.textShadow = '2px 2px 3px ' + darkGray + ', 2px 2px 4px ' + darkGray + ', 2px 2px 5px ' + darkGray; } else if (overrides.edgeStyle === 'raised') { cueDiv.firstChild.style.textShadow = '1px 1px ' + darkGray + ', 2px 2px ' + darkGray + ', 3px 3px ' + darkGray; } else if (overrides.edgeStyle === 'depressed') { cueDiv.firstChild.style.textShadow = '1px 1px ' + lightGray + ', 0 1px ' + lightGray + ', -1px -1px ' + darkGray + ', 0 -1px ' + darkGray; } else if (overrides.edgeStyle === 'uniform') { cueDiv.firstChild.style.textShadow = '0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray; } } if (overrides.fontPercent && overrides.fontPercent !== 1) { var fontSize = _window2['default'].parseFloat(cueDiv.style.fontSize); cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px'; cueDiv.style.height = 'auto'; cueDiv.style.top = 'auto'; cueDiv.style.bottom = '2px'; } if (overrides.fontFamily && overrides.fontFamily !== 'default') { if (overrides.fontFamily === 'small-caps') { cueDiv.firstChild.style.fontVariant = 'small-caps'; } else { cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily]; } } } }; return TextTrackDisplay; }(_component2['default']); _component2['default'].registerComponent('TextTrackDisplay', TextTrackDisplay); exports['default'] = TextTrackDisplay; },{"5":5,"83":83,"95":95}],69:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; /** * @file text-track-list-converter.js Utilities for capturing text track state and * re-creating tracks based on a capture. * * @module text-track-list-converter */ /** * Examine a single {@link TextTrack} and return a JSON-compatible javascript object that * represents the {@link TextTrack}'s state. * * @param {TextTrack} track * The text track to query. * * @return {Object} * A serializable javascript representation of the TextTrack. * @private */ var trackToJson_ = function trackToJson_(track) { var ret = ['kind', 'label', 'language', 'id', 'inBandMetadataTrackDispatchType', 'mode', 'src'].reduce(function (acc, prop, i) { if (track[prop]) { acc[prop] = track[prop]; } return acc; }, { cues: track.cues && Array.prototype.map.call(track.cues, function (cue) { return { startTime: cue.startTime, endTime: cue.endTime, text: cue.text, id: cue.id }; }) }); return ret; }; /** * Examine a {@link Tech} and return a JSON-compatible javascript array that represents the * state of all {@link TextTrack}s currently configured. The return array is compatible with * {@link text-track-list-converter:jsonToTextTracks}. * * @param {Tech} tech * The tech object to query * * @return {Array} * A serializable javascript representation of the {@link Tech}s * {@link TextTrackList}. */ var textTracksToJson = function textTracksToJson(tech) { var trackEls = tech.$$('track'); var trackObjs = Array.prototype.map.call(trackEls, function (t) { return t.track; }); var tracks = Array.prototype.map.call(trackEls, function (trackEl) { var json = trackToJson_(trackEl.track); if (trackEl.src) { json.src = trackEl.src; } return json; }); return tracks.concat(Array.prototype.filter.call(tech.textTracks(), function (track) { return trackObjs.indexOf(track) === -1; }).map(trackToJson_)); }; /** * Create a set of remote {@link TextTrack}s on a {@link Tech} based on an array of javascript * object {@link TextTrack} representations. * * @param {Array} json * An array of `TextTrack` representation objects, like those that would be * produced by `textTracksToJson`. * * @param {Tech} tech * The `Tech` to create the `TextTrack`s on. */ var jsonToTextTracks = function jsonToTextTracks(json, tech) { json.forEach(function (track) { var addedTrack = tech.addRemoteTextTrack(track).track; if (!track.src && track.cues) { track.cues.forEach(function (cue) { return addedTrack.addCue(cue); }); } }); return tech.textTracks(); }; exports['default'] = { textTracksToJson: textTracksToJson, jsonToTextTracks: jsonToTextTracks, trackToJson_: trackToJson_ }; },{}],70:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _trackList = _dereq_(74); var _trackList2 = _interopRequireDefault(_trackList); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); var _browser = _dereq_(78); var browser = _interopRequireWildcard(_browser); var _document = _dereq_(94); var _document2 = _interopRequireDefault(_document); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file text-track-list.js */ /** * The current list of {@link TextTrack} for a media file. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist} * @extends TrackList */ var TextTrackList = function (_TrackList) { _inherits(TextTrackList, _TrackList); /** * Create an instance of this class. * * @param {TextTrack[]} [tracks=[]] * A list of `TextTrack` to instantiate the list with. */ function TextTrackList() { var _this, _ret; var tracks = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; _classCallCheck(this, TextTrackList); var list = void 0; // IE8 forces us to implement inheritance ourselves // as it does not support Object.defineProperty properly if (browser.IS_IE8) { list = _document2['default'].createElement('custom'); for (var prop in _trackList2['default'].prototype) { if (prop !== 'constructor') { list[prop] = _trackList2['default'].prototype[prop]; } } for (var _prop in TextTrackList.prototype) { if (_prop !== 'constructor') { list[_prop] = TextTrackList.prototype[_prop]; } } } list = (_this = _possibleConstructorReturn(this, _TrackList.call(this, tracks, list)), _this); return _ret = list, _possibleConstructorReturn(_this, _ret); } /** * Add a {@link TextTrack} to the `TextTrackList` * * @param {TextTrack} track * The text track to add to the list. * * @fires TrackList#addtrack * @private */ TextTrackList.prototype.addTrack_ = function addTrack_(track) { _TrackList.prototype.addTrack_.call(this, track); /** * @listens TextTrack#modechange * @fires TrackList#change */ track.addEventListener('modechange', Fn.bind(this, function () { this.trigger('change'); })); }; return TextTrackList; }(_trackList2['default']); exports['default'] = TextTrackList; },{"74":74,"78":78,"83":83,"94":94}],71:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _window = _dereq_(95); var _window2 = _interopRequireDefault(_window); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _dom = _dereq_(81); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); var _obj = _dereq_(88); var Obj = _interopRequireWildcard(_obj); var _log = _dereq_(86); var _log2 = _interopRequireDefault(_log); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file text-track-settings.js */ var LOCAL_STORAGE_KEY = 'vjs-text-track-settings'; var COLOR_BLACK = ['#000', 'Black']; var COLOR_BLUE = ['#00F', 'Blue']; var COLOR_CYAN = ['#0FF', 'Cyan']; var COLOR_GREEN = ['#0F0', 'Green']; var COLOR_MAGENTA = ['#F0F', 'Magenta']; var COLOR_RED = ['#F00', 'Red']; var COLOR_WHITE = ['#FFF', 'White']; var COLOR_YELLOW = ['#FF0', 'Yellow']; var OPACITY_OPAQUE = ['1', 'Opaque']; var OPACITY_SEMI = ['0.5', 'Semi-Transparent']; var OPACITY_TRANS = ['0', 'Transparent']; // Configuration for the various <select> elements in the DOM of this component. // // Possible keys include: // // `default`: // The default option index. Only needs to be provided if not zero. // `parser`: // A function which is used to parse the value from the selected option in // a customized way. // `selector`: // The selector used to find the associated <select> element. var selectConfigs = { backgroundColor: { selector: '.vjs-bg-color > select', id: 'captions-background-color-%s', label: 'Color', options: [COLOR_BLACK, COLOR_WHITE, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN] }, backgroundOpacity: { selector: '.vjs-bg-opacity > select', id: 'captions-background-opacity-%s', label: 'Transparency', options: [OPACITY_OPAQUE, OPACITY_SEMI, OPACITY_TRANS] }, color: { selector: '.vjs-fg-color > select', id: 'captions-foreground-color-%s', label: 'Color', options: [COLOR_WHITE, COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN] }, edgeStyle: { selector: '.vjs-edge-style > select', id: '%s', label: 'Text Edge Style', options: [['none', 'None'], ['raised', 'Raised'], ['depressed', 'Depressed'], ['uniform', 'Uniform'], ['dropshadow', 'Dropshadow']] }, fontFamily: { selector: '.vjs-font-family > select', id: 'captions-font-family-%s', label: 'Font Family', options: [['proportionalSansSerif', 'Proportional Sans-Serif'], ['monospaceSansSerif', 'Monospace Sans-Serif'], ['proportionalSerif', 'Proportional Serif'], ['monospaceSerif', 'Monospace Serif'], ['casual', 'Casual'], ['script', 'Script'], ['small-caps', 'Small Caps']] }, fontPercent: { selector: '.vjs-font-percent > select', id: 'captions-font-size-%s', label: 'Font Size', options: [['0.50', '50%'], ['0.75', '75%'], ['1.00', '100%'], ['1.25', '125%'], ['1.50', '150%'], ['1.75', '175%'], ['2.00', '200%'], ['3.00', '300%'], ['4.00', '400%']], 'default': 2, parser: function parser(v) { return v === '1.00' ? null : Number(v); } }, textOpacity: { selector: '.vjs-text-opacity > select', id: 'captions-foreground-opacity-%s', label: 'Transparency', options: [OPACITY_OPAQUE, OPACITY_SEMI] }, // Options for this object are defined below. windowColor: { selector: '.vjs-window-color > select', id: 'captions-window-color-%s', label: 'Color' }, // Options for this object are defined below. windowOpacity: { selector: '.vjs-window-opacity > select', id: 'captions-window-opacity-%s', label: 'Transparency', options: [OPACITY_TRANS, OPACITY_SEMI, OPACITY_OPAQUE] } }; selectConfigs.windowColor.options = selectConfigs.backgroundColor.options; /** * Get the actual value of an option. * * @param {string} value * The value to get * * @param {Function} [parser] * Optional function to adjust the value. * * @return {Mixed} * - Will be `undefined` if no value exists * - Will be `undefined` if the given value is "none". * - Will be the actual value otherwise. * * @private */ function parseOptionValue(value, parser) { if (parser) { value = parser(value); } if (value && value !== 'none') { return value; } } /** * Gets the value of the selected <option> element within a <select> element. * * @param {Element} el * the element to look in * * @param {Function} [parser] * Optional function to adjust the value. * * @return {Mixed} * - Will be `undefined` if no value exists * - Will be `undefined` if the given value is "none". * - Will be the actual value otherwise. * * @private */ function getSelectedOptionValue(el, parser) { var value = el.options[el.options.selectedIndex].value; return parseOptionValue(value, parser); } /** * Sets the selected <option> element within a <select> element based on a * given value. * * @param {Element} el * The element to look in. * * @param {string} value * the property to look on. * * @param {Function} [parser] * Optional function to adjust the value before comparing. * * @private */ function setSelectedOption(el, value, parser) { if (!value) { return; } for (var i = 0; i < el.options.length; i++) { if (parseOptionValue(el.options[i].value, parser) === value) { el.selectedIndex = i; break; } } } /** * Manipulate Text Tracks settings. * * @extends Component */ var TextTrackSettings = function (_Component) { _inherits(TextTrackSettings, _Component); /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. */ function TextTrackSettings(player, options) { _classCallCheck(this, TextTrackSettings); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.setDefaults(); _this.hide(); _this.updateDisplay = Fn.bind(_this, _this.updateDisplay); // Grab `persistTextTrackSettings` from the player options if not passed in child options if (options.persistTextTrackSettings === undefined) { _this.options_.persistTextTrackSettings = _this.options_.playerOptions.persistTextTrackSettings; } _this.on(_this.$('.vjs-done-button'), 'click', function () { _this.saveSettings(); _this.hide(); }); _this.on(_this.$('.vjs-default-button'), 'click', function () { _this.setDefaults(); _this.updateDisplay(); }); Obj.each(selectConfigs, function (config) { _this.on(_this.$(config.selector), 'change', _this.updateDisplay); }); if (_this.options_.persistTextTrackSettings) { _this.restoreSettings(); } return _this; } /** * Create a <select> element with configured options. * * @param {string} key * Configuration key to use during creation. * * @return {Element} * The DOM element that gets created. * @private */ TextTrackSettings.prototype.createElSelect_ = function createElSelect_(key) { var _this2 = this; var config = selectConfigs[key]; var id = config.id.replace('%s', this.id_); return [(0, _dom.createEl)('label', { className: 'vjs-label', textContent: config.label }, { 'for': id }), (0, _dom.createEl)('select', { id: id }, undefined, config.options.map(function (o) { return (0, _dom.createEl)('option', { textContent: _this2.localize(o[1]), value: o[0] }); }))]; }; /** * Create foreground color element for the component * * @return {Element} * The element that was created. * * @private */ TextTrackSettings.prototype.createElFgColor_ = function createElFgColor_() { var legend = (0, _dom.createEl)('legend', { textContent: this.localize('Text') }); var select = this.createElSelect_('color'); var opacity = (0, _dom.createEl)('span', { className: 'vjs-text-opacity vjs-opacity' }, undefined, this.createElSelect_('textOpacity')); return (0, _dom.createEl)('fieldset', { className: 'vjs-fg-color vjs-tracksetting' }, undefined, [legend].concat(select, opacity)); }; /** * Create background color element for the component * * @return {Element} * The element that was created * * @private */ TextTrackSettings.prototype.createElBgColor_ = function createElBgColor_() { var legend = (0, _dom.createEl)('legend', { textContent: this.localize('Background') }); var select = this.createElSelect_('backgroundColor'); var opacity = (0, _dom.createEl)('span', { className: 'vjs-bg-opacity vjs-opacity' }, undefined, this.createElSelect_('backgroundOpacity')); return (0, _dom.createEl)('fieldset', { className: 'vjs-bg-color vjs-tracksetting' }, undefined, [legend].concat(select, opacity)); }; /** * Create window color element for the component * * @return {Element} * The element that was created * * @private */ TextTrackSettings.prototype.createElWinColor_ = function createElWinColor_() { var legend = (0, _dom.createEl)('legend', { textContent: this.localize('Window') }); var select = this.createElSelect_('windowColor'); var opacity = (0, _dom.createEl)('span', { className: 'vjs-window-opacity vjs-opacity' }, undefined, this.createElSelect_('windowOpacity')); return (0, _dom.createEl)('fieldset', { className: 'vjs-window-color vjs-tracksetting' }, undefined, [legend].concat(select, opacity)); }; /** * Create color elements for the component * * @return {Element} * The element that was created * * @private */ TextTrackSettings.prototype.createElColors_ = function createElColors_() { return (0, _dom.createEl)('div', { className: 'vjs-tracksettings-colors' }, undefined, [this.createElFgColor_(), this.createElBgColor_(), this.createElWinColor_()]); }; /** * Create font elements for the component * * @return {Element} * The element that was created. * * @private */ TextTrackSettings.prototype.createElFont_ = function createElFont_() { var fontPercent = (0, _dom.createEl)('div', { className: 'vjs-font-percent vjs-tracksetting' }, undefined, this.createElSelect_('fontPercent')); var edgeStyle = (0, _dom.createEl)('div', { className: 'vjs-edge-style vjs-tracksetting' }, undefined, this.createElSelect_('edgeStyle')); var fontFamily = (0, _dom.createEl)('div', { className: 'vjs-font-family vjs-tracksetting' }, undefined, this.createElSelect_('fontFamily')); return (0, _dom.createEl)('div', { className: 'vjs-tracksettings-font' }, undefined, [fontPercent, edgeStyle, fontFamily]); }; /** * Create controls for the component * * @return {Element} * The element that was created. * * @private */ TextTrackSettings.prototype.createElControls_ = function createElControls_() { var defaultsButton = (0, _dom.createEl)('button', { className: 'vjs-default-button', textContent: this.localize('Defaults') }); var doneButton = (0, _dom.createEl)('button', { className: 'vjs-done-button', textContent: 'Done' }); return (0, _dom.createEl)('div', { className: 'vjs-tracksettings-controls' }, undefined, [defaultsButton, doneButton]); }; /** * Create the component's DOM element * * @return {Element} * The element that was created. */ TextTrackSettings.prototype.createEl = function createEl() { var settings = (0, _dom.createEl)('div', { className: 'vjs-tracksettings' }, undefined, [this.createElColors_(), this.createElFont_(), this.createElControls_()]); var heading = (0, _dom.createEl)('div', { className: 'vjs-control-text', id: 'TTsettingsDialogLabel-' + this.id_, textContent: 'Caption Settings Dialog' }, { 'aria-level': '1', 'role': 'heading' }); var description = (0, _dom.createEl)('div', { className: 'vjs-control-text', id: 'TTsettingsDialogDescription-' + this.id_, textContent: 'Beginning of dialog window. Escape will cancel and close the window.' }); var doc = (0, _dom.createEl)('div', undefined, { role: 'document' }, [heading, description, settings]); return (0, _dom.createEl)('div', { className: 'vjs-caption-settings vjs-modal-overlay', tabIndex: -1 }, { 'role': 'dialog', 'aria-labelledby': heading.id, 'aria-describedby': description.id }, doc); }; /** * Gets an object of text track settings (or null). * * @return {Object} * An object with config values parsed from the DOM or localStorage. */ TextTrackSettings.prototype.getValues = function getValues() { var _this3 = this; return Obj.reduce(selectConfigs, function (accum, config, key) { var value = getSelectedOptionValue(_this3.$(config.selector), config.parser); if (value !== undefined) { accum[key] = value; } return accum; }, {}); }; /** * Sets text track settings from an object of values. * * @param {Object} values * An object with config values parsed from the DOM or localStorage. */ TextTrackSettings.prototype.setValues = function setValues(values) { var _this4 = this; Obj.each(selectConfigs, function (config, key) { setSelectedOption(_this4.$(config.selector), values[key], config.parser); }); }; /** * Sets all <select> elements to their default values. */ TextTrackSettings.prototype.setDefaults = function setDefaults() { var _this5 = this; Obj.each(selectConfigs, function (config) { var index = config.hasOwnProperty('default') ? config['default'] : 0; _this5.$(config.selector).selectedIndex = index; }); }; /** * Restore texttrack settings from localStorage */ TextTrackSettings.prototype.restoreSettings = function restoreSettings() { var values = void 0; try { values = JSON.parse(_window2['default'].localStorage.getItem(LOCAL_STORAGE_KEY)); } catch (err) { _log2['default'].warn(err); } if (values) { this.setValues(values); } }; /** * Save text track settings to localStorage */ TextTrackSettings.prototype.saveSettings = function saveSettings() { if (!this.options_.persistTextTrackSettings) { return; } var values = this.getValues(); try { if (Object.keys(values).length) { _window2['default'].localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(values)); } else { _window2['default'].localStorage.removeItem(LOCAL_STORAGE_KEY); } } catch (err) { _log2['default'].warn(err); } }; /** * Update display of text track settings */ TextTrackSettings.prototype.updateDisplay = function updateDisplay() { var ttDisplay = this.player_.getChild('textTrackDisplay'); if (ttDisplay) { ttDisplay.updateDisplay(); } }; return TextTrackSettings; }(_component2['default']); _component2['default'].registerComponent('TextTrackSettings', TextTrackSettings); exports['default'] = TextTrackSettings; },{"5":5,"81":81,"83":83,"86":86,"88":88,"95":95}],72:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _textTrackCueList = _dereq_(67); var _textTrackCueList2 = _interopRequireDefault(_textTrackCueList); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); var _trackEnums = _dereq_(73); var _log = _dereq_(86); var _log2 = _interopRequireDefault(_log); var _window = _dereq_(95); var _window2 = _interopRequireDefault(_window); var _track = _dereq_(75); var _track2 = _interopRequireDefault(_track); var _url = _dereq_(92); var _xhr = _dereq_(99); var _xhr2 = _interopRequireDefault(_xhr); var _mergeOptions = _dereq_(87); var _mergeOptions2 = _interopRequireDefault(_mergeOptions); var _browser = _dereq_(78); var browser = _interopRequireWildcard(_browser); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file text-track.js */ /** * Takes a webvtt file contents and parses it into cues * * @param {string} srcContent * webVTT file contents * * @param {TextTrack} track * TextTrack to add cues to. Cues come from the srcContent. * * @private */ var parseCues = function parseCues(srcContent, track) { var parser = new _window2['default'].WebVTT.Parser(_window2['default'], _window2['default'].vttjs, _window2['default'].WebVTT.StringDecoder()); var errors = []; parser.oncue = function (cue) { track.addCue(cue); }; parser.onparsingerror = function (error) { errors.push(error); }; parser.onflush = function () { track.trigger({ type: 'loadeddata', target: track }); }; parser.parse(srcContent); if (errors.length > 0) { if (_window2['default'].console && _window2['default'].console.groupCollapsed) { _window2['default'].console.groupCollapsed('Text Track parsing errors for ' + track.src); } errors.forEach(function (error) { return _log2['default'].error(error); }); if (_window2['default'].console && _window2['default'].console.groupEnd) { _window2['default'].console.groupEnd(); } } parser.flush(); }; /** * Load a `TextTrack` from a specifed url. * * @param {string} src * Url to load track from. * * @param {TextTrack} track * Track to add cues to. Comes from the content at the end of `url`. * * @private */ var loadTrack = function loadTrack(src, track) { var opts = { uri: src }; var crossOrigin = (0, _url.isCrossOrigin)(src); if (crossOrigin) { opts.cors = crossOrigin; } (0, _xhr2['default'])(opts, Fn.bind(this, function (err, response, responseBody) { if (err) { return _log2['default'].error(err, response); } track.loaded_ = true; // Make sure that vttjs has loaded, otherwise, wait till it finished loading // NOTE: this is only used for the alt/video.novtt.js build if (typeof _window2['default'].WebVTT !== 'function') { if (track.tech_) { var loadHandler = function loadHandler() { return parseCues(responseBody, track); }; track.tech_.on('vttjsloaded', loadHandler); track.tech_.on('vttjserror', function () { _log2['default'].error('vttjs failed to load, stopping trying to process ' + track.src); track.tech_.off('vttjsloaded', loadHandler); }); } } else { parseCues(responseBody, track); } })); }; /** * A representation of a single `TextTrack`. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack} * @extends Track */ var TextTrack = function (_Track) { _inherits(TextTrack, _Track); /** * Create an instance of this class. * * @param {Object} options={} * Object of option names and values * * @param {Tech} options.tech * A reference to the tech that owns this TextTrack. * * @param {TextTrack~Kind} [options.kind='subtitles'] * A valid text track kind. * * @param {TextTrack~Mode} [options.mode='disabled'] * A valid text track mode. * * @param {string} [options.id='vjs_track_' + Guid.newGUID()] * A unique id for this TextTrack. * * @param {string} [options.label=''] * The menu label for this track. * * @param {string} [options.language=''] * A valid two character language code. * * @param {string} [options.srclang=''] * A valid two character language code. An alternative, but deprioritized * vesion of `options.language` * * @param {string} [options.src] * A url to TextTrack cues. * * @param {boolean} [options.default] * If this track should default to on or off. */ function TextTrack() { var _this, _ret; var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, TextTrack); if (!options.tech) { throw new Error('A tech was not provided.'); } var settings = (0, _mergeOptions2['default'])(options, { kind: _trackEnums.TextTrackKind[options.kind] || 'subtitles', language: options.language || options.srclang || '' }); var mode = _trackEnums.TextTrackMode[settings.mode] || 'disabled'; var default_ = settings['default']; if (settings.kind === 'metadata' || settings.kind === 'chapters') { mode = 'hidden'; } // on IE8 this will be a document element // for every other browser this will be a normal object var tt = (_this = _possibleConstructorReturn(this, _Track.call(this, settings)), _this); tt.tech_ = settings.tech; if (browser.IS_IE8) { for (var prop in TextTrack.prototype) { if (prop !== 'constructor') { tt[prop] = TextTrack.prototype[prop]; } } } tt.cues_ = []; tt.activeCues_ = []; var cues = new _textTrackCueList2['default'](tt.cues_); var activeCues = new _textTrackCueList2['default'](tt.activeCues_); var changed = false; var timeupdateHandler = Fn.bind(tt, function () { // Accessing this.activeCues for the side-effects of updating itself // due to it's nature as a getter function. Do not remove or cues will // stop updating! /* eslint-disable no-unused-expressions */ this.activeCues; /* eslint-enable no-unused-expressions */ if (changed) { this.trigger('cuechange'); changed = false; } }); if (mode !== 'disabled') { tt.tech_.ready(function () { tt.tech_.on('timeupdate', timeupdateHandler); }, true); } /** * @member {boolean} default * If this track was set to be on or off by default. Cannot be changed after * creation. * * @readonly */ Object.defineProperty(tt, 'default', { get: function get() { return default_; }, set: function set() {} }); /** * @member {string} mode * Set the mode of this TextTrack to a valid {@link TextTrack~Mode}. Will * not be set if setting to an invalid mode. * * @fires TextTrack#modechange */ Object.defineProperty(tt, 'mode', { get: function get() { return mode; }, set: function set(newMode) { var _this2 = this; if (!_trackEnums.TextTrackMode[newMode]) { return; } mode = newMode; if (mode === 'showing') { this.tech_.ready(function () { _this2.tech_.on('timeupdate', timeupdateHandler); }, true); } /** * An event that fires when mode changes on this track. This allows * the TextTrackList that holds this track to act accordingly. * * > Note: This is not part of the spec! * * @event TextTrack#modechange * @type {EventTarget~Event} */ this.trigger('modechange'); } }); /** * @member {TextTrackCueList} cues * The text track cue list for this TextTrack. */ Object.defineProperty(tt, 'cues', { get: function get() { if (!this.loaded_) { return null; } return cues; }, set: function set() {} }); /** * @member {TextTrackCueList} activeCues * The list text track cues that are currently active for this TextTrack. */ Object.defineProperty(tt, 'activeCues', { get: function get() { if (!this.loaded_) { return null; } // nothing to do if (this.cues.length === 0) { return activeCues; } var ct = this.tech_.currentTime(); var active = []; for (var i = 0, l = this.cues.length; i < l; i++) { var cue = this.cues[i]; if (cue.startTime <= ct && cue.endTime >= ct) { active.push(cue); } else if (cue.startTime === cue.endTime && cue.startTime <= ct && cue.startTime + 0.5 >= ct) { active.push(cue); } } changed = false; if (active.length !== this.activeCues_.length) { changed = true; } else { for (var _i = 0; _i < active.length; _i++) { if (this.activeCues_.indexOf(active[_i]) === -1) { changed = true; } } } this.activeCues_ = active; activeCues.setCues_(this.activeCues_); return activeCues; }, set: function set() {} }); if (settings.src) { tt.src = settings.src; loadTrack(settings.src, tt); } else { tt.loaded_ = true; } return _ret = tt, _possibleConstructorReturn(_this, _ret); } /** * Add a cue to the internal list of cues. * * @param {TextTrack~Cue} cue * The cue to add to our internal list */ TextTrack.prototype.addCue = function addCue(originalCue) { var cue = originalCue; if (_window2['default'].vttjs && !(originalCue instanceof _window2['default'].vttjs.VTTCue)) { cue = new _window2['default'].vttjs.VTTCue(originalCue.startTime, originalCue.endTime, originalCue.text); for (var prop in originalCue) { if (!(prop in cue)) { cue[prop] = originalCue[prop]; } } // make sure that `id` is copied over cue.id = originalCue.id; cue.originalCue_ = originalCue; } var tracks = this.tech_.textTracks(); if (tracks) { for (var i = 0; i < tracks.length; i++) { if (tracks[i] !== this) { tracks[i].removeCue(cue); } } } this.cues_.push(cue); this.cues.setCues_(this.cues_); }; /** * Remove a cue from our internal list * * @param {TextTrack~Cue} removeCue * The cue to remove from our internal list */ TextTrack.prototype.removeCue = function removeCue(_removeCue) { var i = this.cues_.length; while (i--) { var cue = this.cues_[i]; if (cue === _removeCue || cue.originalCue_ && cue.originalCue_ === _removeCue) { this.cues_.splice(i, 1); this.cues.setCues_(this.cues_); break; } } }; return TextTrack; }(_track2['default']); /** * cuechange - One or more cues in the track have become active or stopped being active. */ TextTrack.prototype.allowedEvents_ = { cuechange: 'cuechange' }; exports['default'] = TextTrack; },{"67":67,"73":73,"75":75,"78":78,"83":83,"86":86,"87":87,"92":92,"95":95,"99":99}],73:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; /** * @file track-kinds.js */ /** * All possible `VideoTrackKind`s * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-videotrack-kind * @typedef VideoTrack~Kind * @enum */ var VideoTrackKind = exports.VideoTrackKind = { alternative: 'alternative', captions: 'captions', main: 'main', sign: 'sign', subtitles: 'subtitles', commentary: 'commentary' }; /** * All possible `AudioTrackKind`s * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-audiotrack-kind * @typedef AudioTrack~Kind * @enum */ var AudioTrackKind = exports.AudioTrackKind = { 'alternative': 'alternative', 'descriptions': 'descriptions', 'main': 'main', 'main-desc': 'main-desc', 'translation': 'translation', 'commentary': 'commentary' }; /** * All possible `TextTrackKind`s * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-texttrack-kind * @typedef TextTrack~Kind * @enum */ var TextTrackKind = exports.TextTrackKind = { subtitles: 'subtitles', captions: 'captions', descriptions: 'descriptions', chapters: 'chapters', metadata: 'metadata' }; /** * All possible `TextTrackMode`s * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode * @typedef TextTrack~Mode * @enum */ var TextTrackMode = exports.TextTrackMode = { disabled: 'disabled', hidden: 'hidden', showing: 'showing' }; },{}],74:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _eventTarget = _dereq_(42); var _eventTarget2 = _interopRequireDefault(_eventTarget); var _browser = _dereq_(78); var browser = _interopRequireWildcard(_browser); var _document = _dereq_(94); var _document2 = _interopRequireDefault(_document); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file track-list.js */ /** * Common functionaliy between {@link TextTrackList}, {@link AudioTrackList}, and * {@link VideoTrackList} * * @extends EventTarget */ var TrackList = function (_EventTarget) { _inherits(TrackList, _EventTarget); /** * Create an instance of this class * * @param {Track[]} tracks * A list of tracks to initialize the list with. * * @param {Object} [list] * The child object with inheritance done manually for ie8. * * @abstract */ function TrackList() { var tracks = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var _ret; var list = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; _classCallCheck(this, TrackList); var _this = _possibleConstructorReturn(this, _EventTarget.call(this)); if (!list) { list = _this; // eslint-disable-line if (browser.IS_IE8) { list = _document2['default'].createElement('custom'); for (var prop in TrackList.prototype) { if (prop !== 'constructor') { list[prop] = TrackList.prototype[prop]; } } } } list.tracks_ = []; /** * @member {number} length * The current number of `Track`s in the this Trackist. */ Object.defineProperty(list, 'length', { get: function get() { return this.tracks_.length; } }); for (var i = 0; i < tracks.length; i++) { list.addTrack_(tracks[i]); } // must return the object, as for ie8 it will not be this // but a reference to a document object return _ret = list, _possibleConstructorReturn(_this, _ret); } /** * Add a {@link Track} to the `TrackList` * * @param {Track} track * The audio, video, or text track to add to the list. * * @fires TrackList#addtrack * @private */ TrackList.prototype.addTrack_ = function addTrack_(track) { var index = this.tracks_.length; if (!('' + index in this)) { Object.defineProperty(this, index, { get: function get() { return this.tracks_[index]; } }); } // Do not add duplicate tracks if (this.tracks_.indexOf(track) === -1) { this.tracks_.push(track); /** * Triggered when a track is added to a track list. * * @event TrackList#addtrack * @type {EventTarget~Event} * @property {Track} track * A reference to track that was added. */ this.trigger({ track: track, type: 'addtrack' }); } }; /** * Remove a {@link Track} from the `TrackList` * * @param {Track} track * The audio, video, or text track to remove from the list. * * @fires TrackList#removetrack * @private */ TrackList.prototype.removeTrack_ = function removeTrack_(rtrack) { var track = void 0; for (var i = 0, l = this.length; i < l; i++) { if (this[i] === rtrack) { track = this[i]; if (track.off) { track.off(); } this.tracks_.splice(i, 1); break; } } if (!track) { return; } /** * Triggered when a track is removed from track list. * * @event TrackList#removetrack * @type {EventTarget~Event} * @property {Track} track * A reference to track that was removed. */ this.trigger({ track: track, type: 'removetrack' }); }; /** * Get a Track from the TrackList by a tracks id * * @param {String} id - the id of the track to get * @method getTrackById * @return {Track} * @private */ TrackList.prototype.getTrackById = function getTrackById(id) { var result = null; for (var i = 0, l = this.length; i < l; i++) { var track = this[i]; if (track.id === id) { result = track; break; } } return result; }; return TrackList; }(_eventTarget2['default']); /** * Triggered when a different track is selected/enabled. * * @event TrackList#change * @type {EventTarget~Event} */ /** * Events that can be called with on + eventName. See {@link EventHandler}. * * @property {Object} TrackList#allowedEvents_ * @private */ TrackList.prototype.allowedEvents_ = { change: 'change', addtrack: 'addtrack', removetrack: 'removetrack' }; // emulate attribute EventHandler support to allow for feature detection for (var event in TrackList.prototype.allowedEvents_) { TrackList.prototype['on' + event] = null; } exports['default'] = TrackList; },{"42":42,"78":78,"94":94}],75:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _browser = _dereq_(78); var browser = _interopRequireWildcard(_browser); var _document = _dereq_(94); var _document2 = _interopRequireDefault(_document); var _guid = _dereq_(85); var Guid = _interopRequireWildcard(_guid); var _eventTarget = _dereq_(42); var _eventTarget2 = _interopRequireDefault(_eventTarget); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file track.js */ /** * A Track class that contains all of the common functionality for {@link AudioTrack}, * {@link VideoTrack}, and {@link TextTrack}. * * > Note: This class should not be used directly * * @see {@link https://html.spec.whatwg.org/multipage/embedded-content.html} * @extends EventTarget * @abstract */ var Track = function (_EventTarget) { _inherits(Track, _EventTarget); /** * Create an instance of this class. * * @param {Object} [options={}] * Object of option names and values * * @param {string} [options.kind=''] * A valid kind for the track type you are creating. * * @param {string} [options.id='vjs_track_' + Guid.newGUID()] * A unique id for this AudioTrack. * * @param {string} [options.label=''] * The menu label for this track. * * @param {string} [options.language=''] * A valid two character language code. * * @abstract */ function Track() { var _ret; var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Track); var _this = _possibleConstructorReturn(this, _EventTarget.call(this)); var track = _this; // eslint-disable-line if (browser.IS_IE8) { track = _document2['default'].createElement('custom'); for (var prop in Track.prototype) { if (prop !== 'constructor') { track[prop] = Track.prototype[prop]; } } } var trackProps = { id: options.id || 'vjs_track_' + Guid.newGUID(), kind: options.kind || '', label: options.label || '', language: options.language || '' }; /** * @member {string} id * The id of this track. Cannot be changed after creation. * * @readonly */ /** * @member {string} kind * The kind of track that this is. Cannot be changed after creation. * * @readonly */ /** * @member {string} label * The label of this track. Cannot be changed after creation. * * @readonly */ /** * @member {string} language * The two letter language code for this track. Cannot be changed after * creation. * * @readonly */ var _loop = function _loop(key) { Object.defineProperty(track, key, { get: function get() { return trackProps[key]; }, set: function set() {} }); }; for (var key in trackProps) { _loop(key); } return _ret = track, _possibleConstructorReturn(_this, _ret); } return Track; }(_eventTarget2['default']); exports['default'] = Track; },{"42":42,"78":78,"85":85,"94":94}],76:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _trackList = _dereq_(74); var _trackList2 = _interopRequireDefault(_trackList); var _browser = _dereq_(78); var browser = _interopRequireWildcard(_browser); var _document = _dereq_(94); var _document2 = _interopRequireDefault(_document); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file video-track-list.js */ /** * Un-select all other {@link VideoTrack}s that are selected. * * @param {VideoTrackList} list * list to work on * * @param {VideoTrack} track * The track to skip * * @private */ var disableOthers = function disableOthers(list, track) { for (var i = 0; i < list.length; i++) { if (track.id === list[i].id) { continue; } // another video track is enabled, disable it list[i].selected = false; } }; /** * The current list of {@link VideoTrack} for a video. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist} * @extends TrackList */ var VideoTrackList = function (_TrackList) { _inherits(VideoTrackList, _TrackList); /** * Create an instance of this class. * * @param {VideoTrack[]} [tracks=[]] * A list of `VideoTrack` to instantiate the list with. */ function VideoTrackList() { var _this, _ret; var tracks = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; _classCallCheck(this, VideoTrackList); var list = void 0; // make sure only 1 track is enabled // sorted from last index to first index for (var i = tracks.length - 1; i >= 0; i--) { if (tracks[i].selected) { disableOthers(tracks, tracks[i]); break; } } // IE8 forces us to implement inheritance ourselves // as it does not support Object.defineProperty properly if (browser.IS_IE8) { list = _document2['default'].createElement('custom'); for (var prop in _trackList2['default'].prototype) { if (prop !== 'constructor') { list[prop] = _trackList2['default'].prototype[prop]; } } for (var _prop in VideoTrackList.prototype) { if (_prop !== 'constructor') { list[_prop] = VideoTrackList.prototype[_prop]; } } } list = (_this = _possibleConstructorReturn(this, _TrackList.call(this, tracks, list)), _this); list.changing_ = false; /** * @member {number} VideoTrackList#selectedIndex * The current index of the selected {@link VideoTrack`}. */ Object.defineProperty(list, 'selectedIndex', { get: function get() { for (var _i = 0; _i < this.length; _i++) { if (this[_i].selected) { return _i; } } return -1; }, set: function set() {} }); return _ret = list, _possibleConstructorReturn(_this, _ret); } /** * Add a {@link VideoTrack} to the `VideoTrackList`. * * @param {VideoTrack} track * The VideoTrack to add to the list * * @fires TrackList#addtrack * @private */ VideoTrackList.prototype.addTrack_ = function addTrack_(track) { var _this2 = this; if (track.selected) { disableOthers(this, track); } _TrackList.prototype.addTrack_.call(this, track); // native tracks don't have this if (!track.addEventListener) { return; } /** * @listens VideoTrack#selectedchange * @fires TrackList#change */ track.addEventListener('selectedchange', function () { if (_this2.changing_) { return; } _this2.changing_ = true; disableOthers(_this2, track); _this2.changing_ = false; _this2.trigger('change'); }); }; /** * Add a {@link VideoTrack} to the `VideoTrackList`. * * @param {VideoTrack} track * The VideoTrack to add to the list * * @fires TrackList#addtrack */ VideoTrackList.prototype.addTrack = function addTrack(track) { this.addTrack_(track); }; /** * Remove a {@link VideoTrack} to the `VideoTrackList`. * * @param {VideoTrack} track * The VideoTrack to remove from the list. * * @fires TrackList#removetrack */ VideoTrackList.prototype.removeTrack = function removeTrack(track) { _TrackList.prototype.removeTrack_.call(this, track); }; return VideoTrackList; }(_trackList2['default']); exports['default'] = VideoTrackList; },{"74":74,"78":78,"94":94}],77:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _trackEnums = _dereq_(73); var _track = _dereq_(75); var _track2 = _interopRequireDefault(_track); var _mergeOptions = _dereq_(87); var _mergeOptions2 = _interopRequireDefault(_mergeOptions); var _browser = _dereq_(78); var browser = _interopRequireWildcard(_browser); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * A representation of a single `VideoTrack`. * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotrack} * @extends Track */ var VideoTrack = function (_Track) { _inherits(VideoTrack, _Track); /** * Create an instance of this class. * * @param {Object} [options={}] * Object of option names and values * * @param {string} [options.kind=''] * A valid {@link VideoTrack~Kind} * * @param {string} [options.id='vjs_track_' + Guid.newGUID()] * A unique id for this AudioTrack. * * @param {string} [options.label=''] * The menu label for this track. * * @param {string} [options.language=''] * A valid two character language code. * * @param {boolean} [options.selected] * If this track is the one that is currently playing. */ function VideoTrack() { var _this, _ret; var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, VideoTrack); var settings = (0, _mergeOptions2['default'])(options, { kind: _trackEnums.VideoTrackKind[options.kind] || '' }); // on IE8 this will be a document element // for every other browser this will be a normal object var track = (_this = _possibleConstructorReturn(this, _Track.call(this, settings)), _this); var selected = false; if (browser.IS_IE8) { for (var prop in VideoTrack.prototype) { if (prop !== 'constructor') { track[prop] = VideoTrack.prototype[prop]; } } } /** * @member {boolean} selected * If this `VideoTrack` is selected or not. When setting this will * fire {@link VideoTrack#selectedchange} if the state of selected changed. * * @fires VideoTrack#selectedchange */ Object.defineProperty(track, 'selected', { get: function get() { return selected; }, set: function set(newSelected) { // an invalid or unchanged value if (typeof newSelected !== 'boolean' || newSelected === selected) { return; } selected = newSelected; /** * An event that fires when selected changes on this track. This allows * the VideoTrackList that holds this track to act accordingly. * * > Note: This is not part of the spec! Native tracks will do * this internally without an event. * * @event VideoTrack#selectedchange * @type {EventTarget~Event} */ this.trigger('selectedchange'); } }); // if the user sets this track to selected then // set selected to that true value otherwise // we keep it false if (settings.selected) { track.selected = settings.selected; } return _ret = track, _possibleConstructorReturn(_this, _ret); } return VideoTrack; }(_track2['default']); exports['default'] = VideoTrack; },{"73":73,"75":75,"78":78,"87":87}],78:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.BACKGROUND_SIZE_SUPPORTED = exports.TOUCH_ENABLED = exports.IS_ANY_SAFARI = exports.IS_SAFARI = exports.IE_VERSION = exports.IS_IE8 = exports.IS_CHROME = exports.IS_EDGE = exports.IS_FIREFOX = exports.IS_NATIVE_ANDROID = exports.IS_OLD_ANDROID = exports.ANDROID_VERSION = exports.IS_ANDROID = exports.IOS_VERSION = exports.IS_IOS = exports.IS_IPOD = exports.IS_IPHONE = exports.IS_IPAD = undefined; var _dom = _dereq_(81); var Dom = _interopRequireWildcard(_dom); var _window = _dereq_(95); var _window2 = _interopRequireDefault(_window); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } /** * @file browser.js * @module browser */ var USER_AGENT = _window2['default'].navigator && _window2['default'].navigator.userAgent || ''; var webkitVersionMap = /AppleWebKit\/([\d.]+)/i.exec(USER_AGENT); var appleWebkitVersion = webkitVersionMap ? parseFloat(webkitVersionMap.pop()) : null; /* * Device is an iPhone * * @type {Boolean} * @constant * @private */ var IS_IPAD = exports.IS_IPAD = /iPad/i.test(USER_AGENT); // The Facebook app's UIWebView identifies as both an iPhone and iPad, so // to identify iPhones, we need to exclude iPads. // http://artsy.github.io/blog/2012/10/18/the-perils-of-ios-user-agent-sniffing/ var IS_IPHONE = exports.IS_IPHONE = /iPhone/i.test(USER_AGENT) && !IS_IPAD; var IS_IPOD = exports.IS_IPOD = /iPod/i.test(USER_AGENT); var IS_IOS = exports.IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD; var IOS_VERSION = exports.IOS_VERSION = function () { var match = USER_AGENT.match(/OS (\d+)_/i); if (match && match[1]) { return match[1]; } return null; }(); var IS_ANDROID = exports.IS_ANDROID = /Android/i.test(USER_AGENT); var ANDROID_VERSION = exports.ANDROID_VERSION = function () { // This matches Android Major.Minor.Patch versions // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned var match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i); if (!match) { return null; } var major = match[1] && parseFloat(match[1]); var minor = match[2] && parseFloat(match[2]); if (major && minor) { return parseFloat(match[1] + '.' + match[2]); } else if (major) { return major; } return null; }(); // Old Android is defined as Version older than 2.3, and requiring a webkit version of the android browser var IS_OLD_ANDROID = exports.IS_OLD_ANDROID = IS_ANDROID && /webkit/i.test(USER_AGENT) && ANDROID_VERSION < 2.3; var IS_NATIVE_ANDROID = exports.IS_NATIVE_ANDROID = IS_ANDROID && ANDROID_VERSION < 5 && appleWebkitVersion < 537; var IS_FIREFOX = exports.IS_FIREFOX = /Firefox/i.test(USER_AGENT); var IS_EDGE = exports.IS_EDGE = /Edge/i.test(USER_AGENT); var IS_CHROME = exports.IS_CHROME = !IS_EDGE && /Chrome/i.test(USER_AGENT); var IS_IE8 = exports.IS_IE8 = /MSIE\s8\.0/.test(USER_AGENT); var IE_VERSION = exports.IE_VERSION = function () { var result = /MSIE\s(\d+)\.\d/.exec(USER_AGENT); var version = result && parseFloat(result[1]); if (!version && /Trident\/7.0/i.test(USER_AGENT) && /rv:11.0/.test(USER_AGENT)) { // IE 11 has a different user agent string than other IE versions version = 11.0; } return version; }(); var IS_SAFARI = exports.IS_SAFARI = /Safari/i.test(USER_AGENT) && !IS_CHROME && !IS_ANDROID && !IS_EDGE; var IS_ANY_SAFARI = exports.IS_ANY_SAFARI = IS_SAFARI || IS_IOS; var TOUCH_ENABLED = exports.TOUCH_ENABLED = Dom.isReal() && ('ontouchstart' in _window2['default'] || _window2['default'].DocumentTouch && _window2['default'].document instanceof _window2['default'].DocumentTouch); var BACKGROUND_SIZE_SUPPORTED = exports.BACKGROUND_SIZE_SUPPORTED = Dom.isReal() && 'backgroundSize' in _window2['default'].document.createElement('video').style; },{"81":81,"95":95}],79:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.bufferedPercent = bufferedPercent; var _timeRanges = _dereq_(90); /** * Compute the percentage of the media that has been buffered. * * @param {TimeRange} buffered * The current `TimeRange` object representing buffered time ranges * * @param {number} duration * Total duration of the media * * @return {number} * Percent buffered of the total duration in decimal form. */ function bufferedPercent(buffered, duration) { var bufferedDuration = 0; var start = void 0; var end = void 0; if (!duration) { return 0; } if (!buffered || !buffered.length) { buffered = (0, _timeRanges.createTimeRange)(0, 0); } for (var i = 0; i < buffered.length; i++) { start = buffered.start(i); end = buffered.end(i); // buffered end can be bigger than duration by a very small fraction if (end > duration) { end = duration; } bufferedDuration += end - start; } return bufferedDuration / duration; } /** * @file buffer.js * @module buffer */ },{"90":90}],80:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports['default'] = computedStyle; var _window = _dereq_(95); var _window2 = _interopRequireDefault(_window); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * A safe getComputedStyle with an IE8 fallback. * * This is needed because in Firefox, if the player is loaded in an iframe with * `display:none`, then `getComputedStyle` returns `null`, so, we do a null-check to * make sure that the player doesn't break in these cases. * * @param {Element} el * The element you want the computed style of * * @param {string} prop * The property name you want * * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397 */ function computedStyle(el, prop) { if (!el || !prop) { return ''; } if (typeof _window2['default'].getComputedStyle === 'function') { var cs = _window2['default'].getComputedStyle(el); return cs ? cs[prop] : ''; } return el.currentStyle[prop] || ''; } /** * @file computed-style.js * @module computed-style */ },{"95":95}],81:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.$$ = exports.$ = undefined; var _templateObject = _taggedTemplateLiteralLoose(['Setting attributes in the second argument of createEl()\n has been deprecated. Use the third argument instead.\n createEl(type, properties, attributes). Attempting to set ', ' to ', '.'], ['Setting attributes in the second argument of createEl()\n has been deprecated. Use the third argument instead.\n createEl(type, properties, attributes). Attempting to set ', ' to ', '.']); exports.isReal = isReal; exports.isEl = isEl; exports.getEl = getEl; exports.createEl = createEl; exports.textContent = textContent; exports.insertElFirst = insertElFirst; exports.getElData = getElData; exports.hasElData = hasElData; exports.removeElData = removeElData; exports.hasElClass = hasElClass; exports.addElClass = addElClass; exports.removeElClass = removeElClass; exports.toggleElClass = toggleElClass; exports.setElAttributes = setElAttributes; exports.getElAttributes = getElAttributes; exports.getAttribute = getAttribute; exports.setAttribute = setAttribute; exports.removeAttribute = removeAttribute; exports.blockTextSelection = blockTextSelection; exports.unblockTextSelection = unblockTextSelection; exports.findElPosition = findElPosition; exports.getPointerPosition = getPointerPosition; exports.isTextNode = isTextNode; exports.emptyEl = emptyEl; exports.normalizeContent = normalizeContent; exports.appendContent = appendContent; exports.insertContent = insertContent; var _document = _dereq_(94); var _document2 = _interopRequireDefault(_document); var _window = _dereq_(95); var _window2 = _interopRequireDefault(_window); var _guid = _dereq_(85); var Guid = _interopRequireWildcard(_guid); var _log = _dereq_(86); var _log2 = _interopRequireDefault(_log); var _tsml = _dereq_(98); var _tsml2 = _interopRequireDefault(_tsml); var _obj = _dereq_(88); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _taggedTemplateLiteralLoose(strings, raw) { strings.raw = raw; return strings; } /** * @file dom.js * @module dom */ /** * Detect if a value is a string with any non-whitespace characters. * * @param {string} str * The string to check * * @return {boolean} * - True if the string is non-blank * - False otherwise * */ function isNonBlankString(str) { return typeof str === 'string' && /\S/.test(str); } /** * Throws an error if the passed string has whitespace. This is used by * class methods to be relatively consistent with the classList API. * * @param {string} str * The string to check for whitespace. * * @throws {Error} * Throws an error if there is whitespace in the string. * */ function throwIfWhitespace(str) { if (/\s/.test(str)) { throw new Error('class has illegal whitespace characters'); } } /** * Produce a regular expression for matching a className within an elements className. * * @param {string} className * The className to generate the RegExp for. * * @return {RegExp} * The RegExp that will check for a specific `className` in an elements * className. */ function classRegExp(className) { return new RegExp('(^|\\s)' + className + '($|\\s)'); } /** * Whether the current DOM interface appears to be real. * * @return {Boolean} */ function isReal() { return ( // Both document and window will never be undefined thanks to `global`. _document2['default'] === _window2['default'].document && // In IE < 9, DOM methods return "object" as their type, so all we can // confidently check is that it exists. typeof _document2['default'].createElement !== 'undefined' ); } /** * Determines, via duck typing, whether or not a value is a DOM element. * * @param {Mixed} value * The thing to check * * @return {boolean} * - True if it is a DOM element * - False otherwise */ function isEl(value) { return (0, _obj.isObject)(value) && value.nodeType === 1; } /** * Creates functions to query the DOM using a given method. * * @param {string} method * The method to create the query with. * * @return {Function} * The query method */ function createQuerier(method) { return function (selector, context) { if (!isNonBlankString(selector)) { return _document2['default'][method](null); } if (isNonBlankString(context)) { context = _document2['default'].querySelector(context); } var ctx = isEl(context) ? context : _document2['default']; return ctx[method] && ctx[method](selector); }; } /** * Shorthand for document.getElementById() * Also allows for CSS (jQuery) ID syntax. But nothing other than IDs. * * @param {string} id * The id of the element to get * * @return {Element|null} * Element with supplied ID or null if there wasn't one. */ function getEl(id) { if (id.indexOf('#') === 0) { id = id.slice(1); } return _document2['default'].getElementById(id); } /** * Creates an element and applies properties. * * @param {string} [tagName='div'] * Name of tag to be created. * * @param {Object} [properties={}] * Element properties to be applied. * * @param {Object} [attributes={}] * Element attributes to be applied. * * @param {String|Element|TextNode|Array|Function} [content] * Contents for the element (see: {@link dom:normalizeContent}) * * @return {Element} * The element that was created. */ function createEl() { var tagName = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'div'; var properties = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var attributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var content = arguments[3]; var el = _document2['default'].createElement(tagName); Object.getOwnPropertyNames(properties).forEach(function (propName) { var val = properties[propName]; // See #2176 // We originally were accepting both properties and attributes in the // same object, but that doesn't work so well. if (propName.indexOf('aria-') !== -1 || propName === 'role' || propName === 'type') { _log2['default'].warn((0, _tsml2['default'])(_templateObject, propName, val)); el.setAttribute(propName, val); // Handle textContent since it's not supported everywhere and we have a // method for it. } else if (propName === 'textContent') { textContent(el, val); } else { el[propName] = val; } }); Object.getOwnPropertyNames(attributes).forEach(function (attrName) { el.setAttribute(attrName, attributes[attrName]); }); if (content) { appendContent(el, content); } return el; } /** * Injects text into an element, replacing any existing contents entirely. * * @param {Element} el * The element to add text content into * * @param {string} text * The text content to add. * * @return {Element} * The element with added text content. */ function textContent(el, text) { if (typeof el.textContent === 'undefined') { el.innerText = text; } else { el.textContent = text; } return el; } /** * Insert an element as the first child node of another * * @param {Element} child * Element to insert * * @param {Element} parent * Element to insert child into * */ function insertElFirst(child, parent) { if (parent.firstChild) { parent.insertBefore(child, parent.firstChild); } else { parent.appendChild(child); } } /** * Element Data Store. Allows for binding data to an element without putting it directly on the element. * Ex. Event listeners are stored here. * (also from jsninja.com, slightly modified and updated for closure compiler) * * @type {Object} * @private */ var elData = {}; /* * Unique attribute name to store an element's guid in * * @type {string} * @constant * @private */ var elIdAttr = 'vdata' + new Date().getTime(); /** * Returns the cache object where data for an element is stored * * @param {Element} el * Element to store data for. * * @return {Object} * The cache object for that el that was passed in. */ function getElData(el) { var id = el[elIdAttr]; if (!id) { id = el[elIdAttr] = Guid.newGUID(); } if (!elData[id]) { elData[id] = {}; } return elData[id]; } /** * Returns whether or not an element has cached data * * @param {Element} el * Check if this element has cached data. * * @return {boolean} * - True if the DOM element has cached data. * - False otherwise. */ function hasElData(el) { var id = el[elIdAttr]; if (!id) { return false; } return !!Object.getOwnPropertyNames(elData[id]).length; } /** * Delete data for the element from the cache and the guid attr from getElementById * * @param {Element} el * Remove cached data for this element. */ function removeElData(el) { var id = el[elIdAttr]; if (!id) { return; } // Remove all stored data delete elData[id]; // Remove the elIdAttr property from the DOM node try { delete el[elIdAttr]; } catch (e) { if (el.removeAttribute) { el.removeAttribute(elIdAttr); } else { // IE doesn't appear to support removeAttribute on the document element el[elIdAttr] = null; } } } /** * Check if an element has a CSS class * * @param {Element} element * Element to check * * @param {string} classToCheck * Class name to check for * * @return {boolean} * - True if the element had the class * - False otherwise. * * @throws {Error} * Throws an error if `classToCheck` has white space. */ function hasElClass(element, classToCheck) { throwIfWhitespace(classToCheck); if (element.classList) { return element.classList.contains(classToCheck); } return classRegExp(classToCheck).test(element.className); } /** * Add a CSS class name to an element * * @param {Element} element * Element to add class name to. * * @param {string} classToAdd * Class name to add. * * @return {Element} * The dom element with the added class name. */ function addElClass(element, classToAdd) { if (element.classList) { element.classList.add(classToAdd); // Don't need to `throwIfWhitespace` here because `hasElClass` will do it // in the case of classList not being supported. } else if (!hasElClass(element, classToAdd)) { element.className = (element.className + ' ' + classToAdd).trim(); } return element; } /** * Remove a CSS class name from an element * * @param {Element} element * Element to remove a class name from. * * @param {string} classToRemove * Class name to remove * * @return {Element} * The dom element with class name removed. */ function removeElClass(element, classToRemove) { if (element.classList) { element.classList.remove(classToRemove); } else { throwIfWhitespace(classToRemove); element.className = element.className.split(/\s+/).filter(function (c) { return c !== classToRemove; }).join(' '); } return element; } /** * The callback definition for toggleElClass. * * @callback Dom~PredicateCallback * @param {Element} element * The DOM element of the Component. * * @param {string} classToToggle * The `className` that wants to be toggled * * @return {boolean|undefined} * - If true the `classToToggle` will get added to `element`. * - If false the `classToToggle` will get removed from `element`. * - If undefined this callback will be ignored */ /** * Adds or removes a CSS class name on an element depending on an optional * condition or the presence/absence of the class name. * * @param {Element} element * The element to toggle a class name on. * * @param {string} classToToggle * The class that should be toggled * * @param {boolean|PredicateCallback} [predicate] * See the return value for {@link Dom~PredicateCallback} * * @return {Element} * The element with a class that has been toggled. */ function toggleElClass(element, classToToggle, predicate) { // This CANNOT use `classList` internally because IE does not support the // second parameter to the `classList.toggle()` method! Which is fine because // `classList` will be used by the add/remove functions. var has = hasElClass(element, classToToggle); if (typeof predicate === 'function') { predicate = predicate(element, classToToggle); } if (typeof predicate !== 'boolean') { predicate = !has; } // If the necessary class operation matches the current state of the // element, no action is required. if (predicate === has) { return; } if (predicate) { addElClass(element, classToToggle); } else { removeElClass(element, classToToggle); } return element; } /** * Apply attributes to an HTML element. * * @param {Element} el * Element to add attributes to. * * @param {Object} [attributes] * Attributes to be applied. */ function setElAttributes(el, attributes) { Object.getOwnPropertyNames(attributes).forEach(function (attrName) { var attrValue = attributes[attrName]; if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) { el.removeAttribute(attrName); } else { el.setAttribute(attrName, attrValue === true ? '' : attrValue); } }); } /** * Get an element's attribute values, as defined on the HTML tag * Attributes are not the same as properties. They're defined on the tag * or with setAttribute (which shouldn't be used with HTML) * This will return true or false for boolean attributes. * * @param {Element} tag * Element from which to get tag attributes. * * @return {Object} * All attributes of the element. */ function getElAttributes(tag) { var obj = {}; // known boolean attributes // we can check for matching boolean properties, but older browsers // won't know about HTML5 boolean attributes that we still read from var knownBooleans = ',' + 'autoplay,controls,loop,muted,default' + ','; if (tag && tag.attributes && tag.attributes.length > 0) { var attrs = tag.attributes; for (var i = attrs.length - 1; i >= 0; i--) { var attrName = attrs[i].name; var attrVal = attrs[i].value; // check for known booleans // the matching element property will return a value for typeof if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(',' + attrName + ',') !== -1) { // the value of an included boolean attribute is typically an empty // string ('') which would equal false if we just check for a false value. // we also don't want support bad code like autoplay='false' attrVal = attrVal !== null ? true : false; } obj[attrName] = attrVal; } } return obj; } /** * Get the value of an element's attribute * * @param {Element} el * A DOM element * * @param {string} attribute * Attribute to get the value of * * @return {string} * value of the attribute */ function getAttribute(el, attribute) { return el.getAttribute(attribute); } /** * Set the value of an element's attribute * * @param {Element} el * A DOM element * * @param {string} attribute * Attribute to set * * @param {string} value * Value to set the attribute to */ function setAttribute(el, attribute, value) { el.setAttribute(attribute, value); } /** * Remove an element's attribute * * @param {Element} el * A DOM element * * @param {string} attribute * Attribute to remove */ function removeAttribute(el, attribute) { el.removeAttribute(attribute); } /** * Attempt to block the ability to select text while dragging controls */ function blockTextSelection() { _document2['default'].body.focus(); _document2['default'].onselectstart = function () { return false; }; } /** * Turn off text selection blocking */ function unblockTextSelection() { _document2['default'].onselectstart = function () { return true; }; } /** * The postion of a DOM element on the page. * * @typedef {Object} Dom~Position * * @property {number} left * Pixels to the left * * @property {number} top * Pixels on top */ /** * Offset Left. * getBoundingClientRect technique from * John Resig * * @see http://ejohn.org/blog/getboundingclientrect-is-awesome/ * * @param {Element} el * Element from which to get offset * * @return {Dom~Position} * The position of the element that was passed in. */ function findElPosition(el) { var box = void 0; if (el.getBoundingClientRect && el.parentNode) { box = el.getBoundingClientRect(); } if (!box) { return { left: 0, top: 0 }; } var docEl = _document2['default'].documentElement; var body = _document2['default'].body; var clientLeft = docEl.clientLeft || body.clientLeft || 0; var scrollLeft = _window2['default'].pageXOffset || body.scrollLeft; var left = box.left + scrollLeft - clientLeft; var clientTop = docEl.clientTop || body.clientTop || 0; var scrollTop = _window2['default'].pageYOffset || body.scrollTop; var top = box.top + scrollTop - clientTop; // Android sometimes returns slightly off decimal values, so need to round return { left: Math.round(left), top: Math.round(top) }; } /** * x and y coordinates for a dom element or mouse pointer * * @typedef {Object} Dom~Coordinates * * @property {number} x * x coordinate in pixels * * @property {number} y * y coordinate in pixels */ /** * Get pointer position in element * Returns an object with x and y coordinates. * The base on the coordinates are the bottom left of the element. * * @param {Element} el * Element on which to get the pointer position on * * @param {EventTarget~Event} event * Event object * * @return {Dom~Coordinates} * A Coordinates object corresponding to the mouse position. * */ function getPointerPosition(el, event) { var position = {}; var box = findElPosition(el); var boxW = el.offsetWidth; var boxH = el.offsetHeight; var boxY = box.top; var boxX = box.left; var pageY = event.pageY; var pageX = event.pageX; if (event.changedTouches) { pageX = event.changedTouches[0].pageX; pageY = event.changedTouches[0].pageY; } position.y = Math.max(0, Math.min(1, (boxY - pageY + boxH) / boxH)); position.x = Math.max(0, Math.min(1, (pageX - boxX) / boxW)); return position; } /** * Determines, via duck typing, whether or not a value is a text node. * * @param {Mixed} value * Check if this value is a text node. * * @return {boolean} * - True if it is a text node * - False otherwise */ function isTextNode(value) { return (0, _obj.isObject)(value) && value.nodeType === 3; } /** * Empties the contents of an element. * * @param {Element} el * The element to empty children from * * @return {Element} * The element with no children */ function emptyEl(el) { while (el.firstChild) { el.removeChild(el.firstChild); } return el; } /** * Normalizes content for eventual insertion into the DOM. * * This allows a wide range of content definition methods, but protects * from falling into the trap of simply writing to `innerHTML`, which is * an XSS concern. * * The content for an element can be passed in multiple types and * combinations, whose behavior is as follows: * * @param {String|Element|TextNode|Array|Function} content * - String: Normalized into a text node. * - Element/TextNode: Passed through. * - Array: A one-dimensional array of strings, elements, nodes, or functions * (which return single strings, elements, or nodes). * - Function: If the sole argument, is expected to produce a string, element, * node, or array as defined above. * * @return {Array} * All of the content that was passed in normalized. */ function normalizeContent(content) { // First, invoke content if it is a function. If it produces an array, // that needs to happen before normalization. if (typeof content === 'function') { content = content(); } // Next up, normalize to an array, so one or many items can be normalized, // filtered, and returned. return (Array.isArray(content) ? content : [content]).map(function (value) { // First, invoke value if it is a function to produce a new value, // which will be subsequently normalized to a Node of some kind. if (typeof value === 'function') { value = value(); } if (isEl(value) || isTextNode(value)) { return value; } if (typeof value === 'string' && /\S/.test(value)) { return _document2['default'].createTextNode(value); } }).filter(function (value) { return value; }); } /** * Normalizes and appends content to an element. * * @param {Element} el * Element to append normalized content to. * * * @param {String|Element|TextNode|Array|Function} content * See the `content` argument of {@link dom:normalizeContent} * * @return {Element} * The element with appended normalized content. */ function appendContent(el, content) { normalizeContent(content).forEach(function (node) { return el.appendChild(node); }); return el; } /** * Normalizes and inserts content into an element; this is identical to * `appendContent()`, except it empties the element first. * * @param {Element} el * Element to insert normalized content into. * * @param {String|Element|TextNode|Array|Function} content * See the `content` argument of {@link dom:normalizeContent} * * @return {Element} * The element with inserted normalized content. * */ function insertContent(el, content) { return appendContent(emptyEl(el), content); } /** * Finds a single DOM element matching `selector` within the optional * `context` of another DOM element (defaulting to `document`). * * @param {string} selector * A valid CSS selector, which will be passed to `querySelector`. * * @param {Element|String} [context=document] * A DOM element within which to query. Can also be a selector * string in which case the first matching element will be used * as context. If missing (or no element matches selector), falls * back to `document`. * * @return {Element|null} * The element that was found or null. */ var $ = exports.$ = createQuerier('querySelector'); /** * Finds a all DOM elements matching `selector` within the optional * `context` of another DOM element (defaulting to `document`). * * @param {string} selector * A valid CSS selector, which will be passed to `querySelectorAll`. * * @param {Element|String} [context=document] * A DOM element within which to query. Can also be a selector * string in which case the first matching element will be used * as context. If missing (or no element matches selector), falls * back to `document`. * * @return {NodeList} * A element list of elements that were found. Will be empty if none were found. * */ var $$ = exports.$$ = createQuerier('querySelectorAll'); },{"85":85,"86":86,"88":88,"94":94,"95":95,"98":98}],82:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.fixEvent = fixEvent; exports.on = on; exports.off = off; exports.trigger = trigger; exports.one = one; var _dom = _dereq_(81); var Dom = _interopRequireWildcard(_dom); var _guid = _dereq_(85); var Guid = _interopRequireWildcard(_guid); var _log = _dereq_(86); var _log2 = _interopRequireDefault(_log); var _window = _dereq_(95); var _window2 = _interopRequireDefault(_window); var _document = _dereq_(94); var _document2 = _interopRequireDefault(_document); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } /** * Clean up the listener cache and dispatchers * * @param {Element|Object} elem * Element to clean up * * @param {string} type * Type of event to clean up */ function _cleanUpEvents(elem, type) { var data = Dom.getElData(elem); // Remove the events of a particular type if there are none left if (data.handlers[type].length === 0) { delete data.handlers[type]; // data.handlers[type] = null; // Setting to null was causing an error with data.handlers // Remove the meta-handler from the element if (elem.removeEventListener) { elem.removeEventListener(type, data.dispatcher, false); } else if (elem.detachEvent) { elem.detachEvent('on' + type, data.dispatcher); } } // Remove the events object if there are no types left if (Object.getOwnPropertyNames(data.handlers).length <= 0) { delete data.handlers; delete data.dispatcher; delete data.disabled; } // Finally remove the element data if there is no data left if (Object.getOwnPropertyNames(data).length === 0) { Dom.removeElData(elem); } } /** * Loops through an array of event types and calls the requested method for each type. * * @param {Function} fn * The event method we want to use. * * @param {Element|Object} elem * Element or object to bind listeners to * * @param {string} type * Type of event to bind to. * * @param {EventTarget~EventListener} callback * Event listener. */ /** * @file events.js. An Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/) * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible) * This should work very similarly to jQuery's events, however it's based off the book version which isn't as * robust as jquery's, so there's probably some differences. * * @module events */ function _handleMultipleEvents(fn, elem, types, callback) { types.forEach(function (type) { // Call the event method for each one of the types fn(elem, type, callback); }); } /** * Fix a native event to have standard property values * * @param {Object} event * Event object to fix. * * @return {Object} * Fixed event object. */ function fixEvent(event) { function returnTrue() { return true; } function returnFalse() { return false; } // Test if fixing up is needed // Used to check if !event.stopPropagation instead of isPropagationStopped // But native events return true for stopPropagation, but don't have // other expected methods like isPropagationStopped. Seems to be a problem // with the Javascript Ninja code. So we're just overriding all events now. if (!event || !event.isPropagationStopped) { var old = event || _window2['default'].event; event = {}; // Clone the old object so that we can modify the values event = {}; // IE8 Doesn't like when you mess with native event properties // Firefox returns false for event.hasOwnProperty('type') and other props // which makes copying more difficult. // TODO: Probably best to create a whitelist of event props for (var key in old) { // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y // Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation // and webkitMovementX/Y if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation' && key !== 'webkitMovementX' && key !== 'webkitMovementY') { // Chrome 32+ warns if you try to copy deprecated returnValue, but // we still want to if preventDefault isn't supported (IE8). if (!(key === 'returnValue' && old.preventDefault)) { event[key] = old[key]; } } } // The event occurred on this element if (!event.target) { event.target = event.srcElement || _document2['default']; } // Handle which other element the event is related to if (!event.relatedTarget) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Stop the default browser action event.preventDefault = function () { if (old.preventDefault) { old.preventDefault(); } event.returnValue = false; old.returnValue = false; event.defaultPrevented = true; }; event.defaultPrevented = false; // Stop the event from bubbling event.stopPropagation = function () { if (old.stopPropagation) { old.stopPropagation(); } event.cancelBubble = true; old.cancelBubble = true; event.isPropagationStopped = returnTrue; }; event.isPropagationStopped = returnFalse; // Stop the event from bubbling and executing other handlers event.stopImmediatePropagation = function () { if (old.stopImmediatePropagation) { old.stopImmediatePropagation(); } event.isImmediatePropagationStopped = returnTrue; event.stopPropagation(); }; event.isImmediatePropagationStopped = returnFalse; // Handle mouse position if (event.clientX !== null && event.clientX !== undefined) { var doc = _document2['default'].documentElement; var body = _document2['default'].body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Handle key presses event.which = event.charCode || event.keyCode; // Fix button for mouse clicks: // 0 == left; 1 == middle; 2 == right if (event.button !== null && event.button !== undefined) { // The following is disabled because it does not pass videojs-standard // and... yikes. /* eslint-disable */ event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0; /* eslint-enable */ } } // Returns fixed-up instance return event; } /** * Add an event listener to element * It stores the handler function in a separate cache object * and adds a generic handler to the element's event, * along with a unique id (guid) to the element. * * @param {Element|Object} elem * Element or object to bind listeners to * * @param {string|string[]} type * Type of event to bind to. * * @param {EventTarget~EventListener} fn * Event listener. */ function on(elem, type, fn) { if (Array.isArray(type)) { return _handleMultipleEvents(on, elem, type, fn); } var data = Dom.getElData(elem); // We need a place to store all our handler data if (!data.handlers) { data.handlers = {}; } if (!data.handlers[type]) { data.handlers[type] = []; } if (!fn.guid) { fn.guid = Guid.newGUID(); } data.handlers[type].push(fn); if (!data.dispatcher) { data.disabled = false; data.dispatcher = function (event, hash) { if (data.disabled) { return; } event = fixEvent(event); var handlers = data.handlers[event.type]; if (handlers) { // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off. var handlersCopy = handlers.slice(0); for (var m = 0, n = handlersCopy.length; m < n; m++) { if (event.isImmediatePropagationStopped()) { break; } else { try { handlersCopy[m].call(elem, event, hash); } catch (e) { _log2['default'].error(e); } } } } }; } if (data.handlers[type].length === 1) { if (elem.addEventListener) { elem.addEventListener(type, data.dispatcher, false); } else if (elem.attachEvent) { elem.attachEvent('on' + type, data.dispatcher); } } } /** * Removes event listeners from an element * * @param {Element|Object} elem * Object to remove listeners from. * * @param {string|string[]} [type] * Type of listener to remove. Don't include to remove all events from element. * * @param {EventTarget~EventListener} [fn] * Specific listener to remove. Don't include to remove listeners for an event * type. */ function off(elem, type, fn) { // Don't want to add a cache object through getElData if not needed if (!Dom.hasElData(elem)) { return; } var data = Dom.getElData(elem); // If no events exist, nothing to unbind if (!data.handlers) { return; } if (Array.isArray(type)) { return _handleMultipleEvents(off, elem, type, fn); } // Utility function var removeType = function removeType(t) { data.handlers[t] = []; _cleanUpEvents(elem, t); }; // Are we removing all bound events? if (!type) { for (var t in data.handlers) { removeType(t); } return; } var handlers = data.handlers[type]; // If no handlers exist, nothing to unbind if (!handlers) { return; } // If no listener was provided, remove all listeners for type if (!fn) { removeType(type); return; } // We're only removing a single handler if (fn.guid) { for (var n = 0; n < handlers.length; n++) { if (handlers[n].guid === fn.guid) { handlers.splice(n--, 1); } } } _cleanUpEvents(elem, type); } /** * Trigger an event for an element * * @param {Element|Object} elem * Element to trigger an event on * * @param {EventTarget~Event|string} event * A string (the type) or an event object with a type attribute * * @param {Object} [hash] * data hash to pass along with the event * * @return {boolean|undefined} * - Returns the opposite of `defaultPrevented` if default was prevented * - Otherwise returns undefined */ function trigger(elem, event, hash) { // Fetches element data and a reference to the parent (for bubbling). // Don't want to add a data object to cache for every parent, // so checking hasElData first. var elemData = Dom.hasElData(elem) ? Dom.getElData(elem) : {}; var parent = elem.parentNode || elem.ownerDocument; // type = event.type || event, // handler; // If an event name was passed as a string, creates an event out of it if (typeof event === 'string') { event = { type: event, target: elem }; } // Normalizes the event properties. event = fixEvent(event); // If the passed element has a dispatcher, executes the established handlers. if (elemData.dispatcher) { elemData.dispatcher.call(elem, event, hash); } // Unless explicitly stopped or the event does not bubble (e.g. media events) // recursively calls this function to bubble the event up the DOM. if (parent && !event.isPropagationStopped() && event.bubbles === true) { trigger.call(null, parent, event, hash); // If at the top of the DOM, triggers the default action unless disabled. } else if (!parent && !event.defaultPrevented) { var targetData = Dom.getElData(event.target); // Checks if the target has a default action for this event. if (event.target[event.type]) { // Temporarily disables event dispatching on the target as we have already executed the handler. targetData.disabled = true; // Executes the default action. if (typeof event.target[event.type] === 'function') { event.target[event.type](); } // Re-enables event dispatching. targetData.disabled = false; } } // Inform the triggerer if the default was prevented by returning false return !event.defaultPrevented; } /** * Trigger a listener only once for an event * * @param {Element|Object} elem * Element or object to bind to. * * @param {string|string[]} type * Name/type of event * * @param {Event~EventListener} fn * Event Listener function */ function one(elem, type, fn) { if (Array.isArray(type)) { return _handleMultipleEvents(one, elem, type, fn); } var func = function func() { off(elem, type, func); fn.apply(this, arguments); }; // copy the guid to the new function so it can removed using the original function's ID func.guid = fn.guid = fn.guid || Guid.newGUID(); on(elem, type, func); } },{"81":81,"85":85,"86":86,"94":94,"95":95}],83:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.throttle = exports.bind = undefined; var _guid = _dereq_(85); /** * Bind (a.k.a proxy or Context). A simple method for changing the context of a function * It also stores a unique id on the function so it can be easily removed from events. * * @param {Mixed} context * The object to bind as scope. * * @param {Function} fn * The function to be bound to a scope. * * @param {number} [uid] * An optional unique ID for the function to be set * * @return {Function} * The new function that will be bound into the context given */ var bind = exports.bind = function bind(context, fn, uid) { // Make sure the function has a unique ID if (!fn.guid) { fn.guid = (0, _guid.newGUID)(); } // Create the new function that changes the context var bound = function bound() { return fn.apply(context, arguments); }; // Allow for the ability to individualize this function // Needed in the case where multiple objects might share the same prototype // IF both items add an event listener with the same function, then you try to remove just one // it will remove both because they both have the same guid. // when using this, you need to use the bind method when you remove the listener as well. // currently used in text tracks bound.guid = uid ? uid + '_' + fn.guid : fn.guid; return bound; }; /** * Wraps the given function, `fn`, with a new function that only invokes `fn` * at most once per every `wait` milliseconds. * * @param {Function} fn * The function to be throttled. * * @param {Number} wait * The number of milliseconds by which to throttle. * * @return {Function} */ /** * @file fn.js * @module fn */ var throttle = exports.throttle = function throttle(fn, wait) { var last = Date.now(); var throttled = function throttled() { var now = Date.now(); if (now - last >= wait) { fn.apply(undefined, arguments); last = now; } }; return throttled; }; },{"85":85}],84:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; /** * @file format-time.js * @module Format-time */ /** * Format seconds as a time string, H:MM:SS or M:SS. Supplying a guide (in seconds) * will force a number of leading zeros to cover the length of the guide. * * @param {number} seconds * Number of seconds to be turned into a string * * @param {number} guide * Number (in seconds) to model the string after * * @return {string} * Time formatted as H:MM:SS or M:SS */ function formatTime(seconds) { var guide = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : seconds; seconds = seconds < 0 ? 0 : seconds; var s = Math.floor(seconds % 60); var m = Math.floor(seconds / 60 % 60); var h = Math.floor(seconds / 3600); var gm = Math.floor(guide / 60 % 60); var gh = Math.floor(guide / 3600); // handle invalid times if (isNaN(seconds) || seconds === Infinity) { // '-' is false for all relational operators (e.g. <, >=) so this setting // will add the minimum number of fields specified by the guide h = m = s = '-'; } // Check if we need to show hours h = h > 0 || gh > 0 ? h + ':' : ''; // If hours are showing, we may need to add a leading zero. // Always show at least one digit of minutes. m = ((h || gm >= 10) && m < 10 ? '0' + m : m) + ':'; // Check if leading zero is need for seconds s = s < 10 ? '0' + s : s; return h + m + s; } exports['default'] = formatTime; },{}],85:[function(_dereq_,module,exports){ "use strict"; exports.__esModule = true; exports.newGUID = newGUID; /** * @file guid.js * @module guid */ /** * Unique ID for an element or function * @type {Number} */ var _guid = 1; /** * Get a unique auto-incrementing ID by number that has not been returned before. * * @return {number} * A new unique ID. */ function newGUID() { return _guid++; } },{}],86:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.logByType = undefined; var _window = _dereq_(95); var _window2 = _interopRequireDefault(_window); var _browser = _dereq_(78); var _obj = _dereq_(88); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var log = void 0; /** * Log messages to the console and history based on the type of message * * @param {string} type * The name of the console method to use. * * @param {Array} args * The arguments to be passed to the matching console method. * * @param {boolean} [stringify] * By default, only old IEs should get console argument stringification, * but this is exposed as a parameter to facilitate testing. */ /** * @file log.js * @module log */ var logByType = exports.logByType = function logByType(type, args) { var stringify = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : !!_browser.IE_VERSION && _browser.IE_VERSION < 11; if (type !== 'log') { // add the type to the front of the message when it's not "log" args.unshift(type.toUpperCase() + ':'); } // add to history log.history.push(args); // add console prefix after adding to history args.unshift('VIDEOJS:'); // If there's no console then don't try to output messages, but they will // still be stored in `log.history`. // // Was setting these once outside of this function, but containing them // in the function makes it easier to test cases where console doesn't exist // when the module is executed. var fn = _window2['default'].console && _window2['default'].console[type]; // Bail out if there's no console. if (!fn) { return; } // IEs previous to 11 log objects uselessly as "[object Object]"; so, JSONify // objects and arrays for those less-capable browsers. if (stringify) { args = args.map(function (a) { if ((0, _obj.isObject)(a) || Array.isArray(a)) { try { return JSON.stringify(a); } catch (x) { return String(a); } } // Cast to string before joining, so we get null and undefined explicitly // included in output (as we would in a modern console). return String(a); }).join(' '); } // Old IE versions do not allow .apply() for console methods (they are // reported as objects rather than functions). if (!fn.apply) { fn(args); } else { fn[Array.isArray(args) ? 'apply' : 'call'](_window2['default'].console, args); } }; /** * Log plain debug messages * * @param {Mixed[]} args * One or more messages or objects that should be logged. */ log = function log() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } logByType('log', args); }; /** * Keep a history of log messages * * @type {Array} */ log.history = []; /** * Log error messages * * @param {Mixed[]} args * One or more messages or objects that should be logged as an error */ log.error = function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return logByType('error', args); }; /** * Log warning messages * * @param {Mixed[]} args * One or more messages or objects that should be logged as a warning. */ log.warn = function () { for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return logByType('warn', args); }; exports['default'] = log; },{"78":78,"88":88,"95":95}],87:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports['default'] = mergeOptions; var _obj = _dereq_(88); /** * Deep-merge one or more options objects, recursively merging **only** plain * object properties. * * @param {Object[]} sources * One or more objects to merge into a new object. * * @returns {Object} * A new object that is the merged result of all sources. */ function mergeOptions() { var result = {}; for (var _len = arguments.length, sources = Array(_len), _key = 0; _key < _len; _key++) { sources[_key] = arguments[_key]; } sources.forEach(function (source) { if (!source) { return; } (0, _obj.each)(source, function (value, key) { if (!(0, _obj.isPlain)(value)) { result[key] = value; return; } if (!(0, _obj.isPlain)(result[key])) { result[key] = {}; } result[key] = mergeOptions(result[key], value); }); }); return result; } /** * @file merge-options.js * @module merge-options */ },{"88":88}],88:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; exports.each = each; exports.reduce = reduce; exports.assign = assign; exports.isObject = isObject; exports.isPlain = isPlain; /** * @file obj.js * @module obj */ /** * @callback obj:EachCallback * * @param {Mixed} value * The current key for the object that is being iterated over. * * @param {string} key * The current key-value for object that is being iterated over */ /** * @callback obj:ReduceCallback * * @param {Mixed} accum * The value that is accumulating over the reduce loop. * * @param {Mixed} value * The current key for the object that is being iterated over. * * @param {string} key * The current key-value for object that is being iterated over * * @return {Mixed} * The new accumulated value. */ var toString = Object.prototype.toString; /** * Get the keys of an Object * * @param {Object} * The Object to get the keys from * * @return {string[]} * An array of the keys from the object. Returns an empty array if the * object passed in was invalid or had no keys. * * @private */ var keys = function keys(object) { return isObject(object) ? Object.keys(object) : []; }; /** * Array-like iteration for objects. * * @param {Object} object * The object to iterate over * * @param {obj:EachCallback} fn * The callback function which is called for each key in the object. */ function each(object, fn) { keys(object).forEach(function (key) { return fn(object[key], key); }); } /** * Array-like reduce for objects. * * @param {Object} object * The Object that you want to reduce. * * @param {Function} fn * A callback function which is called for each key in the object. It * receives the accumulated value and the per-iteration value and key * as arguments. * * @param {Mixed} [initial = 0] * Starting value * * @return {Mixed} * The final accumulated value. */ function reduce(object, fn) { var initial = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; return keys(object).reduce(function (accum, key) { return fn(accum, object[key], key); }, initial); } /** * Object.assign-style object shallow merge/extend. * * @param {Object} target * @param {Object} ...sources * @return {Object} */ function assign(target) { for (var _len = arguments.length, sources = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { sources[_key - 1] = arguments[_key]; } if (Object.assign) { return Object.assign.apply(Object, [target].concat(sources)); } sources.forEach(function (source) { if (!source) { return; } each(source, function (value, key) { target[key] = value; }); }); return target; } /** * Returns whether a value is an object of any kind - including DOM nodes, * arrays, regular expressions, etc. Not functions, though. * * This avoids the gotcha where using `typeof` on a `null` value * results in `'object'`. * * @param {Object} value * @return {Boolean} */ function isObject(value) { return !!value && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object'; } /** * Returns whether an object appears to be a "plain" object - that is, a * direct instance of `Object`. * * @param {Object} value * @return {Boolean} */ function isPlain(value) { return isObject(value) && toString.call(value) === '[object Object]' && value.constructor === Object; } },{}],89:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.setTextContent = exports.createStyleElement = undefined; var _document = _dereq_(94); var _document2 = _interopRequireDefault(_document); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Create a DOM syle element given a className for it. * * @param {string} className * The className to add to the created style element. * * @return {Element} * The element that was created. */ var createStyleElement = exports.createStyleElement = function createStyleElement(className) { var style = _document2['default'].createElement('style'); style.className = className; return style; }; /** * Add text to a DOM element. * * @param {Element} el * The Element to add text content to. * * @param {string} content * The text to add to the element. */ /** * @file stylesheet.js * @module stylesheet */ var setTextContent = exports.setTextContent = function setTextContent(el, content) { if (el.styleSheet) { el.styleSheet.cssText = content; } else { el.textContent = content; } }; },{"94":94}],90:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.createTimeRange = undefined; exports.createTimeRanges = createTimeRanges; var _log = _dereq_(86); var _log2 = _interopRequireDefault(_log); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Returns the time for the specified index at the start or end * of a TimeRange object. * * @function time-ranges:indexFunction * * @param {number} [index=0] * The range number to return the time for. * * @return {number} * The time that offset at the specified index. * * @depricated index must be set to a value, in the future this will throw an error. */ /** * An object that contains ranges of time for various reasons. * * @typedef {Object} TimeRange * * @property {number} length * The number of time ranges represented by this Object * * @property {time-ranges:indexFunction} start * Returns the time offset at which a specified time range begins. * * @property {time-ranges:indexFunction} end * Returns the time offset at which a specified time range begins. * * @see https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges */ /** * Check if any of the time ranges are over the maximum index. * * @param {string} fnName * The function name to use for logging * * @param {number} index * The index to check * * @param {number} maxIndex * The maximum possible index * * @throws {Error} if the timeRanges provided are over the maxIndex */ function rangeCheck(fnName, index, maxIndex) { if (index < 0 || index > maxIndex) { throw new Error('Failed to execute \'' + fnName + '\' on \'TimeRanges\': The index provided (' + index + ') is greater than or equal to the maximum bound (' + maxIndex + ').'); } } /** * Check if any of the time ranges are over the maximum index. * * @param {string} fnName * The function name to use for logging * * @param {string} valueIndex * The proprety that should be used to get the time. should be 'start' or 'end' * * @param {Array} ranges * An array of time ranges * * @param {Array} [rangeIndex=0] * The index to start the search at * * @return {number} * The time that offset at the specified index. * * * @depricated rangeIndex must be set to a value, in the future this will throw an error. * @throws {Error} if rangeIndex is more than the length of ranges */ /** * @file time-ranges.js * @module time-ranges */ function getRange(fnName, valueIndex, ranges, rangeIndex) { if (rangeIndex === undefined) { _log2['default'].warn('DEPRECATED: Function \'' + fnName + '\' on \'TimeRanges\' called without an index argument.'); rangeIndex = 0; } rangeCheck(fnName, rangeIndex, ranges.length - 1); return ranges[rangeIndex][valueIndex]; } /** * Create a time range object givent ranges of time. * * @param {Array} [ranges] * An array of time ranges. */ function createTimeRangesObj(ranges) { if (ranges === undefined || ranges.length === 0) { return { length: 0, start: function start() { throw new Error('This TimeRanges object is empty'); }, end: function end() { throw new Error('This TimeRanges object is empty'); } }; } return { length: ranges.length, start: getRange.bind(null, 'start', 0, ranges), end: getRange.bind(null, 'end', 1, ranges) }; } /** * Should create a fake `TimeRange` object which mimics an HTML5 time range instance. * * @param {number|Array} start * The start of a single range or an array of ranges * * @param {number} end * The end of a single range. * * @private */ function createTimeRanges(start, end) { if (Array.isArray(start)) { return createTimeRangesObj(start); } else if (start === undefined || end === undefined) { return createTimeRangesObj(); } return createTimeRangesObj([[start, end]]); } exports.createTimeRange = createTimeRanges; },{"86":86}],91:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; /** * @file to-title-case.js * @module to-title-case */ /** * Uppercase the first letter of a string. * * @param {string} string * String to be uppercased * * @return {string} * The string with an uppercased first letter */ function toTitleCase(string) { if (typeof string !== 'string') { return string; } return string.charAt(0).toUpperCase() + string.slice(1); } exports['default'] = toTitleCase; },{}],92:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.isCrossOrigin = exports.getFileExtension = exports.getAbsoluteURL = exports.parseUrl = undefined; var _document = _dereq_(94); var _document2 = _interopRequireDefault(_document); var _window = _dereq_(95); var _window2 = _interopRequireDefault(_window); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * @typedef {Object} url:URLObject * * @property {string} protocol * The protocol of the url that was parsed. * * @property {string} hostname * The hostname of the url that was parsed. * * @property {string} port * The port of the url that was parsed. * * @property {string} pathname * The pathname of the url that was parsed. * * @property {string} search * The search query of the url that was parsed. * * @property {string} hash * The hash of the url that was parsed. * * @property {string} host * The host of the url that was parsed. */ /** * Resolve and parse the elements of a URL. * * @param {String} url * The url to parse * * @return {url:URLObject} * An object of url details */ /** * @file url.js * @module url */ var parseUrl = exports.parseUrl = function parseUrl(url) { var props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host']; // add the url to an anchor and let the browser parse the URL var a = _document2['default'].createElement('a'); a.href = url; // IE8 (and 9?) Fix // ie8 doesn't parse the URL correctly until the anchor is actually // added to the body, and an innerHTML is needed to trigger the parsing var addToBody = a.host === '' && a.protocol !== 'file:'; var div = void 0; if (addToBody) { div = _document2['default'].createElement('div'); div.innerHTML = '<a href="' + url + '"></a>'; a = div.firstChild; // prevent the div from affecting layout div.setAttribute('style', 'display:none; position:absolute;'); _document2['default'].body.appendChild(div); } // Copy the specific URL properties to a new object // This is also needed for IE8 because the anchor loses its // properties when it's removed from the dom var details = {}; for (var i = 0; i < props.length; i++) { details[props[i]] = a[props[i]]; } // IE9 adds the port to the host property unlike everyone else. If // a port identifier is added for standard ports, strip it. if (details.protocol === 'http:') { details.host = details.host.replace(/:80$/, ''); } if (details.protocol === 'https:') { details.host = details.host.replace(/:443$/, ''); } if (addToBody) { _document2['default'].body.removeChild(div); } return details; }; /** * Get absolute version of relative URL. Used to tell flash correct URL. * * * @param {string} url * URL to make absolute * * @return {string} * Absolute URL * * @see http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue */ var getAbsoluteURL = exports.getAbsoluteURL = function getAbsoluteURL(url) { // Check if absolute URL if (!url.match(/^https?:\/\//)) { // Convert to absolute URL. Flash hosted off-site needs an absolute URL. var div = _document2['default'].createElement('div'); div.innerHTML = '<a href="' + url + '">x</a>'; url = div.firstChild.href; } return url; }; /** * Returns the extension of the passed file name. It will return an empty string * if passed an invalid path. * * @param {string} path * The fileName path like '/path/to/file.mp4' * * @returns {string} * The extension in lower case or an empty string if no * extension could be found. */ var getFileExtension = exports.getFileExtension = function getFileExtension(path) { if (typeof path === 'string') { var splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/i; var pathParts = splitPathRe.exec(path); if (pathParts) { return pathParts.pop().toLowerCase(); } } return ''; }; /** * Returns whether the url passed is a cross domain request or not. * * @param {string} url * The url to check. * * @return {boolean} * Whether it is a cross domain request or not. */ var isCrossOrigin = exports.isCrossOrigin = function isCrossOrigin(url) { var winLoc = _window2['default'].location; var urlInfo = parseUrl(url); // IE8 protocol relative urls will return ':' for protocol var srcProtocol = urlInfo.protocol === ':' ? winLoc.protocol : urlInfo.protocol; // Check if url is for another domain/origin // IE8 doesn't know location.origin, so we won't rely on it here var crossOrigin = srcProtocol + urlInfo.host !== winLoc.protocol + winLoc.host; return crossOrigin; }; },{"94":94,"95":95}],93:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /** * @file video.js * @module videojs */ /* global define */ // Include the built-in techs var _window = _dereq_(95); var _window2 = _interopRequireDefault(_window); var _document = _dereq_(94); var _document2 = _interopRequireDefault(_document); var _setup = _dereq_(56); var setup = _interopRequireWildcard(_setup); var _stylesheet = _dereq_(89); var stylesheet = _interopRequireWildcard(_stylesheet); var _component = _dereq_(5); var _component2 = _interopRequireDefault(_component); var _eventTarget = _dereq_(42); var _eventTarget2 = _interopRequireDefault(_eventTarget); var _events = _dereq_(82); var Events = _interopRequireWildcard(_events); var _player = _dereq_(51); var _player2 = _interopRequireDefault(_player); var _plugins = _dereq_(52); var _plugins2 = _interopRequireDefault(_plugins); var _mergeOptions2 = _dereq_(87); var _mergeOptions3 = _interopRequireDefault(_mergeOptions2); var _fn = _dereq_(83); var Fn = _interopRequireWildcard(_fn); var _textTrack = _dereq_(72); var _textTrack2 = _interopRequireDefault(_textTrack); var _audioTrack = _dereq_(64); var _audioTrack2 = _interopRequireDefault(_audioTrack); var _videoTrack = _dereq_(77); var _videoTrack2 = _interopRequireDefault(_videoTrack); var _timeRanges = _dereq_(90); var _formatTime = _dereq_(84); var _formatTime2 = _interopRequireDefault(_formatTime); var _log = _dereq_(86); var _log2 = _interopRequireDefault(_log); var _dom = _dereq_(81); var Dom = _interopRequireWildcard(_dom); var _browser = _dereq_(78); var browser = _interopRequireWildcard(_browser); var _url = _dereq_(92); var Url = _interopRequireWildcard(_url); var _obj = _dereq_(88); var _computedStyle = _dereq_(80); var _computedStyle2 = _interopRequireDefault(_computedStyle); var _extend = _dereq_(43); var _extend2 = _interopRequireDefault(_extend); var _xhr = _dereq_(99); var _xhr2 = _interopRequireDefault(_xhr); var _tech = _dereq_(62); var _tech2 = _interopRequireDefault(_tech); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } // HTML5 Element Shim for IE8 if (typeof HTMLVideoElement === 'undefined' && Dom.isReal()) { _document2['default'].createElement('video'); _document2['default'].createElement('audio'); _document2['default'].createElement('track'); } /** * Doubles as the main function for users to create a player instance and also * the main library object. * The `videojs` function can be used to initialize or retrieve a player. * * @param {string|Element} id * Video element or video element ID * * @param {Object} [options] * Optional options object for config/settings * * @param {Component~ReadyCallback} [ready] * Optional ready callback * * @return {Player} * A player instance * * @mixes videojs */ function videojs(id, options, ready) { var tag = void 0; // Allow for element or ID to be passed in // String ID if (typeof id === 'string') { // Adjust for jQuery ID syntax if (id.indexOf('#') === 0) { id = id.slice(1); } // If a player instance has already been created for this ID return it. if (videojs.getPlayers()[id]) { // If options or ready funtion are passed, warn if (options) { _log2['default'].warn('Player "' + id + '" is already initialised. Options will not be applied.'); } if (ready) { videojs.getPlayers()[id].ready(ready); } return videojs.getPlayers()[id]; } // Otherwise get element for ID tag = Dom.getEl(id); // ID is a media element } else { tag = id; } // Check for a useable element // re: nodeName, could be a box div also if (!tag || !tag.nodeName) { throw new TypeError('The element or ID supplied is not valid. (videojs)'); } // Element may have a player attr referring to an already created player instance. // If so return that otherwise set up a new player below if (tag.player || _player2['default'].players[tag.playerId]) { return tag.player || _player2['default'].players[tag.playerId]; } options = options || {}; videojs.hooks('beforesetup').forEach(function (hookFunction) { var opts = hookFunction(tag, (0, _mergeOptions3['default'])(options)); if (!(0, _obj.isObject)(opts) || Array.isArray(opts)) { _log2['default'].error('please return an object in beforesetup hooks'); return; } options = (0, _mergeOptions3['default'])(options, opts); }); var PlayerComponent = _component2['default'].getComponent('Player'); // If not, set up a new player var player = new PlayerComponent(tag, options, ready); videojs.hooks('setup').forEach(function (hookFunction) { return hookFunction(player); }); return player; } /** * An Object that contains lifecycle hooks as keys which point to an array * of functions that are run when a lifecycle is triggered */ videojs.hooks_ = {}; /** * Get a list of hooks for a specific lifecycle * * @param {string} type * the lifecyle to get hooks from * * @param {Function} [fn] * Optionally add a hook to the lifecycle that your are getting. * * @return {Array} * an array of hooks, or an empty array if there are none. */ videojs.hooks = function (type, fn) { videojs.hooks_[type] = videojs.hooks_[type] || []; if (fn) { videojs.hooks_[type] = videojs.hooks_[type].concat(fn); } return videojs.hooks_[type]; }; /** * Add a function hook to a specific videojs lifecycle. * * @param {string} type * the lifecycle to hook the function to. * * @param {Function|Function[]} * The function or array of functions to attach. */ videojs.hook = function (type, fn) { videojs.hooks(type, fn); }; /** * Remove a hook from a specific videojs lifecycle. * * @param {string} type * the lifecycle that the function hooked to * * @param {Function} fn * The hooked function to remove * * @return {boolean} * The function that was removed or undef */ videojs.removeHook = function (type, fn) { var index = videojs.hooks(type).indexOf(fn); if (index <= -1) { return false; } videojs.hooks_[type] = videojs.hooks_[type].slice(); videojs.hooks_[type].splice(index, 1); return true; }; // Add default styles if (_window2['default'].VIDEOJS_NO_DYNAMIC_STYLE !== true && Dom.isReal()) { var style = Dom.$('.vjs-styles-defaults'); if (!style) { style = stylesheet.createStyleElement('vjs-styles-defaults'); var head = Dom.$('head'); if (head) { head.insertBefore(style, head.firstChild); } stylesheet.setTextContent(style, '\n .video-js {\n width: 300px;\n height: 150px;\n }\n\n .vjs-fluid {\n padding-top: 56.25%\n }\n '); } } // Run Auto-load players // You have to wait at least once in case this script is loaded after your // video in the DOM (weird behavior only with minified version) setup.autoSetupTimeout(1, videojs); /** * Current software version. Follows semver. * * @type {string} */ videojs.VERSION = '5.19.2'; /** * The global options object. These are the settings that take effect * if no overrides are specified when the player is created. * * @type {Object} */ videojs.options = _player2['default'].prototype.options_; /** * Get an object with the currently created players, keyed by player ID * * @return {Object} * The created players */ videojs.getPlayers = function () { return _player2['default'].players; }; /** * Expose players object. * * @memberOf videojs * @property {Object} players */ videojs.players = _player2['default'].players; /** * Get a component class object by name * * @borrows Component.getComponent as videojs.getComponent */ videojs.getComponent = _component2['default'].getComponent; /** * Register a component so it can referred to by name. Used when adding to other * components, either through addChild `component.addChild('myComponent')` or through * default children options `{ children: ['myComponent'] }`. * * > NOTE: You could also just initialize the component before adding. * `component.addChild(new MyComponent());` * * @param {string} name * The class name of the component * * @param {Component} comp * The component class * * @return {Component} * The newly registered component */ videojs.registerComponent = function (name, comp) { if (_tech2['default'].isTech(comp)) { _log2['default'].warn('The ' + name + ' tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)'); } _component2['default'].registerComponent.call(_component2['default'], name, comp); }; /** * Get a Tech class object by name * * @borrows Tech.getTech as videojs.getTech */ videojs.getTech = _tech2['default'].getTech; /** * Register a Tech so it can referred to by name. * This is used in the tech order for the player. * * @borrows Tech.registerTech as videojs.registerTech */ videojs.registerTech = _tech2['default'].registerTech; /** * A suite of browser and device tests from {@link browser}. * * @type {Object} * @private */ videojs.browser = browser; /** * Whether or not the browser supports touch events. Included for backward * compatibility with 4.x, but deprecated. Use `videojs.browser.TOUCH_ENABLED` * instead going forward. * * @deprecated since version 5.0 * @type {boolean} */ videojs.TOUCH_ENABLED = browser.TOUCH_ENABLED; /** * Subclass an existing class * Mimics ES6 subclassing with the `extend` keyword * * @borrows extend:extendFn as videojs.extend */ videojs.extend = _extend2['default']; /** * Merge two options objects recursively * Performs a deep merge like lodash.merge but **only merges plain objects** * (not arrays, elements, anything else) * Other values will be copied directly from the second object. * * @borrows merge-options:mergeOptions as videojs.mergeOptions */ videojs.mergeOptions = _mergeOptions3['default']; /** * Change the context (this) of a function * * > NOTE: as of v5.0 we require an ES5 shim, so you should use the native * `function() {}.bind(newContext);` instead of this. * * @borrows fn:bind as videojs.bind */ videojs.bind = Fn.bind; /** * Create a Video.js player plugin. * Plugins are only initialized when options for the plugin are included * in the player options, or the plugin function on the player instance is * called. * * @borrows plugin:plugin as videojs.plugin */ videojs.plugin = _plugins2['default']; /** * Adding languages so that they're available to all players. * Example: `videojs.addLanguage('es', { 'Hello': 'Hola' });` * * @param {string} code * The language code or dictionary property * * @param {Object} data * The data values to be translated * * @return {Object} * The resulting language dictionary object */ videojs.addLanguage = function (code, data) { var _mergeOptions; code = ('' + code).toLowerCase(); videojs.options.languages = (0, _mergeOptions3['default'])(videojs.options.languages, (_mergeOptions = {}, _mergeOptions[code] = data, _mergeOptions)); return videojs.options.languages[code]; }; /** * Log messages * * @borrows log:log as videojs.log */ videojs.log = _log2['default']; /** * Creates an emulated TimeRange object. * * @borrows time-ranges:createTimeRanges as videojs.createTimeRange */ /** * @borrows time-ranges:createTimeRanges as videojs.createTimeRanges */ videojs.createTimeRange = videojs.createTimeRanges = _timeRanges.createTimeRanges; /** * Format seconds as a time string, H:MM:SS or M:SS * Supplying a guide (in seconds) will force a number of leading zeros * to cover the length of the guide * * @borrows format-time:formatTime as videojs.formatTime */ videojs.formatTime = _formatTime2['default']; /** * Resolve and parse the elements of a URL * * @borrows url:parseUrl as videojs.parseUrl */ videojs.parseUrl = Url.parseUrl; /** * Returns whether the url passed is a cross domain request or not. * * @borrows url:isCrossOrigin as videojs.isCrossOrigin */ videojs.isCrossOrigin = Url.isCrossOrigin; /** * Event target class. * * @borrows EventTarget as videojs.EventTarget */ videojs.EventTarget = _eventTarget2['default']; /** * Add an event listener to element * It stores the handler function in a separate cache object * and adds a generic handler to the element's event, * along with a unique id (guid) to the element. * * @borrows events:on as videojs.on */ videojs.on = Events.on; /** * Trigger a listener only once for an event * * @borrows events:one as videojs.one */ videojs.one = Events.one; /** * Removes event listeners from an element * * @borrows events:off as videojs.off */ videojs.off = Events.off; /** * Trigger an event for an element * * @borrows events:trigger as videojs.trigger */ videojs.trigger = Events.trigger; /** * A cross-browser XMLHttpRequest wrapper. Here's a simple example: * * @param {Object} options * settings for the request. * * @return {XMLHttpRequest|XDomainRequest} * The request object. * * @see https://github.com/Raynos/xhr */ videojs.xhr = _xhr2['default']; /** * TextTrack class * * @borrows TextTrack as videojs.TextTrack */ videojs.TextTrack = _textTrack2['default']; /** * export the AudioTrack class so that source handlers can create * AudioTracks and then add them to the players AudioTrackList * * @borrows AudioTrack as videojs.AudioTrack */ videojs.AudioTrack = _audioTrack2['default']; /** * export the VideoTrack class so that source handlers can create * VideoTracks and then add them to the players VideoTrackList * * @borrows VideoTrack as videojs.VideoTrack */ videojs.VideoTrack = _videoTrack2['default']; /** * Determines, via duck typing, whether or not a value is a DOM element. * * @borrows dom:isEl as videojs.isEl */ videojs.isEl = Dom.isEl; /** * Determines, via duck typing, whether or not a value is a text node. * * @borrows dom:isTextNode as videojs.isTextNode */ videojs.isTextNode = Dom.isTextNode; /** * Creates an element and applies properties. * * @borrows dom:createEl as videojs.createEl */ videojs.createEl = Dom.createEl; /** * Check if an element has a CSS class * * @borrows dom:hasElClass as videojs.hasClass */ videojs.hasClass = Dom.hasElClass; /** * Add a CSS class name to an element * * @borrows dom:addElClass as videojs.addClass */ videojs.addClass = Dom.addElClass; /** * Remove a CSS class name from an element * * @borrows dom:removeElClass as videojs.removeClass */ videojs.removeClass = Dom.removeElClass; /** * Adds or removes a CSS class name on an element depending on an optional * condition or the presence/absence of the class name. * * @borrows dom:toggleElClass as videojs.toggleClass */ videojs.toggleClass = Dom.toggleElClass; /** * Apply attributes to an HTML element. * * @borrows dom:setElAttributes as videojs.setAttribute */ videojs.setAttributes = Dom.setElAttributes; /** * Get an element's attribute values, as defined on the HTML tag * Attributes are not the same as properties. They're defined on the tag * or with setAttribute (which shouldn't be used with HTML) * This will return true or false for boolean attributes. * * @borrows dom:getElAttributes as videojs.getAttributes */ videojs.getAttributes = Dom.getElAttributes; /** * Empties the contents of an element. * * @borrows dom:emptyEl as videojs.emptyEl */ videojs.emptyEl = Dom.emptyEl; /** * Normalizes and appends content to an element. * * The content for an element can be passed in multiple types and * combinations, whose behavior is as follows: * * - String * Normalized into a text node. * * - Element, TextNode * Passed through. * * - Array * A one-dimensional array of strings, elements, nodes, or functions (which * return single strings, elements, or nodes). * * - Function * If the sole argument, is expected to produce a string, element, * node, or array. * * @borrows dom:appendContents as videojs.appendContet */ videojs.appendContent = Dom.appendContent; /** * Normalizes and inserts content into an element; this is identical to * `appendContent()`, except it empties the element first. * * The content for an element can be passed in multiple types and * combinations, whose behavior is as follows: * * - String * Normalized into a text node. * * - Element, TextNode * Passed through. * * - Array * A one-dimensional array of strings, elements, nodes, or functions (which * return single strings, elements, or nodes). * * - Function * If the sole argument, is expected to produce a string, element, * node, or array. * * @borrows dom:insertContent as videojs.insertContent */ videojs.insertContent = Dom.insertContent; /** * A safe getComputedStyle with an IE8 fallback. * * This is because in Firefox, if the player is loaded in an iframe with `display:none`, * then `getComputedStyle` returns `null`, so, we do a null-check to make sure * that the player doesn't break in these cases. * See https://bugzilla.mozilla.org/show_bug.cgi?id=548397 for more details. * * @borrows computed-style:computedStyle as videojs.computedStyle */ videojs.computedStyle = _computedStyle2['default']; /* * Custom Universal Module Definition (UMD) * * Video.js will never be a non-browser lib so we can simplify UMD a bunch and * still support requirejs and browserify. This also needs to be closure * compiler compatible, so string keys are used. */ if (typeof define === 'function' && define.amd) { define('videojs', [], function () { return videojs; }); // checking that module is an object too because of umdjs/umd#35 } else if ((typeof exports === 'undefined' ? 'undefined' : _typeof(exports)) === 'object' && (typeof module === 'undefined' ? 'undefined' : _typeof(module)) === 'object') { module.exports = videojs; } exports['default'] = videojs; },{"42":42,"43":43,"5":5,"51":51,"52":52,"56":56,"62":62,"64":64,"72":72,"77":77,"78":78,"80":80,"81":81,"82":82,"83":83,"84":84,"86":86,"87":87,"88":88,"89":89,"90":90,"92":92,"94":94,"95":95,"99":99}],94:[function(_dereq_,module,exports){ (function (global){ var topLevel = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {} var minDoc = _dereq_(96); if (typeof document !== 'undefined') { module.exports = document; } else { var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4']; if (!doccy) { doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc; } module.exports = doccy; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"96":96}],95:[function(_dereq_,module,exports){ (function (global){ if (typeof window !== "undefined") { module.exports = window; } else if (typeof global !== "undefined") { module.exports = global; } else if (typeof self !== "undefined"){ module.exports = self; } else { module.exports = {}; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],96:[function(_dereq_,module,exports){ },{}],97:[function(_dereq_,module,exports){ module.exports = SafeParseTuple function SafeParseTuple(obj, reviver) { var json var error = null try { json = JSON.parse(obj, reviver) } catch (err) { error = err } return [error, json] } },{}],98:[function(_dereq_,module,exports){ function clean (s) { return s.replace(/\n\r?\s*/g, '') } module.exports = function tsml (sa) { var s = '' , i = 0 for (; i < arguments.length; i++) s += clean(sa[i]) + (arguments[i + 1] || '') return s } },{}],99:[function(_dereq_,module,exports){ "use strict"; var window = _dereq_(95) var isFunction = _dereq_(100) var parseHeaders = _dereq_(103) var xtend = _dereq_(104) module.exports = createXHR createXHR.XMLHttpRequest = window.XMLHttpRequest || noop createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) { createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) { options = initParams(uri, options, callback) options.method = method.toUpperCase() return _createXHR(options) } }) function forEachArray(array, iterator) { for (var i = 0; i < array.length; i++) { iterator(array[i]) } } function isEmpty(obj){ for(var i in obj){ if(obj.hasOwnProperty(i)) return false } return true } function initParams(uri, options, callback) { var params = uri if (isFunction(options)) { callback = options if (typeof uri === "string") { params = {uri:uri} } } else { params = xtend(options, {uri: uri}) } params.callback = callback return params } function createXHR(uri, options, callback) { options = initParams(uri, options, callback) return _createXHR(options) } function _createXHR(options) { if(typeof options.callback === "undefined"){ throw new Error("callback argument missing") } var called = false var callback = function cbOnce(err, response, body){ if(!called){ called = true options.callback(err, response, body) } } function readystatechange() { if (xhr.readyState === 4) { setTimeout(loadFunc, 0) } } function getBody() { // Chrome with requestType=blob throws errors arround when even testing access to responseText var body = undefined if (xhr.response) { body = xhr.response } else { body = xhr.responseText || getXml(xhr) } if (isJson) { try { body = JSON.parse(body) } catch (e) {} } return body } function errorFunc(evt) { clearTimeout(timeoutTimer) if(!(evt instanceof Error)){ evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") ) } evt.statusCode = 0 return callback(evt, failureResponse) } // will load the data & process the response in a special response object function loadFunc() { if (aborted) return var status clearTimeout(timeoutTimer) if(options.useXDR && xhr.status===undefined) { //IE8 CORS GET successful response doesn't have a status field, but body is fine status = 200 } else { status = (xhr.status === 1223 ? 204 : xhr.status) } var response = failureResponse var err = null if (status !== 0){ response = { body: getBody(), statusCode: status, method: method, headers: {}, url: uri, rawRequest: xhr } if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE response.headers = parseHeaders(xhr.getAllResponseHeaders()) } } else { err = new Error("Internal XMLHttpRequest Error") } return callback(err, response, response.body) } var xhr = options.xhr || null if (!xhr) { if (options.cors || options.useXDR) { xhr = new createXHR.XDomainRequest() }else{ xhr = new createXHR.XMLHttpRequest() } } var key var aborted var uri = xhr.url = options.uri || options.url var method = xhr.method = options.method || "GET" var body = options.body || options.data var headers = xhr.headers = options.headers || {} var sync = !!options.sync var isJson = false var timeoutTimer var failureResponse = { body: undefined, headers: {}, statusCode: 0, method: method, url: uri, rawRequest: xhr } if ("json" in options && options.json !== false) { isJson = true headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user if (method !== "GET" && method !== "HEAD") { headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user body = JSON.stringify(options.json === true ? body : options.json) } } xhr.onreadystatechange = readystatechange xhr.onload = loadFunc xhr.onerror = errorFunc // IE9 must have onprogress be set to a unique function. xhr.onprogress = function () { // IE must die } xhr.onabort = function(){ aborted = true; } xhr.ontimeout = errorFunc xhr.open(method, uri, !sync, options.username, options.password) //has to be after open if(!sync) { xhr.withCredentials = !!options.withCredentials } // Cannot set timeout with sync request // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent if (!sync && options.timeout > 0 ) { timeoutTimer = setTimeout(function(){ if (aborted) return aborted = true//IE9 may still call readystatechange xhr.abort("timeout") var e = new Error("XMLHttpRequest timeout") e.code = "ETIMEDOUT" errorFunc(e) }, options.timeout ) } if (xhr.setRequestHeader) { for(key in headers){ if(headers.hasOwnProperty(key)){ xhr.setRequestHeader(key, headers[key]) } } } else if (options.headers && !isEmpty(options.headers)) { throw new Error("Headers cannot be set on an XDomainRequest object") } if ("responseType" in options) { xhr.responseType = options.responseType } if ("beforeSend" in options && typeof options.beforeSend === "function" ) { options.beforeSend(xhr) } // Microsoft Edge browser sends "undefined" when send is called with undefined value. // XMLHttpRequest spec says to pass null as body to indicate no body // See https://github.com/naugtur/xhr/issues/100. xhr.send(body || null) return xhr } function getXml(xhr) { if (xhr.responseType === "document") { return xhr.responseXML } var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror" if (xhr.responseType === "" && !firefoxBugTakenEffect) { return xhr.responseXML } return null } function noop() {} },{"100":100,"103":103,"104":104,"95":95}],100:[function(_dereq_,module,exports){ module.exports = isFunction var toString = Object.prototype.toString function isFunction (fn) { var string = toString.call(fn) return string === '[object Function]' || (typeof fn === 'function' && string !== '[object RegExp]') || (typeof window !== 'undefined' && // IE8 and below (fn === window.setTimeout || fn === window.alert || fn === window.confirm || fn === window.prompt)) }; },{}],101:[function(_dereq_,module,exports){ var isFunction = _dereq_(100) module.exports = forEach var toString = Object.prototype.toString var hasOwnProperty = Object.prototype.hasOwnProperty function forEach(list, iterator, context) { if (!isFunction(iterator)) { throw new TypeError('iterator must be a function') } if (arguments.length < 3) { context = this } if (toString.call(list) === '[object Array]') forEachArray(list, iterator, context) else if (typeof list === 'string') forEachString(list, iterator, context) else forEachObject(list, iterator, context) } function forEachArray(array, iterator, context) { for (var i = 0, len = array.length; i < len; i++) { if (hasOwnProperty.call(array, i)) { iterator.call(context, array[i], i, array) } } } function forEachString(string, iterator, context) { for (var i = 0, len = string.length; i < len; i++) { // no such thing as a sparse string. iterator.call(context, string.charAt(i), i, string) } } function forEachObject(object, iterator, context) { for (var k in object) { if (hasOwnProperty.call(object, k)) { iterator.call(context, object[k], k, object) } } } },{"100":100}],102:[function(_dereq_,module,exports){ exports = module.exports = trim; function trim(str){ return str.replace(/^\s*|\s*$/g, ''); } exports.left = function(str){ return str.replace(/^\s*/, ''); }; exports.right = function(str){ return str.replace(/\s*$/, ''); }; },{}],103:[function(_dereq_,module,exports){ var trim = _dereq_(102) , forEach = _dereq_(101) , isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; } module.exports = function (headers) { if (!headers) return {} var result = {} forEach( trim(headers).split('\n') , function (row) { var index = row.indexOf(':') , key = trim(row.slice(0, index)).toLowerCase() , value = trim(row.slice(index + 1)) if (typeof(result[key]) === 'undefined') { result[key] = value } else if (isArray(result[key])) { result[key].push(value) } else { result[key] = [ result[key], value ] } } ) return result } },{"101":101,"102":102}],104:[function(_dereq_,module,exports){ module.exports = extend var hasOwnProperty = Object.prototype.hasOwnProperty; function extend() { var target = {} for (var i = 0; i < arguments.length; i++) { var source = arguments[i] for (var key in source) { if (hasOwnProperty.call(source, key)) { target[key] = source[key] } } } return target } },{}],105:[function(_dereq_,module,exports){ /** * Copyright 2013 vtt.js Contributors * * 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. */ // Default exports for Node. Export the extended versions of VTTCue and // VTTRegion in Node since we likely want the capability to convert back and // forth between JSON. If we don't then it's not that big of a deal since we're // off browser. var window = _dereq_(109); var vttjs = module.exports = { WebVTT: _dereq_(106).WebVTT, VTTCue: _dereq_(107).VTTCue, VTTRegion: _dereq_(108).VTTRegion }; window.vttjs = vttjs; window.WebVTT = vttjs.WebVTT; var cueShim = vttjs.VTTCue; var regionShim = vttjs.VTTRegion; var nativeVTTCue = window.VTTCue; var nativeVTTRegion = window.VTTRegion; vttjs.shim = function() { window.VTTCue = cueShim; window.VTTRegion = regionShim; }; vttjs.restore = function() { window.VTTCue = nativeVTTCue; window.VTTRegion = nativeVTTRegion; }; if (!window.VTTCue) { vttjs.shim(); } },{"106":106,"107":107,"108":108,"109":109}],106:[function(_dereq_,module,exports){ /** * Copyright 2013 vtt.js Contributors * * 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. */ /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ (function(global) { var _objCreate = Object.create || (function() { function F() {} return function(o) { if (arguments.length !== 1) { throw new Error('Object.create shim only accepts one parameter.'); } F.prototype = o; return new F(); }; })(); // Creates a new ParserError object from an errorData object. The errorData // object should have default code and message properties. The default message // property can be overriden by passing in a message parameter. // See ParsingError.Errors below for acceptable errors. function ParsingError(errorData, message) { this.name = "ParsingError"; this.code = errorData.code; this.message = message || errorData.message; } ParsingError.prototype = _objCreate(Error.prototype); ParsingError.prototype.constructor = ParsingError; // ParsingError metadata for acceptable ParsingErrors. ParsingError.Errors = { BadSignature: { code: 0, message: "Malformed WebVTT signature." }, BadTimeStamp: { code: 1, message: "Malformed time stamp." } }; // Try to parse input as a time stamp. function parseTimeStamp(input) { function computeSeconds(h, m, s, f) { return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000; } var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/); if (!m) { return null; } if (m[3]) { // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds] return computeSeconds(m[1], m[2], m[3].replace(":", ""), m[4]); } else if (m[1] > 59) { // Timestamp takes the form of [hours]:[minutes].[milliseconds] // First position is hours as it's over 59. return computeSeconds(m[1], m[2], 0, m[4]); } else { // Timestamp takes the form of [minutes]:[seconds].[milliseconds] return computeSeconds(0, m[1], m[2], m[4]); } } // A settings object holds key/value pairs and will ignore anything but the first // assignment to a specific key. function Settings() { this.values = _objCreate(null); } Settings.prototype = { // Only accept the first assignment to any key. set: function(k, v) { if (!this.get(k) && v !== "") { this.values[k] = v; } }, // Return the value for a key, or a default value. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with // a number of possible default values as properties where 'defaultKey' is // the key of the property that will be chosen; otherwise it's assumed to be // a single value. get: function(k, dflt, defaultKey) { if (defaultKey) { return this.has(k) ? this.values[k] : dflt[defaultKey]; } return this.has(k) ? this.values[k] : dflt; }, // Check whether we have a value for a key. has: function(k) { return k in this.values; }, // Accept a setting if its one of the given alternatives. alt: function(k, v, a) { for (var n = 0; n < a.length; ++n) { if (v === a[n]) { this.set(k, v); break; } } }, // Accept a setting if its a valid (signed) integer. integer: function(k, v) { if (/^-?\d+$/.test(v)) { // integer this.set(k, parseInt(v, 10)); } }, // Accept a setting if its a valid percentage. percent: function(k, v) { var m; if ((m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/))) { v = parseFloat(v); if (v >= 0 && v <= 100) { this.set(k, v); return true; } } return false; } }; // Helper function to parse input into groups separated by 'groupDelim', and // interprete each group as a key/value pair separated by 'keyValueDelim'. function parseOptions(input, callback, keyValueDelim, groupDelim) { var groups = groupDelim ? input.split(groupDelim) : [input]; for (var i in groups) { if (typeof groups[i] !== "string") { continue; } var kv = groups[i].split(keyValueDelim); if (kv.length !== 2) { continue; } var k = kv[0]; var v = kv[1]; callback(k, v); } } function parseCue(input, cue, regionList) { // Remember the original input if we need to throw an error. var oInput = input; // 4.1 WebVTT timestamp function consumeTimeStamp() { var ts = parseTimeStamp(input); if (ts === null) { throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed timestamp: " + oInput); } // Remove time stamp from input. input = input.replace(/^[^\sa-zA-Z-]+/, ""); return ts; } // 4.4.2 WebVTT cue settings function consumeCueSettings(input, cue) { var settings = new Settings(); parseOptions(input, function (k, v) { switch (k) { case "region": // Find the last region we parsed with the same region id. for (var i = regionList.length - 1; i >= 0; i--) { if (regionList[i].id === v) { settings.set(k, regionList[i].region); break; } } break; case "vertical": settings.alt(k, v, ["rl", "lr"]); break; case "line": var vals = v.split(","), vals0 = vals[0]; settings.integer(k, vals0); settings.percent(k, vals0) ? settings.set("snapToLines", false) : null; settings.alt(k, vals0, ["auto"]); if (vals.length === 2) { settings.alt("lineAlign", vals[1], ["start", "middle", "end"]); } break; case "position": vals = v.split(","); settings.percent(k, vals[0]); if (vals.length === 2) { settings.alt("positionAlign", vals[1], ["start", "middle", "end"]); } break; case "size": settings.percent(k, v); break; case "align": settings.alt(k, v, ["start", "middle", "end", "left", "right"]); break; } }, /:/, /\s/); // Apply default values for any missing fields. cue.region = settings.get("region", null); cue.vertical = settings.get("vertical", ""); cue.line = settings.get("line", "auto"); cue.lineAlign = settings.get("lineAlign", "start"); cue.snapToLines = settings.get("snapToLines", true); cue.size = settings.get("size", 100); cue.align = settings.get("align", "middle"); cue.position = settings.get("position", { start: 0, left: 0, middle: 50, end: 100, right: 100 }, cue.align); cue.positionAlign = settings.get("positionAlign", { start: "start", left: "start", middle: "middle", end: "end", right: "end" }, cue.align); } function skipWhitespace() { input = input.replace(/^\s+/, ""); } // 4.1 WebVTT cue timings. skipWhitespace(); cue.startTime = consumeTimeStamp(); // (1) collect cue start time skipWhitespace(); if (input.substr(0, 3) !== "-->") { // (3) next characters must match "-->" throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed time stamp (time stamps must be separated by '-->'): " + oInput); } input = input.substr(3); skipWhitespace(); cue.endTime = consumeTimeStamp(); // (5) collect cue end time // 4.1 WebVTT cue settings list. skipWhitespace(); consumeCueSettings(input, cue); } var ESCAPE = { "&amp;": "&", "&lt;": "<", "&gt;": ">", "&lrm;": "\u200e", "&rlm;": "\u200f", "&nbsp;": "\u00a0" }; var TAG_NAME = { c: "span", i: "i", b: "b", u: "u", ruby: "ruby", rt: "rt", v: "span", lang: "span" }; var TAG_ANNOTATION = { v: "title", lang: "lang" }; var NEEDS_PARENT = { rt: "ruby" }; // Parse content into a document fragment. function parseContent(window, input) { function nextToken() { // Check for end-of-string. if (!input) { return null; } // Consume 'n' characters from the input. function consume(result) { input = input.substr(result.length); return result; } var m = input.match(/^([^<]*)(<[^>]+>?)?/); // If there is some text before the next tag, return it, otherwise return // the tag. return consume(m[1] ? m[1] : m[2]); } // Unescape a string 's'. function unescape1(e) { return ESCAPE[e]; } function unescape(s) { while ((m = s.match(/&(amp|lt|gt|lrm|rlm|nbsp);/))) { s = s.replace(m[0], unescape1); } return s; } function shouldAdd(current, element) { return !NEEDS_PARENT[element.localName] || NEEDS_PARENT[element.localName] === current.localName; } // Create an element for this tag. function createElement(type, annotation) { var tagName = TAG_NAME[type]; if (!tagName) { return null; } var element = window.document.createElement(tagName); element.localName = tagName; var name = TAG_ANNOTATION[type]; if (name && annotation) { element[name] = annotation.trim(); } return element; } var rootDiv = window.document.createElement("div"), current = rootDiv, t, tagStack = []; while ((t = nextToken()) !== null) { if (t[0] === '<') { if (t[1] === "/") { // If the closing tag matches, move back up to the parent node. if (tagStack.length && tagStack[tagStack.length - 1] === t.substr(2).replace(">", "")) { tagStack.pop(); current = current.parentNode; } // Otherwise just ignore the end tag. continue; } var ts = parseTimeStamp(t.substr(1, t.length - 2)); var node; if (ts) { // Timestamps are lead nodes as well. node = window.document.createProcessingInstruction("timestamp", ts); current.appendChild(node); continue; } var m = t.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/); // If we can't parse the tag, skip to the next tag. if (!m) { continue; } // Try to construct an element, and ignore the tag if we couldn't. node = createElement(m[1], m[3]); if (!node) { continue; } // Determine if the tag should be added based on the context of where it // is placed in the cuetext. if (!shouldAdd(current, node)) { continue; } // Set the class list (as a list of classes, separated by space). if (m[2]) { node.className = m[2].substr(1).replace('.', ' '); } // Append the node to the current node, and enter the scope of the new // node. tagStack.push(m[1]); current.appendChild(node); current = node; continue; } // Text nodes are leaf nodes. current.appendChild(window.document.createTextNode(unescape(t))); } return rootDiv; } // This is a list of all the Unicode characters that have a strong // right-to-left category. What this means is that these characters are // written right-to-left for sure. It was generated by pulling all the strong // right-to-left characters out of the Unicode data table. That table can // found at: http://www.unicode.org/Public/UNIDATA/UnicodeData.txt var strongRTLRanges = [[0x5be, 0x5be], [0x5c0, 0x5c0], [0x5c3, 0x5c3], [0x5c6, 0x5c6], [0x5d0, 0x5ea], [0x5f0, 0x5f4], [0x608, 0x608], [0x60b, 0x60b], [0x60d, 0x60d], [0x61b, 0x61b], [0x61e, 0x64a], [0x66d, 0x66f], [0x671, 0x6d5], [0x6e5, 0x6e6], [0x6ee, 0x6ef], [0x6fa, 0x70d], [0x70f, 0x710], [0x712, 0x72f], [0x74d, 0x7a5], [0x7b1, 0x7b1], [0x7c0, 0x7ea], [0x7f4, 0x7f5], [0x7fa, 0x7fa], [0x800, 0x815], [0x81a, 0x81a], [0x824, 0x824], [0x828, 0x828], [0x830, 0x83e], [0x840, 0x858], [0x85e, 0x85e], [0x8a0, 0x8a0], [0x8a2, 0x8ac], [0x200f, 0x200f], [0xfb1d, 0xfb1d], [0xfb1f, 0xfb28], [0xfb2a, 0xfb36], [0xfb38, 0xfb3c], [0xfb3e, 0xfb3e], [0xfb40, 0xfb41], [0xfb43, 0xfb44], [0xfb46, 0xfbc1], [0xfbd3, 0xfd3d], [0xfd50, 0xfd8f], [0xfd92, 0xfdc7], [0xfdf0, 0xfdfc], [0xfe70, 0xfe74], [0xfe76, 0xfefc], [0x10800, 0x10805], [0x10808, 0x10808], [0x1080a, 0x10835], [0x10837, 0x10838], [0x1083c, 0x1083c], [0x1083f, 0x10855], [0x10857, 0x1085f], [0x10900, 0x1091b], [0x10920, 0x10939], [0x1093f, 0x1093f], [0x10980, 0x109b7], [0x109be, 0x109bf], [0x10a00, 0x10a00], [0x10a10, 0x10a13], [0x10a15, 0x10a17], [0x10a19, 0x10a33], [0x10a40, 0x10a47], [0x10a50, 0x10a58], [0x10a60, 0x10a7f], [0x10b00, 0x10b35], [0x10b40, 0x10b55], [0x10b58, 0x10b72], [0x10b78, 0x10b7f], [0x10c00, 0x10c48], [0x1ee00, 0x1ee03], [0x1ee05, 0x1ee1f], [0x1ee21, 0x1ee22], [0x1ee24, 0x1ee24], [0x1ee27, 0x1ee27], [0x1ee29, 0x1ee32], [0x1ee34, 0x1ee37], [0x1ee39, 0x1ee39], [0x1ee3b, 0x1ee3b], [0x1ee42, 0x1ee42], [0x1ee47, 0x1ee47], [0x1ee49, 0x1ee49], [0x1ee4b, 0x1ee4b], [0x1ee4d, 0x1ee4f], [0x1ee51, 0x1ee52], [0x1ee54, 0x1ee54], [0x1ee57, 0x1ee57], [0x1ee59, 0x1ee59], [0x1ee5b, 0x1ee5b], [0x1ee5d, 0x1ee5d], [0x1ee5f, 0x1ee5f], [0x1ee61, 0x1ee62], [0x1ee64, 0x1ee64], [0x1ee67, 0x1ee6a], [0x1ee6c, 0x1ee72], [0x1ee74, 0x1ee77], [0x1ee79, 0x1ee7c], [0x1ee7e, 0x1ee7e], [0x1ee80, 0x1ee89], [0x1ee8b, 0x1ee9b], [0x1eea1, 0x1eea3], [0x1eea5, 0x1eea9], [0x1eeab, 0x1eebb], [0x10fffd, 0x10fffd]]; function isStrongRTLChar(charCode) { for (var i = 0; i < strongRTLRanges.length; i++) { var currentRange = strongRTLRanges[i]; if (charCode >= currentRange[0] && charCode <= currentRange[1]) { return true; } } return false; } function determineBidi(cueDiv) { var nodeStack = [], text = "", charCode; if (!cueDiv || !cueDiv.childNodes) { return "ltr"; } function pushNodes(nodeStack, node) { for (var i = node.childNodes.length - 1; i >= 0; i--) { nodeStack.push(node.childNodes[i]); } } function nextTextNode(nodeStack) { if (!nodeStack || !nodeStack.length) { return null; } var node = nodeStack.pop(), text = node.textContent || node.innerText; if (text) { // TODO: This should match all unicode type B characters (paragraph // separator characters). See issue #115. var m = text.match(/^.*(\n|\r)/); if (m) { nodeStack.length = 0; return m[0]; } return text; } if (node.tagName === "ruby") { return nextTextNode(nodeStack); } if (node.childNodes) { pushNodes(nodeStack, node); return nextTextNode(nodeStack); } } pushNodes(nodeStack, cueDiv); while ((text = nextTextNode(nodeStack))) { for (var i = 0; i < text.length; i++) { charCode = text.charCodeAt(i); if (isStrongRTLChar(charCode)) { return "rtl"; } } } return "ltr"; } function computeLinePos(cue) { if (typeof cue.line === "number" && (cue.snapToLines || (cue.line >= 0 && cue.line <= 100))) { return cue.line; } if (!cue.track || !cue.track.textTrackList || !cue.track.textTrackList.mediaElement) { return -1; } var track = cue.track, trackList = track.textTrackList, count = 0; for (var i = 0; i < trackList.length && trackList[i] !== track; i++) { if (trackList[i].mode === "showing") { count++; } } return ++count * -1; } function StyleBox() { } // Apply styles to a div. If there is no div passed then it defaults to the // div on 'this'. StyleBox.prototype.applyStyles = function(styles, div) { div = div || this.div; for (var prop in styles) { if (styles.hasOwnProperty(prop)) { div.style[prop] = styles[prop]; } } }; StyleBox.prototype.formatStyle = function(val, unit) { return val === 0 ? 0 : val + unit; }; // Constructs the computed display state of the cue (a div). Places the div // into the overlay which should be a block level element (usually a div). function CueStyleBox(window, cue, styleOptions) { var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); var color = "rgba(255, 255, 255, 1)"; var backgroundColor = "rgba(0, 0, 0, 0.8)"; if (isIE8) { color = "rgb(255, 255, 255)"; backgroundColor = "rgb(0, 0, 0)"; } StyleBox.call(this); this.cue = cue; // Parse our cue's text into a DOM tree rooted at 'cueDiv'. This div will // have inline positioning and will function as the cue background box. this.cueDiv = parseContent(window, cue.text); var styles = { color: color, backgroundColor: backgroundColor, position: "relative", left: 0, right: 0, top: 0, bottom: 0, display: "inline" }; if (!isIE8) { styles.writingMode = cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl"; styles.unicodeBidi = "plaintext"; } this.applyStyles(styles, this.cueDiv); // Create an absolutely positioned div that will be used to position the cue // div. Note, all WebVTT cue-setting alignments are equivalent to the CSS // mirrors of them except "middle" which is "center" in CSS. this.div = window.document.createElement("div"); styles = { textAlign: cue.align === "middle" ? "center" : cue.align, font: styleOptions.font, whiteSpace: "pre-line", position: "absolute" }; if (!isIE8) { styles.direction = determineBidi(this.cueDiv); styles.writingMode = cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl". stylesunicodeBidi = "plaintext"; } this.applyStyles(styles); this.div.appendChild(this.cueDiv); // Calculate the distance from the reference edge of the viewport to the text // position of the cue box. The reference edge will be resolved later when // the box orientation styles are applied. var textPos = 0; switch (cue.positionAlign) { case "start": textPos = cue.position; break; case "middle": textPos = cue.position - (cue.size / 2); break; case "end": textPos = cue.position - cue.size; break; } // Horizontal box orientation; textPos is the distance from the left edge of the // area to the left edge of the box and cue.size is the distance extending to // the right from there. if (cue.vertical === "") { this.applyStyles({ left: this.formatStyle(textPos, "%"), width: this.formatStyle(cue.size, "%") }); // Vertical box orientation; textPos is the distance from the top edge of the // area to the top edge of the box and cue.size is the height extending // downwards from there. } else { this.applyStyles({ top: this.formatStyle(textPos, "%"), height: this.formatStyle(cue.size, "%") }); } this.move = function(box) { this.applyStyles({ top: this.formatStyle(box.top, "px"), bottom: this.formatStyle(box.bottom, "px"), left: this.formatStyle(box.left, "px"), right: this.formatStyle(box.right, "px"), height: this.formatStyle(box.height, "px"), width: this.formatStyle(box.width, "px") }); }; } CueStyleBox.prototype = _objCreate(StyleBox.prototype); CueStyleBox.prototype.constructor = CueStyleBox; // Represents the co-ordinates of an Element in a way that we can easily // compute things with such as if it overlaps or intersects with another Element. // Can initialize it with either a StyleBox or another BoxPosition. function BoxPosition(obj) { var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); // Either a BoxPosition was passed in and we need to copy it, or a StyleBox // was passed in and we need to copy the results of 'getBoundingClientRect' // as the object returned is readonly. All co-ordinate values are in reference // to the viewport origin (top left). var lh, height, width, top; if (obj.div) { height = obj.div.offsetHeight; width = obj.div.offsetWidth; top = obj.div.offsetTop; var rects = (rects = obj.div.childNodes) && (rects = rects[0]) && rects.getClientRects && rects.getClientRects(); obj = obj.div.getBoundingClientRect(); // In certain cases the outter div will be slightly larger then the sum of // the inner div's lines. This could be due to bold text, etc, on some platforms. // In this case we should get the average line height and use that. This will // result in the desired behaviour. lh = rects ? Math.max((rects[0] && rects[0].height) || 0, obj.height / rects.length) : 0; } this.left = obj.left; this.right = obj.right; this.top = obj.top || top; this.height = obj.height || height; this.bottom = obj.bottom || (top + (obj.height || height)); this.width = obj.width || width; this.lineHeight = lh !== undefined ? lh : obj.lineHeight; if (isIE8 && !this.lineHeight) { this.lineHeight = 13; } } // Move the box along a particular axis. Optionally pass in an amount to move // the box. If no amount is passed then the default is the line height of the // box. BoxPosition.prototype.move = function(axis, toMove) { toMove = toMove !== undefined ? toMove : this.lineHeight; switch (axis) { case "+x": this.left += toMove; this.right += toMove; break; case "-x": this.left -= toMove; this.right -= toMove; break; case "+y": this.top += toMove; this.bottom += toMove; break; case "-y": this.top -= toMove; this.bottom -= toMove; break; } }; // Check if this box overlaps another box, b2. BoxPosition.prototype.overlaps = function(b2) { return this.left < b2.right && this.right > b2.left && this.top < b2.bottom && this.bottom > b2.top; }; // Check if this box overlaps any other boxes in boxes. BoxPosition.prototype.overlapsAny = function(boxes) { for (var i = 0; i < boxes.length; i++) { if (this.overlaps(boxes[i])) { return true; } } return false; }; // Check if this box is within another box. BoxPosition.prototype.within = function(container) { return this.top >= container.top && this.bottom <= container.bottom && this.left >= container.left && this.right <= container.right; }; // Check if this box is entirely within the container or it is overlapping // on the edge opposite of the axis direction passed. For example, if "+x" is // passed and the box is overlapping on the left edge of the container, then // return true. BoxPosition.prototype.overlapsOppositeAxis = function(container, axis) { switch (axis) { case "+x": return this.left < container.left; case "-x": return this.right > container.right; case "+y": return this.top < container.top; case "-y": return this.bottom > container.bottom; } }; // Find the percentage of the area that this box is overlapping with another // box. BoxPosition.prototype.intersectPercentage = function(b2) { var x = Math.max(0, Math.min(this.right, b2.right) - Math.max(this.left, b2.left)), y = Math.max(0, Math.min(this.bottom, b2.bottom) - Math.max(this.top, b2.top)), intersectArea = x * y; return intersectArea / (this.height * this.width); }; // Convert the positions from this box to CSS compatible positions using // the reference container's positions. This has to be done because this // box's positions are in reference to the viewport origin, whereas, CSS // values are in referecne to their respective edges. BoxPosition.prototype.toCSSCompatValues = function(reference) { return { top: this.top - reference.top, bottom: reference.bottom - this.bottom, left: this.left - reference.left, right: reference.right - this.right, height: this.height, width: this.width }; }; // Get an object that represents the box's position without anything extra. // Can pass a StyleBox, HTMLElement, or another BoxPositon. BoxPosition.getSimpleBoxPosition = function(obj) { var height = obj.div ? obj.div.offsetHeight : obj.tagName ? obj.offsetHeight : 0; var width = obj.div ? obj.div.offsetWidth : obj.tagName ? obj.offsetWidth : 0; var top = obj.div ? obj.div.offsetTop : obj.tagName ? obj.offsetTop : 0; obj = obj.div ? obj.div.getBoundingClientRect() : obj.tagName ? obj.getBoundingClientRect() : obj; var ret = { left: obj.left, right: obj.right, top: obj.top || top, height: obj.height || height, bottom: obj.bottom || (top + (obj.height || height)), width: obj.width || width }; return ret; }; // Move a StyleBox to its specified, or next best, position. The containerBox // is the box that contains the StyleBox, such as a div. boxPositions are // a list of other boxes that the styleBox can't overlap with. function moveBoxToLinePosition(window, styleBox, containerBox, boxPositions) { // Find the best position for a cue box, b, on the video. The axis parameter // is a list of axis, the order of which, it will move the box along. For example: // Passing ["+x", "-x"] will move the box first along the x axis in the positive // direction. If it doesn't find a good position for it there it will then move // it along the x axis in the negative direction. function findBestPosition(b, axis) { var bestPosition, specifiedPosition = new BoxPosition(b), percentage = 1; // Highest possible so the first thing we get is better. for (var i = 0; i < axis.length; i++) { while (b.overlapsOppositeAxis(containerBox, axis[i]) || (b.within(containerBox) && b.overlapsAny(boxPositions))) { b.move(axis[i]); } // We found a spot where we aren't overlapping anything. This is our // best position. if (b.within(containerBox)) { return b; } var p = b.intersectPercentage(containerBox); // If we're outside the container box less then we were on our last try // then remember this position as the best position. if (percentage > p) { bestPosition = new BoxPosition(b); percentage = p; } // Reset the box position to the specified position. b = new BoxPosition(specifiedPosition); } return bestPosition || specifiedPosition; } var boxPosition = new BoxPosition(styleBox), cue = styleBox.cue, linePos = computeLinePos(cue), axis = []; // If we have a line number to align the cue to. if (cue.snapToLines) { var size; switch (cue.vertical) { case "": axis = [ "+y", "-y" ]; size = "height"; break; case "rl": axis = [ "+x", "-x" ]; size = "width"; break; case "lr": axis = [ "-x", "+x" ]; size = "width"; break; } var step = boxPosition.lineHeight, position = step * Math.round(linePos), maxPosition = containerBox[size] + step, initialAxis = axis[0]; // If the specified intial position is greater then the max position then // clamp the box to the amount of steps it would take for the box to // reach the max position. if (Math.abs(position) > maxPosition) { position = position < 0 ? -1 : 1; position *= Math.ceil(maxPosition / step) * step; } // If computed line position returns negative then line numbers are // relative to the bottom of the video instead of the top. Therefore, we // need to increase our initial position by the length or width of the // video, depending on the writing direction, and reverse our axis directions. if (linePos < 0) { position += cue.vertical === "" ? containerBox.height : containerBox.width; axis = axis.reverse(); } // Move the box to the specified position. This may not be its best // position. boxPosition.move(initialAxis, position); } else { // If we have a percentage line value for the cue. var calculatedPercentage = (boxPosition.lineHeight / containerBox.height) * 100; switch (cue.lineAlign) { case "middle": linePos -= (calculatedPercentage / 2); break; case "end": linePos -= calculatedPercentage; break; } // Apply initial line position to the cue box. switch (cue.vertical) { case "": styleBox.applyStyles({ top: styleBox.formatStyle(linePos, "%") }); break; case "rl": styleBox.applyStyles({ left: styleBox.formatStyle(linePos, "%") }); break; case "lr": styleBox.applyStyles({ right: styleBox.formatStyle(linePos, "%") }); break; } axis = [ "+y", "-x", "+x", "-y" ]; // Get the box position again after we've applied the specified positioning // to it. boxPosition = new BoxPosition(styleBox); } var bestPosition = findBestPosition(boxPosition, axis); styleBox.move(bestPosition.toCSSCompatValues(containerBox)); } function WebVTT() { // Nothing } // Helper to allow strings to be decoded instead of the default binary utf8 data. WebVTT.StringDecoder = function() { return { decode: function(data) { if (!data) { return ""; } if (typeof data !== "string") { throw new Error("Error - expected string data."); } return decodeURIComponent(encodeURIComponent(data)); } }; }; WebVTT.convertCueToDOMTree = function(window, cuetext) { if (!window || !cuetext) { return null; } return parseContent(window, cuetext); }; var FONT_SIZE_PERCENT = 0.05; var FONT_STYLE = "sans-serif"; var CUE_BACKGROUND_PADDING = "1.5%"; // Runs the processing model over the cues and regions passed to it. // @param overlay A block level element (usually a div) that the computed cues // and regions will be placed into. WebVTT.processCues = function(window, cues, overlay) { if (!window || !cues || !overlay) { return null; } // Remove all previous children. while (overlay.firstChild) { overlay.removeChild(overlay.firstChild); } var paddedOverlay = window.document.createElement("div"); paddedOverlay.style.position = "absolute"; paddedOverlay.style.left = "0"; paddedOverlay.style.right = "0"; paddedOverlay.style.top = "0"; paddedOverlay.style.bottom = "0"; paddedOverlay.style.margin = CUE_BACKGROUND_PADDING; overlay.appendChild(paddedOverlay); // Determine if we need to compute the display states of the cues. This could // be the case if a cue's state has been changed since the last computation or // if it has not been computed yet. function shouldCompute(cues) { for (var i = 0; i < cues.length; i++) { if (cues[i].hasBeenReset || !cues[i].displayState) { return true; } } return false; } // We don't need to recompute the cues' display states. Just reuse them. if (!shouldCompute(cues)) { for (var i = 0; i < cues.length; i++) { paddedOverlay.appendChild(cues[i].displayState); } return; } var boxPositions = [], containerBox = BoxPosition.getSimpleBoxPosition(paddedOverlay), fontSize = Math.round(containerBox.height * FONT_SIZE_PERCENT * 100) / 100; var styleOptions = { font: fontSize + "px " + FONT_STYLE }; (function() { var styleBox, cue; for (var i = 0; i < cues.length; i++) { cue = cues[i]; // Compute the intial position and styles of the cue div. styleBox = new CueStyleBox(window, cue, styleOptions); paddedOverlay.appendChild(styleBox.div); // Move the cue div to it's correct line position. moveBoxToLinePosition(window, styleBox, containerBox, boxPositions); // Remember the computed div so that we don't have to recompute it later // if we don't have too. cue.displayState = styleBox.div; boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox)); } })(); }; WebVTT.Parser = function(window, vttjs, decoder) { if (!decoder) { decoder = vttjs; vttjs = {}; } if (!vttjs) { vttjs = {}; } this.window = window; this.vttjs = vttjs; this.state = "INITIAL"; this.buffer = ""; this.decoder = decoder || new TextDecoder("utf8"); this.regionList = []; }; WebVTT.Parser.prototype = { // If the error is a ParsingError then report it to the consumer if // possible. If it's not a ParsingError then throw it like normal. reportOrThrowError: function(e) { if (e instanceof ParsingError) { this.onparsingerror && this.onparsingerror(e); } else { throw e; } }, parse: function (data) { var self = this; // If there is no data then we won't decode it, but will just try to parse // whatever is in buffer already. This may occur in circumstances, for // example when flush() is called. if (data) { // Try to decode the data that we received. self.buffer += self.decoder.decode(data, {stream: true}); } function collectNextLine() { var buffer = self.buffer; var pos = 0; while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') { ++pos; } var line = buffer.substr(0, pos); // Advance the buffer early in case we fail below. if (buffer[pos] === '\r') { ++pos; } if (buffer[pos] === '\n') { ++pos; } self.buffer = buffer.substr(pos); return line; } // 3.4 WebVTT region and WebVTT region settings syntax function parseRegion(input) { var settings = new Settings(); parseOptions(input, function (k, v) { switch (k) { case "id": settings.set(k, v); break; case "width": settings.percent(k, v); break; case "lines": settings.integer(k, v); break; case "regionanchor": case "viewportanchor": var xy = v.split(','); if (xy.length !== 2) { break; } // We have to make sure both x and y parse, so use a temporary // settings object here. var anchor = new Settings(); anchor.percent("x", xy[0]); anchor.percent("y", xy[1]); if (!anchor.has("x") || !anchor.has("y")) { break; } settings.set(k + "X", anchor.get("x")); settings.set(k + "Y", anchor.get("y")); break; case "scroll": settings.alt(k, v, ["up"]); break; } }, /=/, /\s/); // Create the region, using default values for any values that were not // specified. if (settings.has("id")) { var region = new (self.vttjs.VTTRegion || self.window.VTTRegion)(); region.width = settings.get("width", 100); region.lines = settings.get("lines", 3); region.regionAnchorX = settings.get("regionanchorX", 0); region.regionAnchorY = settings.get("regionanchorY", 100); region.viewportAnchorX = settings.get("viewportanchorX", 0); region.viewportAnchorY = settings.get("viewportanchorY", 100); region.scroll = settings.get("scroll", ""); // Register the region. self.onregion && self.onregion(region); // Remember the VTTRegion for later in case we parse any VTTCues that // reference it. self.regionList.push({ id: settings.get("id"), region: region }); } } // draft-pantos-http-live-streaming-20 // https://tools.ietf.org/html/draft-pantos-http-live-streaming-20#section-3.5 // 3.5 WebVTT function parseTimestampMap(input) { var settings = new Settings(); parseOptions(input, function(k, v) { switch(k) { case "MPEGT": settings.integer(k + 'S', v); break; case "LOCA": settings.set(k + 'L', parseTimeStamp(v)); break; } }, /[^\d]:/, /,/); self.ontimestampmap && self.ontimestampmap({ "MPEGTS": settings.get("MPEGTS"), "LOCAL": settings.get("LOCAL") }); } // 3.2 WebVTT metadata header syntax function parseHeader(input) { if (input.match(/X-TIMESTAMP-MAP/)) { // This line contains HLS X-TIMESTAMP-MAP metadata parseOptions(input, function(k, v) { switch(k) { case "X-TIMESTAMP-MAP": parseTimestampMap(v); break; } }, /=/); } else { parseOptions(input, function (k, v) { switch (k) { case "Region": // 3.3 WebVTT region metadata header syntax parseRegion(v); break; } }, /:/); } } // 5.1 WebVTT file parsing. try { var line; if (self.state === "INITIAL") { // We can't start parsing until we have the first line. if (!/\r\n|\n/.test(self.buffer)) { return this; } line = collectNextLine(); var m = line.match(/^WEBVTT([ \t].*)?$/); if (!m || !m[0]) { throw new ParsingError(ParsingError.Errors.BadSignature); } self.state = "HEADER"; } var alreadyCollectedLine = false; while (self.buffer) { // We can't parse a line until we have the full line. if (!/\r\n|\n/.test(self.buffer)) { return this; } if (!alreadyCollectedLine) { line = collectNextLine(); } else { alreadyCollectedLine = false; } switch (self.state) { case "HEADER": // 13-18 - Allow a header (metadata) under the WEBVTT line. if (/:/.test(line)) { parseHeader(line); } else if (!line) { // An empty line terminates the header and starts the body (cues). self.state = "ID"; } continue; case "NOTE": // Ignore NOTE blocks. if (!line) { self.state = "ID"; } continue; case "ID": // Check for the start of NOTE blocks. if (/^NOTE($|[ \t])/.test(line)) { self.state = "NOTE"; break; } // 19-29 - Allow any number of line terminators, then initialize new cue values. if (!line) { continue; } self.cue = new (self.vttjs.VTTCue || self.window.VTTCue)(0, 0, ""); self.state = "CUE"; // 30-39 - Check if self line contains an optional identifier or timing data. if (line.indexOf("-->") === -1) { self.cue.id = line; continue; } // Process line as start of a cue. /*falls through*/ case "CUE": // 40 - Collect cue timings and settings. try { parseCue(line, self.cue, self.regionList); } catch (e) { self.reportOrThrowError(e); // In case of an error ignore rest of the cue. self.cue = null; self.state = "BADCUE"; continue; } self.state = "CUETEXT"; continue; case "CUETEXT": var hasSubstring = line.indexOf("-->") !== -1; // 34 - If we have an empty line then report the cue. // 35 - If we have the special substring '-->' then report the cue, // but do not collect the line as we need to process the current // one as a new cue. if (!line || hasSubstring && (alreadyCollectedLine = true)) { // We are done parsing self cue. self.oncue && self.oncue(self.cue); self.cue = null; self.state = "ID"; continue; } if (self.cue.text) { self.cue.text += "\n"; } self.cue.text += line; continue; case "BADCUE": // BADCUE // 54-62 - Collect and discard the remaining cue. if (!line) { self.state = "ID"; } continue; } } } catch (e) { self.reportOrThrowError(e); // If we are currently parsing a cue, report what we have. if (self.state === "CUETEXT" && self.cue && self.oncue) { self.oncue(self.cue); } self.cue = null; // Enter BADWEBVTT state if header was not parsed correctly otherwise // another exception occurred so enter BADCUE state. self.state = self.state === "INITIAL" ? "BADWEBVTT" : "BADCUE"; } return this; }, flush: function () { var self = this; try { // Finish decoding the stream. self.buffer += self.decoder.decode(); // Synthesize the end of the current cue or region. if (self.cue || self.state === "HEADER") { self.buffer += "\n\n"; self.parse(); } // If we've flushed, parsed, and we're still on the INITIAL state then // that means we don't have enough of the stream to parse the first // line. if (self.state === "INITIAL") { throw new ParsingError(ParsingError.Errors.BadSignature); } } catch(e) { self.reportOrThrowError(e); } self.onflush && self.onflush(); return this; } }; global.WebVTT = WebVTT; }(this, (this.vttjs || {}))); },{}],107:[function(_dereq_,module,exports){ /** * Copyright 2013 vtt.js Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function(root, vttjs) { var autoKeyword = "auto"; var directionSetting = { "": true, "lr": true, "rl": true }; var alignSetting = { "start": true, "middle": true, "end": true, "left": true, "right": true }; function findDirectionSetting(value) { if (typeof value !== "string") { return false; } var dir = directionSetting[value.toLowerCase()]; return dir ? value.toLowerCase() : false; } function findAlignSetting(value) { if (typeof value !== "string") { return false; } var align = alignSetting[value.toLowerCase()]; return align ? value.toLowerCase() : false; } function extend(obj) { var i = 1; for (; i < arguments.length; i++) { var cobj = arguments[i]; for (var p in cobj) { obj[p] = cobj[p]; } } return obj; } function VTTCue(startTime, endTime, text) { var cue = this; var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); var baseObj = {}; if (isIE8) { cue = document.createElement('custom'); } else { baseObj.enumerable = true; } /** * Shim implementation specific properties. These properties are not in * the spec. */ // Lets us know when the VTTCue's data has changed in such a way that we need // to recompute its display state. This lets us compute its display state // lazily. cue.hasBeenReset = false; /** * VTTCue and TextTrackCue properties * http://dev.w3.org/html5/webvtt/#vttcue-interface */ var _id = ""; var _pauseOnExit = false; var _startTime = startTime; var _endTime = endTime; var _text = text; var _region = null; var _vertical = ""; var _snapToLines = true; var _line = "auto"; var _lineAlign = "start"; var _position = 50; var _positionAlign = "middle"; var _size = 50; var _align = "middle"; Object.defineProperty(cue, "id", extend({}, baseObj, { get: function() { return _id; }, set: function(value) { _id = "" + value; } })); Object.defineProperty(cue, "pauseOnExit", extend({}, baseObj, { get: function() { return _pauseOnExit; }, set: function(value) { _pauseOnExit = !!value; } })); Object.defineProperty(cue, "startTime", extend({}, baseObj, { get: function() { return _startTime; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("Start time must be set to a number."); } _startTime = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "endTime", extend({}, baseObj, { get: function() { return _endTime; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("End time must be set to a number."); } _endTime = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "text", extend({}, baseObj, { get: function() { return _text; }, set: function(value) { _text = "" + value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "region", extend({}, baseObj, { get: function() { return _region; }, set: function(value) { _region = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "vertical", extend({}, baseObj, { get: function() { return _vertical; }, set: function(value) { var setting = findDirectionSetting(value); // Have to check for false because the setting an be an empty string. if (setting === false) { throw new SyntaxError("An invalid or illegal string was specified."); } _vertical = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "snapToLines", extend({}, baseObj, { get: function() { return _snapToLines; }, set: function(value) { _snapToLines = !!value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "line", extend({}, baseObj, { get: function() { return _line; }, set: function(value) { if (typeof value !== "number" && value !== autoKeyword) { throw new SyntaxError("An invalid number or illegal string was specified."); } _line = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "lineAlign", extend({}, baseObj, { get: function() { return _lineAlign; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _lineAlign = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "position", extend({}, baseObj, { get: function() { return _position; }, set: function(value) { if (value < 0 || value > 100) { throw new Error("Position must be between 0 and 100."); } _position = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "positionAlign", extend({}, baseObj, { get: function() { return _positionAlign; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _positionAlign = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "size", extend({}, baseObj, { get: function() { return _size; }, set: function(value) { if (value < 0 || value > 100) { throw new Error("Size must be between 0 and 100."); } _size = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "align", extend({}, baseObj, { get: function() { return _align; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _align = setting; this.hasBeenReset = true; } })); /** * Other <track> spec defined properties */ // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state cue.displayState = undefined; if (isIE8) { return cue; } } /** * VTTCue methods */ VTTCue.prototype.getCueAsHTML = function() { // Assume WebVTT.convertCueToDOMTree is on the global. return WebVTT.convertCueToDOMTree(window, this.text); }; root.VTTCue = root.VTTCue || VTTCue; vttjs.VTTCue = VTTCue; }(this, (this.vttjs || {}))); },{}],108:[function(_dereq_,module,exports){ /** * Copyright 2013 vtt.js Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function(root, vttjs) { var scrollSetting = { "": true, "up": true }; function findScrollSetting(value) { if (typeof value !== "string") { return false; } var scroll = scrollSetting[value.toLowerCase()]; return scroll ? value.toLowerCase() : false; } function isValidPercentValue(value) { return typeof value === "number" && (value >= 0 && value <= 100); } // VTTRegion shim http://dev.w3.org/html5/webvtt/#vttregion-interface function VTTRegion() { var _width = 100; var _lines = 3; var _regionAnchorX = 0; var _regionAnchorY = 100; var _viewportAnchorX = 0; var _viewportAnchorY = 100; var _scroll = ""; Object.defineProperties(this, { "width": { enumerable: true, get: function() { return _width; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("Width must be between 0 and 100."); } _width = value; } }, "lines": { enumerable: true, get: function() { return _lines; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("Lines must be set to a number."); } _lines = value; } }, "regionAnchorY": { enumerable: true, get: function() { return _regionAnchorY; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("RegionAnchorX must be between 0 and 100."); } _regionAnchorY = value; } }, "regionAnchorX": { enumerable: true, get: function() { return _regionAnchorX; }, set: function(value) { if(!isValidPercentValue(value)) { throw new Error("RegionAnchorY must be between 0 and 100."); } _regionAnchorX = value; } }, "viewportAnchorY": { enumerable: true, get: function() { return _viewportAnchorY; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("ViewportAnchorY must be between 0 and 100."); } _viewportAnchorY = value; } }, "viewportAnchorX": { enumerable: true, get: function() { return _viewportAnchorX; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("ViewportAnchorX must be between 0 and 100."); } _viewportAnchorX = value; } }, "scroll": { enumerable: true, get: function() { return _scroll; }, set: function(value) { var setting = findScrollSetting(value); // Have to check for false as an empty string is a legal value. if (setting === false) { throw new SyntaxError("An invalid or illegal string was specified."); } _scroll = setting; } } }); } root.VTTRegion = root.VTTRegion || VTTRegion; vttjs.VTTRegion = VTTRegion; }(this, (this.vttjs || {}))); },{}],109:[function(_dereq_,module,exports){ arguments[4][95][0].apply(exports,arguments) },{"95":95}]},{},[93])(93) }); !function(){!function(a){var b=a&&a.videojs;if(b){b.CDN_VERSION="5.19.2";var c="https:"===a.location.protocol?"https://":"http://";b.options.flash.swf=c+"vjs.zencdn.net/swf/5.3.0/video-js.swf"}}(window),function(a,b,c,d,e,f,g){b&&b.HELP_IMPROVE_VIDEOJS!==!1&&(e.random()>.01||(f=b.location,g=b.videojs||{},a.src="//www.google-analytics.com/__utm.gif?utmwv=5.4.2&utmac=UA-16505296-3&utmn=1&utmhn="+d(f.hostname)+"&utmsr="+b.screen.availWidth+"x"+b.screen.availHeight+"&utmul="+(c.language||c.userLanguage||"").toLowerCase()+"&utmr="+d(f.href)+"&utmp="+d(f.hostname+f.pathname)+"&utmcc=__utma%3D1."+e.floor(1e10*e.random())+".1.1.1.1%3B&utme=8(vjsv*cdnv)9("+g.VERSION+"*"+g.CDN_VERSION+")"))}(new Image,window,navigator,encodeURIComponent,Math)}();
'use strict' var test = require('tape') var util = require('util') var redeyed = require('..') function inspect(obj) { return util.inspect(obj, false, 5, true) } test('adding custom asserts ... ', function(t) { t.constructor.prototype.assertSurrounds = function(code, opts, expected) { var result = redeyed(code, opts).code this.equals(result, expected, inspect(code) + ' => ' + inspect(expected)) return this } t.end() }) test('\nbefore/after config, keywords', function(t) { var opts001 = { Keyword: { _default: { _before: '*', _after: '&' } } } t.test('\n# ' + inspect(opts001), function(t) { t.assertSurrounds('this', opts001, '*this&') t.assertSurrounds('if (a == 1) return', opts001, '*if& (a == 1) *return&') t.assertSurrounds('var n = new Test();', opts001, '*var& n = *new& Test();') t.end() }) var opts002 = { Keyword: { 'function': { _before: '^' } , 'return': { _before: '(', _after: ')' } , _default: { _before: '*', _after: '&' } } } t.test('\n# ' + inspect(opts002), function(t) { t.assertSurrounds( [ 'function foo (bar) {' , ' var a = 3;' , ' return bar + a;' , '}' ].join('\n') , opts002 , [ '^function& foo (bar) {' , ' *var& a = 3;' , ' (return) bar + a;' , '}' ].join('\n')) t.end() }) t.end() })
var assert = require("assert"); var Lib = require("./../ramda"); describe("contains", function() { var contains = Lib.contains; it("returns true if an element is in a list", function() { assert.equal(contains(7, [1,2,3,9,8,7,100,200,300]), true); }); it("returns false if an element is not in a list", function() { assert.equal(contains(99, [1,2,3,9,8,7,100,200,300]), false); }); it("returns false for the empty list", function() { assert.equal(contains(1, []), false); }); }); describe('uniq', function() { var uniq = Lib.uniq; it('returns a set from any array (i.e. purges duplicate elements)', function() { var arr = [1,2,3,1,2,3,1,2,3]; assert.deepEqual(uniq(arr), [1,2,3]); }); it('returns an empty array for an empty array', function() { assert.deepEqual(uniq([]), []); }); }); describe('isSet', function() { var isSet = Lib.isSet; it('returns true if a list is composed of unique elements', function() { var arr = [1,2,3,1,2,3,1,2,3]; assert.equal(isSet(arr), false); assert.equal(isSet([3,1,4,2,5,7,9]), true); }); it('returns true for an empty array', function() { assert.equal(isSet([]), true); }); });
var browserSync = require('browser-sync'), changed = require('gulp-changed'), config = {}, gulp = require('gulp'); config.server = require('./../../config/server'); config.path = require('./../../config/path'); gulp.task('pages', function () { var result = gulp.src(config.path.views.src) .pipe(changed(config.path.views.dist)) .pipe(gulp.dest(config.path.views.dist)); if (config.server.enabled === true) { result.pipe(browserSync.reload({stream: true})); } });
/** * node-compress-commons * * Copyright (c) 2014 Chris Talkington, contributors. * Licensed under the MIT license. * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT */ var Stream = require('stream').Stream; var PassThrough = require('readable-stream').PassThrough; var util = module.exports = {}; util.isStream = function(source) { return source instanceof Stream; }; util.normalizeInputSource = function(source) { if (source === null) { return Buffer.alloc(0); } else if (typeof source === 'string') { return Buffer.from(source); } else if (util.isStream(source) && !source._readableState) { var normalized = new PassThrough(); source.pipe(normalized); return normalized; } return source; };
$(document).ready(function() { jQuery(".lowvision").on("click", function(e){ $( '#lowvision-keyboard, .lv-help').toggle(); }); ////////// //https://jsfiddle.net/rickj33/3fby0nzr/ /// /// jQuery("#course-inputlv").on("keyup", function(theEvent){ //alert(theEvent.which); //var charCode = (evt.which) ? evt.which : event.keyCode; var charCode = (theEvent.which); var lastKey = jQuery("#roberto input").val(); var lastChar = lastKey[lastKey.length -1]; //alert('hi agian'); if (charCode == 17) { checkAlternatives(lastChar); //alert('pressed Control'); } else { counter = 0; replacementStatus = false; //alert('nope it was '+theEvent.which); } }); jQuery("#course-lvbutton").on("click", function(e){ jQuery('#search-loader').css({'display':'block'}); jQuery('#custom-search-step-1').css({'display':'block'}); jQuery('#search-courses').css({'display':'none'}); jQuery('#response-with-result2').css({'display':'none'}); var searchSemesterKey = []; jQuery('li.semester-key').each(function(index) { index++; if ($('#semester-option'+index).hasClass('active-semester')) { searchSemesterKey.push(jQuery("#semester-option"+index).data('term')); } }); //The number 4 as a suffix is a reminder that oasis currently uses it as an indicator of online classes var deliveryMethod4 = ''; if ($('#delivery-format1').hasClass('active')) { deliveryMethod4 = '4'; } else { deliveryMethod4 = ''; } var input = jQuery('#course-inputlv').val(); var searchTermKey = jQuery('#course-inputlv').val(); var searchTypeKey = 'typed'; var userID = jQuery('#course-inputlv').data('user-id'); $.get( jQuery('body').data('path') + 'search.php', { 'searchSemesterKey': searchSemesterKey, 'deliveryMethod4': deliveryMethod4, 'searchTermKey': searchTermKey, 'searchTypeKey': 'typed'}) .done(function(data) { jQuery("#search-courses").html(data); jQuery('#search-courses').css({'display':'block'}); jQuery('#response-with-result2').css({'display':'block'}); jQuery('#search-loader').css({'display':'none'}); }); });//keypress $('#online-menu + [aria-labelledby="online-menu"] a').on('click', function (e) { e.preventDefault(); var format = this; //alert(format); var choice = $(this).text(); var choiceID = $(this).data('format'); //alert(choiceID); $('#online-menu').html(choice); }); $('#campus-menu + [aria-labelledby="campus-menu"] a').on('click', function (e) { e.preventDefault(); var campus = this; var campusChoice = $(this).text(); var campusID = $(this).data('campus'); $('#campus-menu').html(campusChoice); }); ///////////////////////////////////////////////// //SA 12 June start Port CF code to courses-lowvision.js so may be used across site var replacementStatus = false; var counter = 0; var keyAlternatives = [//open keyAlternatives array [ 'A', ['Q','W','S','Z','Shift','Caps'] ], [ 'a', ['q','w','s','z','Shift','Caps'] ], [ 'B', ['G','H','N','Space','Space','V'] ], [ 'b', ['g','h','n','Space','Space','v'] ], [ 'C', ['D','F','V','Space','Alt','X'] ], [ 'c', ['d','f','v','Space','Alt','x'] ], [ 'D', ['E','R','F','C','X','S'] ], [ 'd', ['e','r','f','c','x','s'] ], [ 'E', ['3','4','R','D','S','W'] ], [ 'e', ['3','4','r','d','s','w'] ], [ 'F', ['R','T','G','V','C','D'] ], [ 'f', ['r','t','g','v','c','d'] ], [ 'G', ['T','Y','H','B','V','F'] ], [ 'g', ['t','y','h','b','v','f'] ], [ 'H', ['Y','U','J','N','B','G'] ], [ 'h', ['y','u','j','n','b','g'] ], [ 'I', ['8','9','O','K','J','U'] ], [ 'i', ['8','9','o','k','j','u'] ], [ 'J', ['U','I','K','M','N','H'] ], [ 'j', ['u','i','k','m','n','h'] ], [ 'K', ['I','O','L','<','M','J'] ], [ 'k', ['i','o','l',',','m','j'] ], [ 'L', ['O','P',':','>','<','K'] ], [ 'l', ['o','p',';','.',',','k'] ], [ 'M', ['J','K','<','Space','Space','N'] ], [ 'm', ['j','k',',','Space','Space','n'] ], [ 'N', ['H','J','M','Space','Space','B'] ], [ 'n', ['h','j','m','Space','Space','b'] ], [ 'O', ['(',')','P','L','K','I'] ], [ 'o', ['9','0','p','l','k','i'] ], [ 'P', [')','_','{',':','L','O'] ], [ 'p', ['0','-','[',';','l','o'] ], [ 'Q', ['!','@','W','A','Caps','Tab'] ], [ 'q', ['1','2','w','a','Caps','Tab'] ], [ 'R', ['$','%','T','F','D','E'] ], [ 'r', ['4','5','t','f','d','e'] ], [ 'S', ['W','E','D','X','Z','A'] ], [ 's', ['w','e','d','x','z','a'] ], [ 'T', ['%','^','Y','G','F','R'] ], [ 't', ['5','6','y','g','f','r'] ], [ 'U', ['&','*','I','J','H','Y'] ], [ 'u', ['7','8','i','j','h','y'] ], [ 'V', ['F','G','B','Space','Space','C'] ], [ 'v', ['f','g','b','Space','Space','c'] ], [ 'W', ['@','#','E','S','A','Q'] ], [ 'w', ['2','3','e','s','a','q'] ], [ 'X', ['S','D','C','Alt','Win/Apple','Z'] ], [ 'x', ['s','d','c','Alt','Win/Apple','z'] ], [ 'Y', ['^','&','U','H','G','T'] ], [ 'y', ['6','7','u','h','g','t'] ], [ 'Z', ['A','S','X','Win/Apple','Fn','Shift'] ], [ 'z', ['a','s','x','Win/Apple','Fn','Shift'] ], //////////////////////// [ '1', ['`','2','3','4','5','6'] ], [ '!', ['~','@','#','$','%','^'] ], ////////////////// ];//close KeyAlternatives array function displayKeyCode(evt) { var textBox = ''; var charCode = (evt.which) ? evt.which : event.keyCode; var lastKey = jQuery("#roberto input").val(); var lastChar = lastKey[lastKey.length -1]; if (charCode == 17) { checkAlternatives(lastChar); } else { counter = 0; replacementStatus = false; } } function checkAlternatives (lastChar) { for (var i = 0; i < keyAlternatives.length; i++) { var thingToCheck = !replacementStatus ? lastChar : replacementStatus; console.log('thing to check ' + thingToCheck); if (thingToCheck == keyAlternatives[i][0]) { replacementStatus = thingToCheck; var str = jQuery("#roberto input").val(); var res = str.substring(jQuery("#roberto input").val(), jQuery("#roberto input").val().length-1); console.log ('replacement: ' + keyAlternatives[i][1][counter]); jQuery("#roberto input").val(res + keyAlternatives[i][1][counter]); counter = counter < keyAlternatives[i][1].length-1 ? counter + 1 : 0; } } } <!-- CF code 9 June 2017 --> //SA 12 June end Port CF code to courses-lowvision.js so may be used across site /////////////////////////////////////////////// /* ////////////////////////////////////////////////////////////////////////////// //works but moving this up in the file var howManyClicks = 0; $("#right-arrow").click(function() { howManyClicks++; //alert('howManyClicks: ' +howManyClicks); var textEntered = $("#course-input").val(); //alert('text entered is ' +textEntered); var lastKey = $("#course-input").val(); var rightArrow = lastKey[lastKey.length - 1]; //var theLetter = lastKey[lastKey.length - 1]; //alert('rightArrow is ' +rightArrow); var $btn = $(this); var howManyClicks = ($btn.data("click_count") || 0) + 1; $("#right-arrow").data("click_count", howManyClicks); if ( howManyClicks == 1 ) $("#right-arrow").text(rightArrow) && $("#right-arrow").val(rightArrow) && $("#right-arrow").css({'color' : 'red', 'font-size' : '5em'}); else if ( howManyClicks == 2 ) $("#right-arrow").text(rightArrowAlt1) && $("#right-arrow").val(rightArrowAlt1) && $("#right-arrow").css({'color' : 'red', 'font-size' : '5em'}); else if ( howManyClicks == 3 ) $("#right-arrow").text(rightArrowAlt2) && $("#right-arrow").val(rightArrowAlt2) && $("#right-arrow").css({'color' : 'red', 'font-size' : '5em'}); else if ( howManyClicks == 4 ) $("#right-arrow").text(rightArrowAlt3) && $("#right-arrow").val(rightArrowAlt3) && $("#right-arrow").css({'color' : 'red', 'font-size' : '5em'}); else if ( howManyClicks == 5 ) $("#right-arrow").text(rightArrowAlt4) && $("#right-arrow").val(rightArrowAlt4) && $("#right-arrow").css({'color' : 'red', 'font-size' : '5em'}); else if ( howManyClicks == 6 ) $("#right-arrow").text(rightArrowAlt5) && $("#right-arrow").val(rightArrowAlt5) && $("#right-arrow").css({'color' : 'red', 'font-size' : '5em'}); else { $("#right-arrow").text("last alternate"); //$btn.unbind("click"); var howManyClicks = 0; } return false; }); //SA 23 May 2017 end right arrow ////////////////////////////////////// //SA 24 May 2017 update jQuery('#accept-option').on('click', function() { $('#accept-option').val(function(i,v){ return v.substr(0,(v.length -1)) }); //return false; var specialKey = textEntered[textEntered.length - 1]; alert('specialKey is '+specialKey); //var theLetter = specialKey;//storing the last choice var caretPos = document.getElementById("course-input").selectionStart; alert('caretPos is '+caretPos); var textAreaTxt = jQuery("#course-input").val(); alert('textAreaText is ' +textAreaTxt); //var txtToAdd = ($(this).val()); //jQuery("#course-input").val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos) ); jQuery("#course-input").val(textAreaTxt.substring(0, caretPos) + 'txtToAdd' + textAreaTxt.substring(caretPos) ); $('#accept-option').html('<span style="font-size:10em;color:red;">'+specialKey+'</span>'); });//closing brace right-arrow button ///////////////////////////////////////////////////////////////////////////// //IMPORTANT keypress needed rather than keydown to capture case var theLetter =''; $('#course-input').keypress(function(e){ //if (e.which == 13) $('#right-arrow').html('reset'); var theLetter = String.fromCharCode(e.which); var alternate1 = ''; var alternate2 = ''; var alternate3 = ''; var alternate4 = ''; var alternate5 = ''; var alternate6 = ''; var text; switch(theLetter) { case 'A': text = 'You chose the upper-case letter A.'; alternate1 = 'Q'; rightArrowAlt1 = 'Q'; alternate2 = 'W'; rightArrowAlt2 = 'W'; alternate3 = 'S'; rightArrowAlt3 = 'S'; alternate4 = 'Z'; rightArrowAlt4 = 'Z'; alternate5 = 'Shift'; rightArrowAlt5 = 'Shift'; alternate6 = 'Caps'; rightArrowAlt6 = 'Caps'; break; case 'a': text = 'You chose the lower-case letter a.'; alternate1 = 'q'; rightArrowAlt1 = 'q'; alternate2 = 'w'; rightArrowAlt2 = 'w'; alternate3 = 's'; rightArrowAlt3 = 's'; alternate4 = 'z'; rightArrowAlt4 = 'z'; alternate5 = 'Shift'; rightArrowAlt5 = 'Shift'; alternate6 = 'Caps'; rightArrowAlt6 = 'Caps'; break; case 'B': text = 'You chose the upper-case letter B.'; alternate1 = 'G'; rightArrowAlt1 = 'G'; alternate2 = 'H'; rightArrowAlt2 = 'H'; alternate3 = 'N'; rightArrowAlt3 = 'N'; alternate4 = 'SpaceBar'; rightArrowAlt4 = 'SpaceBar'; alternate5 = 'V'; rightArrowAlt5 = 'V'; alternate6 = 'F'; rightArrowAlt6 = 'F'; break; case 'b': text = 'You chose the lower-case letter b.'; alternate1 = 'g'; rightArrowAlt1 = 'g'; alternate2 = 'h'; rightArrowAlt2 = 'h'; alternate3 = 'n'; rightArrowAlt3 = 'n'; alternate4 = 'SpaceBar'; rightArrowAlt4 = 'SpaceBar'; alternate5 = 'v'; rightArrowAlt5 = 'v'; alternate6 = 'f'; rightArrowAlt6 = 'f'; break; case 'C': text = 'You chose the upper-case letter C.'; alternate1 = 'D'; rightArrowAlt1 = 'D'; alternate2 = 'F'; rightArrowAlt2 = 'F'; alternate3 = 'V'; rightArrowAlt3 = 'Q'; alternate4 = 'SpaceBar'; rightArrowAlt4 = 'SpaceBar'; alternate5 = 'Alt'; rightArrowAlt5 = 'Alt'; alternate6 = 'X'; rightArrowAlt6 = 'X'; break; case 'c': text = 'You chose the lower-case letter c.'; alternate1 = 'd'; rightArrowAlt1 = 'd'; alternate2 = 'f'; rightArrowAlt2 = 'f'; alternate3 = 'v'; rightArrowAlt3 = 'v'; alternate4 = 'SpaceBar'; rightArrowAlt4 = 'SpaceBar'; alternate5 = 'Alt'; rightArrowAlt5 = 'Alt'; alternate6 = 's'; rightArrowAlt6 = 's'; break; case 'D': text = 'You chose the upper-case letter D.'; alternate1 = 'E'; rightArrowAlt1 = 'E'; alternate2 = 'R'; rightArrowAlt2 = 'R'; alternate3 = 'F'; rightArrowAlt3 = 'F'; alternate4 = 'C'; rightArrowAlt4 = 'C'; alternate5 = 'X'; rightArrowAlt5 = 'X'; alternate6 = 'S'; rightArrowAlt6 = 'S'; break; case 'd': text = 'You chose the lower-case letter d.'; alternate1 = 'e'; rightArrowAlt1 = 'e'; alternate2 = 'r'; rightArrowAlt2 = 'r'; alternate3 = 'f'; rightArrowAlt3 = 'f'; alternate4 = 'c'; rightArrowAlt4 = 'c'; alternate5 = 'x'; rightArrowAlt5 = 'x'; alternate6 = 's'; rightArrowAlt6 = 's'; break; case 'E': text = 'You chose the upper-case letter E.'; alternate1 = '3'; rightArrowAlt1 = '3'; alternate2 = '4'; rightArrowAlt2 = '4'; alternate3 = 'R'; rightArrowAlt3 = 'R'; alternate4 = 'D'; rightArrowAlt4 = 'D'; alternate5 = 'S'; rightArrowAlt5 = 'S'; alternate6 = 'W'; rightArrowAlt6 = 'W'; break; case 'e': text = 'You chose the lower-case letter e.'; alternate1 = '3'; rightArrowAlt1 = '3'; alternate2 = '4'; rightArrowAlt2 = '4'; alternate3 = 'r'; rightArrowAlt3 = 'r'; alternate4 = 'd'; rightArrowAlt4 = 'd'; alternate5 = 's'; rightArrowAlt5 = 's'; alternate6 = 'w'; rightArrowAlt6 = 'w'; break; case 'F': text = 'You chose the upper-case letter F.'; alternate1 = 'R'; rightArrowAlt1 = 'R'; alternate2 = 'T'; rightArrowAlt2 = 'T'; alternate3 = 'G'; rightArrowAlt3 = 'G'; alternate4 = 'V'; rightArrowAlt4 = 'V'; alternate5 = 'C'; rightArrowAlt5 = 'C'; alternate6 = 'D'; rightArrowAlt6 = 'D'; break; case 'f': text = 'You chose the lower-case letter f.'; alternate1 = 'r'; rightArrowAlt1 = 'r'; alternate2 = 't'; rightArrowAlt2 = 't'; alternate3 = 'g'; rightArrowAlt3 = 'g'; alternate4 = 'v'; rightArrowAlt4 = 'v'; alternate5 = 'c'; rightArrowAlt5 = 'c'; alternate6 = 'd'; rightArrowAlt6 = 'd'; break; case 'G': text = 'You chose the upper-case letter G.'; alternate1 = 'T'; rightArrowAlt1 = 'T'; alternate2 = 'Y'; rightArrowAlt2 = 'Y'; alternate3 = 'H'; rightArrowAlt3 = 'H'; alternate4 = 'B'; rightArrowAlt4 = 'B'; alternate5 = 'V'; rightArrowAlt5 = 'V'; alternate6 = 'F'; rightArrowAlt6 = 'F'; break; case 'g': text = 'You chose the lower-case letter g.'; alternate1 = 't'; rightArrowAlt1 = 't'; alternate2 = 'y'; rightArrowAlt2 = 'y'; alternate3 = 'h'; rightArrowAlt3 = 'h'; alternate4 = 'b'; rightArrowAlt4 = 'b'; alternate5 = 'v'; rightArrowAlt5 = 'v'; alternate6 = 'f'; rightArrowAlt6 = 'f'; break; case 'H': text = 'You chose the upper-case letter H.'; alternate1 = 'Y'; rightArrowAlt1 = 'Y'; alternate2 = 'U'; rightArrowAlt2 = 'U'; alternate3 = 'J'; rightArrowAlt3 = 'J'; alternate4 = 'N'; rightArrowAlt4 = 'N'; alternate5 = 'B'; rightArrowAlt5 = 'B'; alternate6 = 'G'; rightArrowAlt6 = 'G'; break; case 'h': text = 'You chose the lower-case letter h.'; alternate1 = 'y'; rightArrowAlt1 = 'y'; alternate2 = 'u'; rightArrowAlt2 = 'u'; alternate3 = 'j'; rightArrowAlt3 = 'j'; alternate4 = 'n'; rightArrowAlt4 = 'n'; alternate5 = 'b'; rightArrowAlt5 = 'b'; alternate6 = 'g'; rightArrowAlt6 = 'g'; break; case 'I': text = 'You chose the upper-case letter I.'; alternate1 = '8'; rightArrowAlt1 = '8'; alternate2 = '9'; rightArrowAlt2 = '9'; alternate3 = 'O'; rightArrowAlt3 = '0'; alternate4 = 'K'; rightArrowAlt4 = 'K'; alternate5 = 'J'; rightArrowAlt5 = 'J'; alternate6 = 'U'; rightArrowAlt6 = 'U'; break; case 'i': text = 'You chose the lower-case letter i.'; alternate1 = '8'; rightArrowAlt1 = '8'; alternate2 = '9'; rightArrowAlt2 = '9'; alternate3 = 'o'; rightArrowAlt3 = 'o'; alternate4 = 'k'; rightArrowAlt4 = 'k'; alternate5 = 'j'; rightArrowAlt5 = 'j'; alternate6 = 'u'; rightArrowAlt6 = 'u'; break; case 'J': text = 'You chose the upper-case letter J.'; alternate1 = 'U'; rightArrowAlt1 = 'U'; alternate2 = 'I'; rightArrowAlt2 = 'I'; alternate3 = 'K'; rightArrowAlt3 = 'K'; alternate4 = 'M'; rightArrowAlt4 = 'M'; alternate5 = 'N'; rightArrowAlt5 = 'N'; alternate6 = 'H'; rightArrowAlt6 = 'H'; break; case 'j': text = 'You chose the lower-case letter j.'; alternate1 = 'u'; rightArrowAlt1 = 'u'; alternate2 = 'i'; rightArrowAlt2 = 'i'; alternate3 = 'k'; rightArrowAlt3 = 'k'; alternate4 = 'm'; rightArrowAlt4 = 'm'; alternate5 = 'n'; rightArrowAlt5 = 'n'; alternate6 = 'h'; rightArrowAlt6 = 'h'; break; case 'K': text = 'You chose the upper-case letter K.'; alternate1 = 'I'; rightArrowAlt1 = 'I'; alternate2 = 'O'; rightArrowAlt2 = 'O'; alternate3 = 'L'; rightArrowAlt3 = 'L'; alternate4 = '<'; rightArrowAlt4 = '<'; alternate5 = 'M'; rightArrowAlt5 = 'M'; alternate6 = 'J'; rightArrowAlt6 = 'J'; break; case 'k': text = 'You chose the lower-case letter k.'; alternate1 = 'i'; rightArrowAlt1 = 'i'; alternate2 = 'o'; rightArrowAlt2 = 'o'; alternate3 = 'l'; rightArrowAlt3 = 'l'; alternate4 = ','; rightArrowAlt4 = ','; alternate5 = 'm'; rightArrowAlt5 = 'm'; alternate6 = 'j'; rightArrowAlt6 = 'j'; break; case 'L': text = 'You chose the upper-case letter L.'; alternate1 = 'O'; rightArrowAlt1 = 'O'; alternate2 = 'P'; rightArrowAlt2 = 'P'; alternate3 = ':'; rightArrowAlt3 = ':'; alternate4 = '>'; rightArrowAlt4 = '>'; alternate5 = '<'; rightArrowAlt5 = '<'; alternate6 = 'K'; rightArrowAlt6 = 'K'; break; case 'l': text = 'You chose the lower-case letter l.'; alternate1 = 'o'; rightArrowAlt1 = 'o'; alternate2 = 'p'; rightArrowAlt2 = 'p'; alternate3 = ';'; rightArrowAlt3 = ';'; alternate4 = '.'; rightArrowAlt4 = '.'; alternate5 = ','; rightArrowAlt5 = ','; alternate6 = 'k'; rightArrowAlt6 = 'k'; break; case 'M': text = 'You chose the upper-case letter M.'; alternate1 = 'J'; rightArrowAlt1 = 'J'; alternate2 = 'K'; rightArrowAlt2 = 'K'; alternate3 = '<'; rightArrowAlt3 = '<'; alternate4 = 'SpaceBar'; rightArrowAlt4 = 'SpaceBar'; alternate5 = 'Spacebar'; rightArrowAlt5 = 'Spacebar'; alternate6 = 'N'; rightArrowAlt6 = 'N'; break; case 'm': text = 'You chose the lower-case letter m.'; alternate1 = 'j'; rightArrowAlt1 = 'j'; alternate2 = 'k'; rightArrowAlt2 = 'k'; alternate3 = ','; rightArrowAlt3 = ','; alternate4 = 'Spacebar'; rightArrowAlt4 = 'Spacebar'; alternate5 = 'Spacebar'; rightArrowAlt5 = 'Spacebar'; alternate6 = 'n'; rightArrowAlt6 = 'n'; break; case 'N': text = 'You chose the upper-case letter N.'; alternate1 = 'H'; rightArrowAlt1 = 'H'; alternate2 = 'J'; rightArrowAlt2 = 'J'; alternate3 = 'M'; rightArrowAlt3 = 'M'; alternate4 = 'SpaceBar'; rightArrowAlt4 = 'SpaceBar'; alternate5 = 'Spacebar'; rightArrowAlt5 = 'Spacebar'; alternate6 = 'B'; rightArrowAlt6 = 'B'; break; case 'n': text = 'You chose the lower-case letter n.'; alternate1 = 'h'; rightArrowAlt1 = 'h'; alternate2 = 'j'; rightArrowAlt2 = 'j'; alternate3 = 'm'; rightArrowAlt3 = 'm'; alternate4 = 'Spacebar'; rightArrowAlt4 = 'Spacebar'; alternate5 = 'Spacebar'; rightArrowAlt5 = 'Spacebar'; alternate6 = 'b'; rightArrowAlt6 = 'b'; break; case 'O': text = 'You chose the upper-case letter O.'; alternate1 = '9'; rightArrowAlt1 = '9'; alternate2 = '0'; rightArrowAlt2 = '0'; alternate3 = 'P'; rightArrowAlt3 = 'P'; alternate4 = 'L'; rightArrowAlt4 = 'L'; alternate5 = 'K' rightArrowAlt5 = 'K'; alternate6 = 'I'; rightArrowAlt6 = 'I'; break; case 'o': text = 'You chose the lower-case letter o.'; alternate1 = '9'; rightArrowAlt1 = '9'; alternate2 = '0'; rightArrowAlt2 = '0'; alternate3 = 'p'; rightArrowAlt3 = 'p'; alternate4 = 'l'; rightArrowAlt4 = 'l'; alternate5 = 'k'; rightArrowAlt5 = 'k'; alternate6 = 'i'; rightArrowAlt6 = 'i'; break; case 'P': text = 'You chose the upper-case letter P.'; alternate1 = '0'; rightArrowAlt1 = '0'; alternate2 = '_'; rightArrowAlt2 = '_'; alternate3 = '{'; rightArrowAlt3 = '{'; alternate4 = ':'; rightArrowAlt4 = ':'; alternate5 = 'L'; rightArrowAlt5 = 'L'; alternate6 = 'O'; rightArrowAlt6 = 'O'; break; case 'p': text = 'You chose the lower-case letter p.'; alternate1 = '0'; rightArrowAlt1 = '0'; alternate2 = '-'; rightArrowAlt2 = '-'; alternate3 = '['; rightArrowAlt3 = '['; alternate4 = ';'; rightArrowAlt4 = ';'; alternate5 = 'l'; rightArrowAlt5 = 'l'; alternate6 = 'o'; rightArrowAlt6 = 'o'; break; case 'Q': text = 'You chose the upper-case letter Q.'; alternate1 = '!'; rightArrowAlt1 = '!'; alternate2 = '@'; rightArrowAlt2 = '@'; alternate3 = 'W'; rightArrowAlt3 = 'W'; alternate4 = 'A'; rightArrowAlt4 = 'A'; alternate5 = 'Caps'; rightArrowAlt5 = 'Caps'; alternate6 = 'Tab'; rightArrowAlt6 = 'Tab'; break; case 'q': text = 'You chose the lower-case letter q.'; alternate1 = '1'; rightArrowAlt1 = '1'; alternate2 = '2'; rightArrowAlt2 = '2'; alternate3 = 'w'; rightArrowAlt3 = 'w'; alternate4 = 'a'; rightArrowAlt4 = 'a'; alternate5 = 'Caps'; rightArrowAlt5 = 'Caps'; alternate6 = 'Tab'; rightArrowAlt6 = 'Tab'; break; case 'R': text = 'You chose the upper-case letter R.'; alternate1 = '$'; rightArrowAlt1 = '$'; alternate2 = '%'; rightArrowAlt2 = '%'; alternate3 = 'T'; rightArrowAlt3 = 'T'; alternate4 = 'F'; rightArrowAlt4 = 'F'; alternate5 = 'D'; rightArrowAlt5 = 'D'; alternate6 = 'E'; rightArrowAlt6 = 'E'; break; case 'r': text = 'You chose the lower-case letter r.'; alternate1 = '4'; rightArrowAlt1 = '4'; alternate2 = '5'; rightArrowAlt2 = '5'; alternate3 = 't'; rightArrowAlt3 = 't'; alternate4 = 'f'; rightArrowAlt4 = 'f'; alternate5 = 'd'; rightArrowAlt5 = 'd'; alternate6 = 'e'; rightArrowAlt6 = 'e'; break; case 'S': text = 'You chose the upper-case letter S.'; alternate1 = 'W'; rightArrowAlt1 = 'W'; alternate2 = 'E'; rightArrowAlt2 = 'E'; alternate3 = 'D'; rightArrowAlt3 = 'D'; alternate4 = 'X'; rightArrowAlt4 = 'X'; alternate5 = 'Z'; rightArrowAlt5 = 'Z'; alternate6 = 'A'; rightArrowAlt6 = 'A'; break; case 's': text = 'You chose the lower-case letter s.'; alternate1 = 'w'; rightArrowAlt1 = 'w'; alternate2 = 'e'; rightArrowAlt2 = 'e'; alternate3 = 'd'; rightArrowAlt3 = 'd'; alternate4 = 'x'; rightArrowAlt4 = 'x'; alternate5 = 'z'; rightArrowAlt5 = 'z'; alternate6 = 'a'; rightArrowAlt6 = 'a'; break; case 'T': text = 'You chose the upper-case letter T.'; alternate1 = '%'; rightArrowAlt1 = '%'; alternate2 = '^'; rightArrowAlt2 = '^'; alternate3 = 'Y'; rightArrowAlt3 = 'Y'; alternate4 = 'G'; rightArrowAlt4 = 'G'; alternate5 = 'F'; rightArrowAlt5 = 'F'; alternate6 = 'R'; rightArrowAlt6 = 'R'; break; case 't': text = 'You chose the lower-case letter t.'; alternate1 = '5'; rightArrowAlt1 = '5'; alternate2 = '6'; rightArrowAlt2 = '6'; alternate3 = 'y'; rightArrowAlt3 = 'y'; alternate4 = 'g'; rightArrowAlt4 = 'g'; alternate5 = 'f'; rightArrowAlt5 = 'f'; alternate6 = 'r'; rightArrowAlt6 = 'r'; break; case 'U': text = 'You chose the upper-case letter U.'; alternate1 = '&'; rightArrowAlt1 = '&'; alternate2 = '*'; rightArrowAlt2 = '*'; alternate3 = 'I'; rightArrowAlt3 = 'I'; alternate4 = 'J'; rightArrowAlt4 = 'J'; alternate5 = 'H'; rightArrowAlt5 = 'H'; alternate6 = 'Y'; rightArrowAlt6 = 'Y'; break; case 'u': text = 'You chose the lower-case letter u.'; alternate1 = '7'; rightArrowAlt1 = '7'; alternate2 = '8'; rightArrowAlt2 = '8'; alternate3 = 'i'; rightArrowAlt3 = 'i'; alternate4 = 'j'; rightArrowAlt4 = 'j'; alternate5 = 'h'; rightArrowAlt5 = 'h'; alternate6 = 'y'; rightArrowAlt6 = 'y'; break; case 'V': text = 'You chose the upper-case letter V.'; alternate1 = 'F'; rightArrowAlt1 = 'F'; alternate2 = 'G'; rightArrowAlt2 = 'G'; alternate3 = 'B'; rightArrowAlt3 = 'B'; alternate4 = 'Spacebar'; rightArrowAlt4 = 'Spacebar'; alternate5 = 'Spacebar'; rightArrowAlt5 = 'Spacebar'; alternate6 = 'C'; rightArrowAlt6 = 'C'; break; case 'v': text = 'You chose the lower-case letter v.'; alternate1 = 'f'; rightArrowAlt1 = 'f'; alternate2 = 'g'; rightArrowAlt2 = 'g'; alternate3 = 'b'; rightArrowAlt3 = 'b'; alternate4 = 'Spacebar'; rightArrowAlt4 = 'Spacebar'; alternate5 = 'Spacebar'; rightArrowAlt5 = 'Spacebar'; alternate6 = 'c'; rightArrowAlt6 = 'c'; break; case 'W': text = 'You chose the upper-case letter W.'; alternate1 = '@'; rightArrowAlt1 = '@'; alternate2 = '#'; rightArrowAlt2 = '#'; alternate3 = 'E'; rightArrowAlt3 = 'E'; alternate4 = 'S'; rightArrowAlt4 = 'S'; alternate5 = 'A'; rightArrowAlt5 = 'A'; alternate6 = 'Q'; rightArrowAlt6 = 'Q'; break; case 'w': text = 'You chose the lower-case letter w.'; alternate1 = '2'; rightArrowAlt1 = '2'; alternate2 = '3'; rightArrowAlt2 = '3'; alternate3 = 'e'; rightArrowAlt3 = 'e'; alternate4 = 's'; rightArrowAlt4 = 's'; alternate5 = 'a'; rightArrowAlt5 = 'a'; alternate6 = 'q'; rightArrowAlt6 = 'q'; break; case 'X': text = 'You chose the upper-case letter X.'; alternate1 = 'S'; rightArrowAlt1 = 'S'; alternate2 = 'D'; rightArrowAlt2 = 'D'; alternate3 = 'C'; rightArrowAlt3 = 'C'; alternate4 = 'Spacebar'; rightArrowAlt4 = 'Spacebar'; alternate5 = 'Alt'; rightArrowAlt5 = 'Alt'; alternate6 = 'Z'; rightArrowAlt6 = 'Z'; break; case 'x': text = 'You chose the lower-case letter x.'; alternate1 = 's'; rightArrowAlt1 = 's'; alternate2 = 'd'; rightArrowAlt2 = 'd'; alternate3 = 'c'; rightArrowAlt3 = 'c'; alternate4 = 'Spacebar'; rightArrowAlt4 = 'Spacebar'; alternate5 = 'Alt'; rightArrowAlt5 = 'Alt'; alternate6 = 'z'; rightArrowAlt6 = 'z'; break; case 'Y': text = 'You chose the upper-case letter Y.'; alternate1 = '^'; rightArrowAlt1 = '^'; alternate2 = '&'; rightArrowAlt2 = '&'; alternate3 = 'U'; rightArrowAlt3 = 'U'; alternate4 = 'H'; rightArrowAlt4 = 'H'; alternate5 = 'G'; rightArrowAlt5 = 'G'; alternate6 = 'T'; rightArrowAlt6 = 'T'; break; case 'y': text = 'You chose the lower-case letter y.'; alternate1 = '6'; rightArrowAlt1 = '6'; alternate2 = '7'; rightArrowAlt2 = '7'; alternate3 = 'u'; rightArrowAlt3 = 'u'; alternate4 = 'h'; rightArrowAlt4 = 'h'; alternate5 = 'g'; rightArrowAlt5 = 'g'; alternate6 = 't'; rightArrowAlt6 = 't'; break; case 'Z': text = 'You chose the upper-case letter Z.'; alternate1 = 'A'; rightArrowAlt1 = 'A'; alternate2 = 'S'; rightArrowAlt2 = 'S'; alternate3 = 'X'; rightArrowAlt3 = 'X'; alternate4 = 'Alt'; rightArrowAlt4 = 'Alt'; alternate5 = 'Special'; rightArrowAlt5 = 'Special'; alternate6 = 'Shift'; rightArrowAlt6 = 'Shift'; break; case 'z': text = 'You chose the lower-case letter z.'; alternate1 = 'a'; rightArrowAlt1 = 'a'; alternate2 = 's'; rightArrowAlt2 = 's'; alternate3 = 'x'; rightArrowAlt3 = 'x'; alternate4 = 'Alt'; rightArrowAlt4 = 'Alt'; alternate5 = 'Special'; rightArrowAlt5 = 'Special'; alternate6 = 'Shift'; rightArrowAlt6 = 'Shift'; break; case '1': text = 'You chose the number 1.'; alternate1 = '`'; rightArrowAlt1 = '`'; alternate2 = '2'; rightArrowAlt2 = '2'; alternate3 = '3'; rightArrowAlt3 = '3'; alternate4 = '4'; rightArrowAlt4 = '4'; alternate5 = '5'; rightArrowAlt5 = '5'; alternate6 = '6'; rightArrowAlt6 = '6'; break; case '2': text = 'You chose the number 2.'; alternate1 = '1'; rightArrowAlt1 = '1'; alternate2 = '3'; rightArrowAlt2 = '3'; alternate3 = '4'; rightArrowAlt3 = '4'; alternate4 = '5'; rightArrowAlt4 = '5'; alternate5 = '6'; rightArrowAlt5 = '6'; alternate6 = '7'; rightArrowAlt6 = '7'; break; case '3': text = 'You chose the number 3.'; alternate1 = '1'; rightArrowAlt1 = '1'; alternate2 = '2'; rightArrowAlt2 = '2'; alternate3 = '4'; rightArrowAlt3 = '4'; alternate4 = '5'; rightArrowAlt4 = '5'; alternate5 = '6'; rightArrowAlt5 = '6'; alternate6 = '7'; rightArrowAlt6 = '7'; break; case '4': text = 'You chose the number 4.'; alternate1 = '1'; rightArrowAlt1 = '1'; alternate2 = '2'; rightArrowAlt2 = '2'; alternate3 = '3'; rightArrowAlt3 = '3'; alternate4 = '5'; rightArrowAlt4 = '5'; alternate5 = '6'; rightArrowAlt5 = '6'; alternate6 = '7'; rightArrowAlt6 = '7'; break; case '5': text = 'You chose the number 5.'; alternate1 = '2'; rightArrowAlt1 = '2'; alternate2 = '3'; rightArrowAlt2 = '3'; alternate3 = '4'; rightArrowAlt3 = '4'; alternate4 = '6'; rightArrowAlt4 = '6'; alternate5 = '7'; rightArrowAlt5 = '7'; alternate6 = '8'; rightArrowAlt6 = '8'; break; case '6': text = 'You chose the number 6.'; alternate1 = '3'; rightArrowAlt1 = '3'; alternate2 = '4'; rightArrowAlt2 = '4'; alternate3 = '5'; rightArrowAlt3 = '5'; alternate4 = '7'; rightArrowAlt4 = '7'; alternate5 = '8'; rightArrowAlt5 = '8'; alternate6 = '9'; rightArrowAlt6 = '9'; break; case '7': text = 'You chose the number 7.'; alternate1 = '4'; rightArrowAlt1 = '4'; alternate2 = '5'; rightArrowAlt2 = '5'; alternate3 = '6'; rightArrowAlt3 = '6'; alternate4 = '8'; rightArrowAlt4 = '8'; alternate5 = '9'; rightArrowAlt5 = '5'; alternate6 = '0'; rightArrowAlt6 = '0'; break; case '8': text = 'You chose the number 8.'; alternate1 = '5'; rightArrowAlt1 = '5'; alternate2 = '6'; rightArrowAlt2 = '6'; alternate3 = '7'; rightArrowAlt3 = '7'; alternate4 = '9'; rightArrowAlt4 = '9'; alternate5 = '0'; rightArrowAlt5 = '0'; alternate6 = '-'; rightArrowAlt6 = '-'; break; case '9': text = 'You chose the number 9.'; alternate1 = '6'; rightArrowAlt1 = '6'; alternate2 = '7'; rightArrowAlt2 = '7'; alternate3 = '8'; rightArrowAlt3 = '8'; alternate4 = '0'; rightArrowAlt4 = '0'; alternate5 = '-'; rightArrowAlt5 = '-'; alternate6 = '='; rightArrowAlt6 = '='; break; case '0': text = 'You chose the number 0.'; alternate1 = '7'; rightArrowAlt1 = '7'; alternate2 = '8'; rightArrowAlt2 = '8'; alternate3 = '9'; rightArrowAlt3 = '9'; alternate4 = '-'; rightArrowAlt4 = '4'; alternate5 = '='; rightArrowAlt5 = '='; alternate6 = ''; rightArrowAlt6 = ''; break; default: text = "To Be Determined"; } //alert(text); //$('#lowv-letter').html($('#lowv-input').val()); $('#lowv-letter').html($('#course-input').val()); $('#lowv-feedback').html(text); $('#selected-letter').html(theLetter); $('#selected-letter').val(theLetter); $('#alternate1').html(alternate1); $('#alternate1').val(alternate1); $('#alternate2').html(alternate2); $('#alternate2').val(alternate2); $('#alternate3').html(alternate3); $('#alternate3').val(alternate3); $('#alternate4').html(alternate4); $('#alternate4').val(alternate4); $('#alternate5').html(alternate5); $('#alternate5').val(alternate5); $('#alternate6').html(alternate6); $('#alternate6').val(alternate6); });//change function //});//right-arrow button //http://api.jquery.com/val/ //http://stackoverflow.com/questions/6891402/delete-last-character-from-input/6891436 //SA 23 May 2017 No longer used but please do not delete below this is used as a model /* jQuery('.letter-button').on('click', function() { $('#course-input').val(function(i,v){ return v.substr(0,(v.length -1)) }); //return false; var caretPos = document.getElementById("course-input").selectionStart; var textAreaTxt = jQuery("#course-input").val(); var txtToAdd = ($(this).val()); jQuery("#course-input").val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos) ); }); */ //SA 23 May 2017 No longer used but please do not delete above this is used as a model //SA 2 May 2017 end add Frechette accessibility initiative /* function alt0() { document.getElementByID('selected-letter').innerHTML = "Selected"; } function alt1() { document.getElementByID('alternate1').innerHTML = "Alternate 1"; } function alt2() { document.getElementByID('alternate2').innerHTML = "Alternate 2"; } function alt3() { document.getElementByID('alternate3').innerHTML = "Alternate 3"; } function alt4() { document.getElementByID('alternate4').innerHTML = "Alternate 4"; } function alt5() { document.getElementByID('alternate5').innerHTML = "Alternate 5"; } function alt6() { document.getElementByID('alternate6').innerHTML = "Alternate 6"; } */ //SA 23 May 2017 start right arrow //https://forum.jquery.com/topic/how-to-make-a-button-disabled-after-3-clicks //var counter = 0; //https://stackoverflow.com/questions/1772179/get-character-value-from-keycode-in-javascript-then-trim //SA 24 2017 commenting out below but want to keep this for reference /* var keyCodes = []; $("#courses-lowvision").click(function() { keyCodes = []; $("#course-input").val(""); $("#key-codes").html("var keyCodes = [ ];"); $("#key-names").html("var keyNames = [ ];"); }); $(document).keydown(function(e) { keyCodes.push(e.which); updateOutput(); }); function updateOutput() { var kC = "var keyCodes = [ "; var kN = "var keyNames = [ "; var len = keyCodes.length; for (var i = 0; i < len; i++) { kC += keyCodes[i]; kN += "'"+keyboardMap[keyCodes[i]]+"'"; if (i !== (len - 1)) { kC += ", "; kN += ", "; } } kC += " ];"; kN += " ];"; $("#key-codes").html(kC); $("#key-names").html(kN); } // names of known key codes (0-255) var keyboardMap = [ "", // [0] "", // [1] "", // [2] "CANCEL", // [3] "", // [4] "", // [5] "HELP", // [6] "", // [7] "BACK_SPACE", // [8] "TAB", // [9] "", // [10] "", // [11] "CLEAR", // [12] "ENTER", // [13] "ENTER_SPECIAL", // [14] "", // [15] "SHIFT", // [16] "CONTROL", // [17] "ALT", // [18] "PAUSE", // [19] "CAPS_LOCK", // [20] "KANA", // [21] "EISU", // [22] "JUNJA", // [23] "FINAL", // [24] "HANJA", // [25] "", // [26] "ESCAPE", // [27] "CONVERT", // [28] "NONCONVERT", // [29] "ACCEPT", // [30] "MODECHANGE", // [31] "SPACE", // [32] "PAGE_UP", // [33] "PAGE_DOWN", // [34] "END", // [35] "HOME", // [36] "LEFT", // [37] "UP", // [38] "RIGHT", // [39] "DOWN", // [40] "SELECT", // [41] "PRINT", // [42] "EXECUTE", // [43] "PRINTSCREEN", // [44] "INSERT", // [45] "DELETE", // [46] "", // [47] "0", // [48] "1", // [49] "2", // [50] "3", // [51] "4", // [52] "5", // [53] "6", // [54] "7", // [55] "8", // [56] "9", // [57] "COLON", // [58] "SEMICOLON", // [59] "LESS_THAN", // [60] "EQUALS", // [61] "GREATER_THAN", // [62] "QUESTION_MARK", // [63] "AT", // [64] "A", // [65] "B", // [66] "C", // [67] "D", // [68] "E", // [69] "F", // [70] "G", // [71] "H", // [72] "I", // [73] "J", // [74] "K", // [75] "L", // [76] "M", // [77] "N", // [78] "O", // [79] "P", // [80] "Q", // [81] "R", // [82] "S", // [83] "T", // [84] "U", // [85] "V", // [86] "W", // [87] "X", // [88] "Y", // [89] "Z", // [90] "OS_KEY", // [91] Windows Key (Windows) or Command Key (Mac) "", // [92] "CONTEXT_MENU", // [93] "", // [94] "SLEEP", // [95] "NUMPAD0", // [96] "NUMPAD1", // [97] "NUMPAD2", // [98] "NUMPAD3", // [99] "NUMPAD4", // [100] "NUMPAD5", // [101] "NUMPAD6", // [102] "NUMPAD7", // [103] "NUMPAD8", // [104] "NUMPAD9", // [105] "MULTIPLY", // [106] "ADD", // [107] "SEPARATOR", // [108] "SUBTRACT", // [109] "DECIMAL", // [110] "DIVIDE", // [111] "F1", // [112] "F2", // [113] "F3", // [114] "F4", // [115] "F5", // [116] "F6", // [117] "F7", // [118] "F8", // [119] "F9", // [120] "F10", // [121] "F11", // [122] "F12", // [123] "F13", // [124] "F14", // [125] "F15", // [126] "F16", // [127] "F17", // [128] "F18", // [129] "F19", // [130] "F20", // [131] "F21", // [132] "F22", // [133] "F23", // [134] "F24", // [135] "", // [136] "", // [137] "", // [138] "", // [139] "", // [140] "", // [141] "", // [142] "", // [143] "NUM_LOCK", // [144] "SCROLL_LOCK", // [145] "WIN_OEM_FJ_JISHO", // [146] "WIN_OEM_FJ_MASSHOU", // [147] "WIN_OEM_FJ_TOUROKU", // [148] "WIN_OEM_FJ_LOYA", // [149] "WIN_OEM_FJ_ROYA", // [150] "", // [151] "", // [152] "", // [153] "", // [154] "", // [155] "", // [156] "", // [157] "", // [158] "", // [159] "CIRCUMFLEX", // [160] "EXCLAMATION", // [161] "DOUBLE_QUOTE", // [162] "HASH", // [163] "DOLLAR", // [164] "PERCENT", // [165] "AMPERSAND", // [166] "UNDERSCORE", // [167] "OPEN_PAREN", // [168] "CLOSE_PAREN", // [169] "ASTERISK", // [170] "PLUS", // [171] "PIPE", // [172] "HYPHEN_MINUS", // [173] "OPEN_CURLY_BRACKET", // [174] "CLOSE_CURLY_BRACKET", // [175] "TILDE", // [176] "", // [177] "", // [178] "", // [179] "", // [180] "VOLUME_MUTE", // [181] "VOLUME_DOWN", // [182] "VOLUME_UP", // [183] "", // [184] "", // [185] "SEMICOLON", // [186] "EQUALS", // [187] "COMMA", // [188] "MINUS", // [189] "PERIOD", // [190] "SLASH", // [191] "BACK_QUOTE", // [192] "", // [193] "", // [194] "", // [195] "", // [196] "", // [197] "", // [198] "", // [199] "", // [200] "", // [201] "", // [202] "", // [203] "", // [204] "", // [205] "", // [206] "", // [207] "", // [208] "", // [209] "", // [210] "", // [211] "", // [212] "", // [213] "", // [214] "", // [215] "", // [216] "", // [217] "", // [218] "OPEN_BRACKET", // [219] "BACK_SLASH", // [220] "CLOSE_BRACKET", // [221] "QUOTE", // [222] "", // [223] "META", // [224] "ALTGR", // [225] "", // [226] "WIN_ICO_HELP", // [227] "WIN_ICO_00", // [228] "", // [229] "WIN_ICO_CLEAR", // [230] "", // [231] "", // [232] "WIN_OEM_RESET", // [233] "WIN_OEM_JUMP", // [234] "WIN_OEM_PA1", // [235] "WIN_OEM_PA2", // [236] "WIN_OEM_PA3", // [237] "WIN_OEM_WSCTRL", // [238] "WIN_OEM_CUSEL", // [239] "WIN_OEM_ATTN", // [240] "WIN_OEM_FINISH", // [241] "WIN_OEM_COPY", // [242] "WIN_OEM_AUTO", // [243] "WIN_OEM_ENLW", // [244] "WIN_OEM_BACKTAB", // [245] "ATTN", // [246] "CRSEL", // [247] "EXSEL", // [248] "EREOF", // [249] "PLAY", // [250] "ZOOM", // [251] "", // [252] "PA1", // [253] "WIN_OEM_CLEAR", // [254] "" // [255] ]; */ /////////////////////////////23 May 2017 end ///////////////////////////////////////////////////////////// });//Do NOT remove this closes document ready
var get = Ember.get; var Person, array; var run = Ember.run; module("unit/record_array - DS.RecordArray", { setup: function() { array = [{ id: '1', name: "Scumbag Dale" }, { id: '2', name: "Scumbag Katz" }, { id: '3', name: "Scumbag Bryn" }]; Person = DS.Model.extend({ name: DS.attr('string') }); } }); test("a record array is backed by records", function() { expect(3); var store = createStore({ person: Person }); run(function() { store.pushMany('person', array); }); run(function() { store.findByIds('person', [1,2,3]).then(function(records) { for (var i=0, l=get(array, 'length'); i<l; i++) { deepEqual(records[i].getProperties('id', 'name'), array[i], "a record array materializes objects on demand"); } }); }); }); test("acts as a live query", function() { var store = createStore({ person: Person }); var recordArray = store.peekAll('person'); run(function() { store.push('person', { id: 1, name: 'wycats' }); }); equal(get(recordArray, 'lastObject.name'), 'wycats'); run(function() { store.push('person', { id: 2, name: 'brohuda' }); }); equal(get(recordArray, 'lastObject.name'), 'brohuda'); }); test("stops updating when destroyed", function() { expect(3); var store = createStore({ person: Person }); // TODO remove once // https://github.com/emberjs/ember.js/commit/c3f13e85a62069295965dd49ca487fe6ddba1188 // is on the release branch var emptyLength = Ember.meta(store).descs ? undefined : 0; var recordArray = store.peekAll('person'); run(function() { store.push('person', { id: 1, name: 'wycats' }); }); run(function() { recordArray.destroy(); }); run(function() { equal(recordArray.get('length'), emptyLength, "Has no more records"); store.push('person', { id: 2, name: 'brohuda' }); }); equal(recordArray.get('length'), emptyLength, "Has not been updated"); equal(recordArray.get('content'), undefined, "Has not been updated"); }); test("a loaded record is removed from a record array when it is deleted", function() { expect(4); var Tag = DS.Model.extend({ people: DS.hasMany('person') }); Person.reopen({ tag: DS.belongsTo('tag') }); var env = setupStore({ tag: Tag, person: Person }); var store = env.store; run(function() { store.pushMany('person', array); store.push('tag', { id: 1 }); }); run(function() { var asyncRecords = Ember.RSVP.hash({ scumbag: store.find('person', 1), tag: store.find('tag', 1) }); asyncRecords.then(function(records) { var scumbag = records.scumbag; var tag = records.tag; run(function() { tag.get('people').addObject(scumbag); }); equal(get(scumbag, 'tag'), tag, "precond - the scumbag's tag has been set"); var recordArray = tag.get('people'); equal(get(recordArray, 'length'), 1, "precond - record array has one item"); equal(get(recordArray.objectAt(0), 'name'), "Scumbag Dale", "item at index 0 is record with id 1"); scumbag.deleteRecord(); equal(get(recordArray, 'length'), 0, "record is removed from the record array"); }); }); }); test("a loaded record is removed from a record array when it is deleted even if the belongsTo side isn't defined", function() { var Tag = DS.Model.extend({ people: DS.hasMany('person') }); var env = setupStore({ tag: Tag, person: Person }); var store = env.store; var scumbag, tag; run(function() { scumbag = store.push('person', { id: 1, name: 'Scumbag Tom' }); tag = store.push('tag', { id: 1, people: [1] }); scumbag.deleteRecord(); }); equal(tag.get('people.length'), 0, "record is removed from the record array"); }); test("a loaded record is removed both from the record array and from the belongs to, even if the belongsTo side isn't defined", function() { var Tag = DS.Model.extend({ people: DS.hasMany('person') }); var Tool = DS.Model.extend({ person: DS.belongsTo('person') }); var env = setupStore({ tag: Tag, person: Person, tool: Tool }); var store = env.store; var scumbag, tag, tool; run(function() { scumbag = store.push('person', { id: 1, name: 'Scumbag Tom' }); tag = store.push('tag', { id: 1, people: [1] }); tool = store.push('tool', { id: 1, person: 1 }); }); equal(tag.get('people.length'), 1, "record is in the record array"); equal(tool.get('person'), scumbag, "the tool belongs to the record"); run(function() { scumbag.deleteRecord(); }); equal(tag.get('people.length'), 0, "record is removed from the record array"); equal(tool.get('person'), null, "the tool is now orphan"); }); // GitHub Issue #168 test("a newly created record is removed from a record array when it is deleted", function() { var store = createStore({ person: Person }); var recordArray = store.peekAll('person'); var scumbag; run(function() { scumbag = store.createRecord('person', { name: "Scumbag Dale" }); }); equal(get(recordArray, 'length'), 1, "precond - record array already has the first created item"); // guarantee coalescence Ember.run(function() { store.createRecord('person', { name: 'p1' }); store.createRecord('person', { name: 'p2' }); store.createRecord('person', { name: 'p3' }); }); equal(get(recordArray, 'length'), 4, "precond - record array has the created item"); equal(get(recordArray.objectAt(0), 'name'), "Scumbag Dale", "item at index 0 is record with id 1"); run(function() { scumbag.deleteRecord(); }); equal(get(recordArray, 'length'), 3, "record is removed from the record array"); run(function() { recordArray.objectAt(0).set('name', 'toto'); }); equal(get(recordArray, 'length'), 3, "record is still removed from the record array"); }); test("a record array returns undefined when asking for a member outside of its content Array's range", function() { var store = createStore({ person: Person }); run(function() { store.pushMany('person', array); }); var recordArray = store.peekAll('person'); strictEqual(recordArray.objectAt(20), undefined, "objects outside of the range just return undefined"); }); // This tests for a bug in the recordCache, where the records were being cached in the incorrect order. test("a record array should be able to be enumerated in any order", function() { var store = createStore({ person: Person }); run(function() { store.pushMany('person', array); }); var recordArray = store.peekAll('person'); equal(get(recordArray.objectAt(2), 'id'), 3, "should retrieve correct record at index 2"); equal(get(recordArray.objectAt(1), 'id'), 2, "should retrieve correct record at index 1"); equal(get(recordArray.objectAt(0), 'id'), 1, "should retrieve correct record at index 0"); }); test("an AdapterPopulatedRecordArray knows if it's loaded or not", function() { expect(1); var env = setupStore({ person: Person }); var store = env.store; env.adapter.findQuery = function(store, type, query, recordArray) { return Ember.RSVP.resolve(array); }; run(function() { store.query('person', { page: 1 }).then(function(people) { equal(get(people, 'isLoaded'), true, "The array is now loaded"); }); }); }); test("a record array should return a promise when updating", function() { var recordArray, promise; var env = setupStore({ person: Person }); var store = env.store; env.adapter.findAll = function(store, type, query, recordArray) { return Ember.RSVP.resolve(array); }; recordArray = store.peekAll('person'); run(function() { promise = recordArray.update(); }); ok(promise.then && typeof promise.then === "function", "#update returns a promise"); });
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S12.11_A3_T2; * @section: 12.11; * @assertion: Syntax constructions of switch statement; * @description: Checking if execution of "switch {}" fails; * @negative; */ function SwitchTest(value){ var result = 0; switch { case 0: result += 2; default: result += 32; break; } return result; } var x = SwitchTest(0);
function BlockSet(blockType) { this.blocks = new Array(); this.blockType = blockType; this.currIndex = 0; this.useHotKeys = true; // HACK: get focus onto something on the page so we can use keyboard shortcuts var dummy = createElement("a"); insertBefore(dummy, document.body.firstChild); dummy.focus(); this.addAllBlocks(document.body); this.setCurrIndex(this.currIndex); } var CLASS = BlockSet.prototype; CLASS.currBlock = function() { return this.blocks[this.currIndex]; } CLASS.addBlock = function(block, refBlock) { // Insert block after refBlock if(!block) return; var i = refBlock ? indexOf(this.blocks, refBlock) : -1; if(i == -1) add(this.blocks, block); else this.blocks.splice(i+1, 0, block); return block; } CLASS.findBlock = function(name) { for(var i = 0; i < this.blocks.length; i++) if(this.blocks[i].name == name) return this.blocks[i]; return null; } CLASS.getBlock = function(type, recycle, block) { if(!type) type = "unknown"; // If recycle, return the block of the given type // If such block doesn't exist, create it if(recycle) { // Find existing one for(var i = 0; i < this.blocks.length; i++) if(this.blocks[i].type == type) return this.blocks[i]; } // Create a new one for(var q = 0; ; q++) { var name = type+(q?q:""); if(!this.findBlock(name)) { if(!block) block = lastInArray(this.blocks); var blockDiv = this.createBlockDivAfter(type, name, block); return this.addBlock(new this.blockType(this, blockDiv), block); } } } CLASS.createBlockDivAfter = function(type, name, block) { // Create a block div after the given block's var blockDiv = createDiv(); blockDiv.setAttribute("id", name+".block"); blockDiv.setAttribute("type", type); insertManyAfter([createElement("p"), blockDiv], block.blockDiv); return blockDiv; } CLASS.addAllBlocks = function(node) { // Find all the blocks under node for(var childNode = node.firstChild; childNode; childNode = childNode.nextSibling) { if(!Block.isBlock(childNode)) continue; var block = new this.blockType(this, childNode); block.prepare(); this.addBlock(block); } } CLASS.setCurrIndex = function(newIndex) { //alert(newIndex + " " + this.currIndex + " " + this.blocks.length); if(newIndex < 0 || newIndex >= this.blocks.length) return; this.blocks[this.currIndex].setSelected(false); this.blocks[newIndex].setSelected(true); this.currIndex = newIndex; } // View the beginning of the current block CLASS.viewBeginCurrBlock = function() { keepCtrlInView(this.currBlock().blockDiv, 0); } CLASS.setCurrBlock = function(block) { for(var i = 0; i < this.blocks.length; i++) if(this.blocks[i] == block) { this.setCurrIndex(i); return; } } CLASS.removeCurrBlock = function() { this.removeBlock(this.currBlock()); } CLASS.removeBlock = function(block) { if(!block) return; block.die(); var index = indexOf(this.blocks, block); this.blocks = removeAt(this.blocks, index); this.currIndex = min(this.blocks.length-1, this.currIndex); this.setCurrIndex(this.currIndex); } CLASS.onKeyPress = function(event) { if(!this.useHotKeys) return false; var hotkey = eventToHotkey(event); if(hotkey == "ctrl-f") { this.setCurrIndex(this.currIndex+1); return true; } else if(hotkey == "ctrl-b") { this.setCurrIndex(this.currIndex-1); return true; } else if(hotkey == "ctrl-shift-d") { this.removeCurrBlock(); return true; } else if(this.currBlock()) { return this.currBlock().onKeyPress(event); // Dispatch to current block } this.viewBeginCurrBlock(); }
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import _extends from "@babel/runtime/helpers/esm/extends"; import * as React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled'; import experimentalStyled from '../styles/experimentalStyled'; import useThemeProps from '../styles/useThemeProps'; import AddIcon from '../internal/svg-icons/Add'; import speedDialIconClasses, { getSpeedDialIconUtilityClass } from './speedDialIconClasses'; import { jsx as _jsx } from "react/jsx-runtime"; import { jsxs as _jsxs } from "react/jsx-runtime"; const useUtilityClasses = styleProps => { const { classes, open, openIcon } = styleProps; const slots = { root: ['root'], icon: ['icon', open && 'iconOpen', openIcon && open && 'iconWithOpenIconOpen'], openIcon: ['openIcon', open && 'openIconOpen'] }; return composeClasses(slots, getSpeedDialIconUtilityClass, classes); }; const SpeedDialIconRoot = experimentalStyled('span', { name: 'MuiSpeedDialIcon', slot: 'Root', overridesResolver: (props, styles) => { const { styleProps } = props; return _extends({ [`& .${speedDialIconClasses.icon}`]: _extends({}, styles.icon, styleProps.open && styles.iconOpen, styleProps.open && styleProps.openIcon && styles.iconWithOpenIconOpen), [`& .${speedDialIconClasses.openIcon}`]: _extends({}, styles.openIcon, styleProps.open && styles.openIconOpen) }, styles.root); } })(({ theme, styleProps }) => ({ height: 24, [`& .${speedDialIconClasses.icon}`]: _extends({ transition: theme.transitions.create(['transform', 'opacity'], { duration: theme.transitions.duration.short }) }, styleProps.open && _extends({ transform: 'rotate(45deg)' }, styleProps.openIcon && { opacity: 0 })), [`& .${speedDialIconClasses.openIcon}`]: _extends({ position: 'absolute', transition: theme.transitions.create(['transform', 'opacity'], { duration: theme.transitions.duration.short }), opacity: 0, transform: 'rotate(-45deg)' }, styleProps.open && { transform: 'rotate(0deg)', opacity: 1 }) })); const SpeedDialIcon = /*#__PURE__*/React.forwardRef(function SpeedDialIcon(inProps, ref) { const props = useThemeProps({ props: inProps, name: 'MuiSpeedDialIcon' }); const { className, icon: iconProp, openIcon: openIconProp } = props, other = _objectWithoutPropertiesLoose(props, ["className", "icon", "open", "openIcon"]); const styleProps = _extends({}, props); const classes = useUtilityClasses(styleProps); function formatIcon(icon, newClassName) { if ( /*#__PURE__*/React.isValidElement(icon)) { return /*#__PURE__*/React.cloneElement(icon, { className: newClassName }); } return icon; } return /*#__PURE__*/_jsxs(SpeedDialIconRoot, _extends({ className: clsx(classes.root, className), ref: ref, styleProps: styleProps }, other, { children: [openIconProp ? formatIcon(openIconProp, classes.openIcon) : null, iconProp ? formatIcon(iconProp, classes.icon) : /*#__PURE__*/_jsx(AddIcon, { className: classes.icon })] })); }); process.env.NODE_ENV !== "production" ? SpeedDialIcon.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * Override or extend the styles applied to the component. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * The icon to display. */ icon: PropTypes.node, /** * @ignore * If `true`, the component is shown. */ open: PropTypes.bool, /** * The icon to display in the SpeedDial Floating Action Button when the SpeedDial is open. */ openIcon: PropTypes.node, /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx: PropTypes.object } : void 0; SpeedDialIcon.muiName = 'SpeedDialIcon'; export default SpeedDialIcon;
/* friendlyDateRanges.js tests */ var test = require('tape'), friendly = require('../friendlyDateRanges'); test('tests', function (t) { t.deepEqual(friendly(['2022-09-05', '2023-09-04']), ['September 5th, 2022','September 4th, 2023']); t.deepEqual(friendly(['2017-01-01', '2017-01-01']), ['January 1st, 2017'], 'since we do not duplicate only return once'); t.deepEqual(friendly(['2016-03-01', '2016-05-05']), ['March 1st','May 5th, 2016']); t.deepEqual(friendly(['2015-12-01', '2017-02-03']), ['December 1st, 2015','February 3rd, 2017']); t.deepEqual(friendly(['2015-12-01', '2016-02-03']), ['December 1st','February 3rd'], 'one month apart can be inferred it is the next year'); t.deepEqual(friendly(['2015-07-01', '2015-07-04']), ['July 1st','4th'], 'ending month should be omitted since it is already mentioned'); t.end(); });
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S11.12_A4_T2; * @section: 11.12; * @assertion: If ToBoolean(x) is true, return y; * @description: Type(y) and Type(z) are number primitives; */ //CHECK#1 if ((1 ? 0 : 1) !== 0) { $ERROR('#1: (1 ? 0 : 1) === 0'); } //CHECK#2 var y = new Number(1); if ((1 ? y : 0) !== y) { $ERROR('#2: (var y = new Number(1); (1 ? y : 0) === y'); } //CHECK#3 var y = new Number(NaN); if ((y ? y : 1) !== y) { $ERROR('#3: (var y = new Number(NaN); (y ? y : 1) === y'); }
const webpack = require('webpack'); const loaders = require("./helpers/webpack.loaders.config"); const preloaders = require("./helpers/webpack.preloaders.config"); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); module.exports = { entry: ['./src/app/app.module.js'], output: { filename: 'build.js', path: './dist' }, resolve: { root: __dirname, extensions: ['', '.js', '.json'] }, resolveLoader: { modulesDirectories: ["node_modules"] }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html', inject: 'body', hash: true }), new CopyWebpackPlugin([{ from: './src/assets/img/', to: 'assets/img/' }]) ], module:{ preloaders: preloaders, loaders: loaders } };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.checkWineVersion = undefined; var _bluebirdLst; function _load_bluebirdLst() { return _bluebirdLst = require("bluebird-lst"); } /** @private */ let checkWineVersion = exports.checkWineVersion = (() => { var _ref2 = (0, (_bluebirdLst || _load_bluebirdLst()).coroutine)(function* (checkPromise) { function wineError(prefix) { return `${prefix}, please see https://electron.build/multi-platform-build#${process.platform === "linux" ? "linux" : "macos"}`; } let wineVersion; try { wineVersion = (yield checkPromise).trim(); } catch (e) { if (e.code === "ENOENT") { throw new Error(wineError("wine is required")); } else { throw new Error(`Cannot check wine version: ${e}`); } } if (wineVersion.startsWith("wine-")) { wineVersion = wineVersion.substring("wine-".length); } const spaceIndex = wineVersion.indexOf(" "); if (spaceIndex > 0) { wineVersion = wineVersion.substring(0, spaceIndex); } const suffixIndex = wineVersion.indexOf("-"); if (suffixIndex > 0) { wineVersion = wineVersion.substring(0, suffixIndex); } if (wineVersion.split(".").length === 2) { wineVersion += ".0"; } if ((_semver || _load_semver()).lt(wineVersion, "1.8.0")) { throw new Error(wineError(`wine 1.8+ is required, but your version is ${wineVersion}`)); } }); return function checkWineVersion(_x2) { return _ref2.apply(this, arguments); }; })(); //# sourceMappingURL=wine.js.map exports.execWine = execWine; exports.prepareWindowsExecutableArgs = prepareWindowsExecutableArgs; var _lazyVal; function _load_lazyVal() { return _lazyVal = require("lazy-val"); } var _path = _interopRequireWildcard(require("path")); var _semver; function _load_semver() { return _semver = _interopRequireWildcard(require("semver")); } var _binDownload; function _load_binDownload() { return _binDownload = require("./binDownload"); } var _bundledTool; function _load_bundledTool() { return _bundledTool = require("./bundledTool"); } var _macosVersion; function _load_macosVersion() { return _macosVersion = require("./macosVersion"); } var _util; function _load_util() { return _util = require("./util"); } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } const wineExecutable = new (_lazyVal || _load_lazyVal()).Lazy((0, (_bluebirdLst || _load_bluebirdLst()).coroutine)(function* () { const isUseSystemWine = (0, (_util || _load_util()).isEnvTrue)(process.env.USE_SYSTEM_WINE); if (isUseSystemWine) { (0, (_util || _load_util()).debug)("Using system wine is forced"); } else if (process.platform === "darwin") { const osVersion = yield (0, (_macosVersion || _load_macosVersion()).getMacOsVersion)(); let version = null; let checksum = null; if ((_semver || _load_semver()).gte(osVersion, "10.13.0")) { version = "2.0.2-mac-10.13"; // noinspection SpellCheckingInspection checksum = "v6r9RSQBAbfvpVQNrEj48X8Cw1181rEGMRatGxSKY5p+7khzzy/0tOdfHGO8cU+GqYvH43FAKMK8p6vUfCqSSA=="; } else if ((_semver || _load_semver()).gte(osVersion, "10.12.0")) { version = "2.0.1-mac-10.12"; // noinspection SpellCheckingInspection checksum = "IvKwDml/Ob0vKfYVxcu92wxUzHu8lTQSjjb8OlCTQ6bdNpVkqw17OM14TPpzGMIgSxfVIrQZhZdCwpkxLyG3mg=="; } if (version != null) { const wineDir = yield (0, (_binDownload || _load_binDownload()).getBinFromGithub)("wine", version, checksum); return { path: _path.join(wineDir, "bin/wine"), env: Object.assign({}, process.env, { WINEDEBUG: "-all,err+all", WINEDLLOVERRIDES: "winemenubuilder.exe=d", WINEPREFIX: _path.join(wineDir, "wine-home"), DYLD_FALLBACK_LIBRARY_PATH: (0, (_bundledTool || _load_bundledTool()).computeEnv)(process.env.DYLD_FALLBACK_LIBRARY_PATH, [_path.join(wineDir, "lib")]) }) }; } } yield checkWineVersion((0, (_util || _load_util()).exec)("wine", ["--version"])); return { path: "wine" }; })); /** @private */ function execWine(file, args) { let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : (_bundledTool || _load_bundledTool()).EXEC_TIMEOUT; if (process.platform === "win32") { return (0, (_util || _load_util()).exec)(file, args, options); } else { return wineExecutable.value.then(wine => (0, (_util || _load_util()).exec)(wine.path, [file].concat(args), wine.env == null ? options : Object.assign({ env: wine.env }, options))); } } /** @private */ function prepareWindowsExecutableArgs(args, exePath) { if (process.platform !== "win32") { args.unshift(exePath); } return args; }
/* * Preloader state * =============== * * Takes care of loading the main game assets, including graphics and sound * effects, while displaying a busy splash screen. */ import assets from '../assets'; export default class Preloader extends Phaser.State { preload() { this.showSplashScreen(); this.load.pack('game', null, assets); } create() { // Here is a good place to initialize plugins dependent of any game asset. // Don't forget to `import` them first. Example: //this.game.myPlugin = this.plugins.add(MyPlugin/*, ... parameters ... */); this.state.start('Game'); } // -------------------------------------------------------------------------- showSplashScreen() { this.add.image(0, 0, 'splash-screen'); this.load.setPreloadSprite(this.add.image(82, 282, 'progress-bar')); } }
var deepEquals = require("assert").deepEqual, CSSwhat = require("../"); var tests = [ ["div", [ [ { type: 'tag', name: 'div' } ] ], "simple tag"], ["*", [ [ { type: 'universal' } ] ], "universal"], //traversal ["div div", [ [ { type: 'tag', name: 'div' }, { type: 'descendant' }, { type: 'tag', name: 'div' } ] ], "descendant"], ["div\t \n \tdiv", [ [ { type: 'tag', name: 'div' }, { type: 'descendant' }, { type: 'tag', name: 'div' } ] ], "descendant /w whitespace"], ["div + div", [ [ { type: 'tag', name: 'div' }, { type: 'adjacent' }, { type: 'tag', name: 'div' } ] ], "adjacent"], ["div ~ div", [ [ { type: 'tag', name: 'div' }, { type: 'sibling' }, { type: 'tag', name: 'div' } ] ], "sibling"], //attributes [".foo", [ [ { type: 'class', value: 'foo' } ] ], "simple class"], ["[name^='foo[']",[[{"type":"attribute","name":"name","action":"start","value":"foo[","ignoreCase":false}]],"escaped attribute"], ["[name^='foo[bar]']",[[{"type":"attribute","name":"name","action":"start","value":"foo[bar]","ignoreCase":false}]],"escaped attribute"], ["[name$='[bar]']",[[{"type":"attribute","name":"name","action":"end","value":"[bar]","ignoreCase":false}]],"escaped attribute"], ["[href *= 'google']",[[{"type":"attribute","name":"href","action":"any","value":"google","ignoreCase":false}]],"escaped attribute"], ["[name=foo\\.baz]",[[{"type":"attribute","name":"name","action":"equals","value":"foo.baz","ignoreCase":false}]],"escaped attribute"], ["[name=foo\\[bar\\]]",[[{"type":"attribute","name":"name","action":"equals","value":"foo[bar]","ignoreCase":false}]],"escaped attribute"], ["[xml\\:test]",[[{"type":"attribute","name":"xml:test","action":"exists","value":"","ignoreCase":false}]],"escaped attribute"] //TODO ]; tests.forEach(function(arr){ arr[0] = CSSwhat(arr[0]); deepEquals.apply(null, arr); console.log(arr[2], "passed"); });
/*! DataTables Bootstrap 3 integration ร‚ยฉ2011-2015 SpryMedia Ltd - datatables.net/license */ (function(c){"function"===typeof define&&define.amd?define(["jquery","datatables.net"],function(a){return c(a,window,document)}):"object"===typeof exports?module.exports=function(a,d){a||(a=window);if(!d||!d.fn.dataTable)d=require("datatables.net")(a,d).$;return c(d,a,a.document)}:c(jQuery,window,document)})(function(c,a,d){var g=c.fn.dataTable;c.extend(!0,g.defaults,{dom:"<'mdl-grid'<'mdl-cell mdl-cell--6-col'l><'mdl-cell mdl-cell--6-col'f>><'mdl-grid dt-table'<'mdl-cell mdl-cell--12-col'tr>><'mdl-grid'<'mdl-cell mdl-cell--4-col'i><'mdl-cell mdl-cell--8-col'p>>", renderer:"material"});c.extend(g.ext.classes,{sWrapper:"dataTables_wrapper form-inline dt-material",sFilterInput:"form-control input-sm",sLengthSelect:"form-control input-sm",sProcessing:"dataTables_processing panel panel-default"});g.ext.renderer.pageButton.material=function(a,h,r,s,i,n){var o=new g.Api(a),l=a.oLanguage.oPaginate,t=a.oLanguage.oAria.paginate||{},f,e,p=0,q=function(d,g){var m,h,j,b,k=function(a){a.preventDefault();!c(a.currentTarget).hasClass("disabled")&&o.page()!=a.data.action&& o.page(a.data.action).draw("page")};m=0;for(h=g.length;m<h;m++)if(b=g[m],c.isArray(b))q(d,b);else{f="";j=!1;switch(b){case "ellipsis":f="&#x2026;";e="disabled";break;case "first":f=l.sFirst;e=b+(0<i?"":" disabled");break;case "previous":f=l.sPrevious;e=b+(0<i?"":" disabled");break;case "next":f=l.sNext;e=b+(i<n-1?"":" disabled");break;case "last":f=l.sLast;e=b+(i<n-1?"":" disabled");break;default:f=b+1,e="",j=i===b}j&&(e+=" mdl-button--raised mdl-button--colored");f&&(j=c("<button>",{"class":"mdl-button "+ e,id:0===r&&"string"===typeof b?a.sTableId+"_"+b:null,"aria-controls":a.sTableId,"aria-label":t[b],"data-dt-idx":p,tabindex:a.iTabIndex,disabled:-1!==e.indexOf("disabled")}).html(f).appendTo(d),a.oApi._fnBindAction(j,{action:b},k),p++)}},k;try{k=c(h).find(d.activeElement).data("dt-idx")}catch(u){}q(c(h).empty().html('<div class="pagination"/>').children(),s);k&&c(h).find("[data-dt-idx="+k+"]").focus()};return g});
'use strict'; const app = require('APP') , debug = require('debug')(`${app.name}:oauth`) , {STRING, JSON} = require('sequelize'); module.exports = db => { const OAuth = db.define('oauths', { uid: STRING, provider: STRING, // OAuth v2 fields accessToken: STRING, refreshToken: STRING, // OAuth v1 fields token: STRING, tokenSecret: STRING, // The whole profile as JSON profileJson: JSON, }, { // Further reading on indexes: // 1. Sequelize and indexes: http://docs.sequelizejs.com/en/2.0/docs/models-definition/#indexes // 2. Postgres documentation: https://www.postgresql.org/docs/9.1/static/indexes.html indexes: [{fields: ['uid'], unique: true}], }); // OAuth.V2 is a default argument for the OAuth.setupStrategy method - it's our callback function that will execute when the user has successfully logged in OAuth.V2 = (accessToken, refreshToken, profile, done) => OAuth.findOrCreate({ where: { provider: profile.provider, uid: profile.id, } }) .spread(oauth => { debug(profile); debug('provider:%s will log in user:{name=%s uid=%s}', profile.provider, profile.displayName, profile.id ); oauth.profileJson = profile; oauth.accessToken = accessToken; // db.Promise.props is a Bluebird.js method; basically like "all" but for an object whose properties might contain promises. // Docs: http://bluebirdjs.com/docs/api/promise.props.html return db.Promise.props({ oauth, user: oauth.getUser(), _saveProfile: oauth.save(), }); }) .then(({ oauth, user }) => user || OAuth.User.create({ name: profile.displayName, }) .then(user => db.Promise.props({ user, _setOauthUser: oauth.setUser(user) })) .then(({user}) => user) ) .then(user => done(null, user)) .catch(done); // setupStrategy is a wrapper around passport.use, and is called in authentication routes in server/auth.js OAuth.setupStrategy = ({ provider, strategy, config, oauth = OAuth.V2, passport }) => { const undefinedKeys = Object.keys(config) .map(k => config[k]) .filter(value => typeof value === 'undefined'); if (undefinedKeys.length) { for (const key in config) { if (!config[key]) debug('provider:%s: needs environment var %s', provider, key); } debug('provider:%s will not initialize', provider); return; } debug('initializing provider:%s', provider); passport.use(new strategy(config, oauth)); }; return OAuth; }; module.exports.associations = (OAuth, {User}) => { // Create a static association between the OAuth and User models. // This lets us refer to OAuth.User above, when we need to create // a user. OAuth.User = User; OAuth.belongsTo(User); };
version https://git-lfs.github.com/spec/v1 oid sha256:0b9064d20bf15213644250009c06870ba3f05cf808535299aa3262698753a950 size 1301
'use strict'; const assert = require('./../../assert'); const common = require('./../../common'); let battle; describe('Grassy Terrain', function () { afterEach(function () { battle.destroy(); }); it('should change the current terrain to Grassy Terrain for five turns', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [{species: "Florges", ability: 'symbiosis', moves: ['mist', 'grassyterrain']}]}); battle.setPlayer('p2', {team: [{species: "Florges", ability: 'symbiosis', moves: ['mist']}]}); battle.makeChoices('move grassyterrain', 'move mist'); assert.ok(battle.field.isTerrain('grassyterrain')); battle.makeChoices('move mist', 'move mist'); assert.ok(battle.field.isTerrain('grassyterrain')); battle.makeChoices('move mist', 'move mist'); assert.ok(battle.field.isTerrain('grassyterrain')); battle.makeChoices('move mist', 'move mist'); assert.ok(battle.field.isTerrain('grassyterrain')); battle.makeChoices('move mist', 'move mist'); assert.ok(battle.field.isTerrain('')); }); it('should halve the base power of Earthquake, Bulldoze, Magnitude', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [{species: "Shaymin", ability: 'naturalcure', moves: ['grassyterrain']}]}); battle.setPlayer('p2', {team: [{species: "Shaymin-Sky", ability: 'serenegrace', moves: ['leechseed']}]}); battle.makeChoices('move grassyterrain', 'move leechseed'); assert.strictEqual(battle.runEvent('BasePower', battle.p2.active[0], battle.p1.active[0], Dex.getMove('earthquake'), 100, true), 50); assert.strictEqual(battle.runEvent('BasePower', battle.p1.active[0], battle.p2.active[0], Dex.getMove('earthquake'), 100, true), 50); assert.strictEqual(battle.runEvent('BasePower', battle.p2.active[0], battle.p1.active[0], Dex.getMove('bulldoze'), 60, true), 30); assert.strictEqual(battle.runEvent('BasePower', battle.p1.active[0], battle.p2.active[0], Dex.getMove('bulldoze'), 60, true), 30); }); it('should increase the base power of Grass-type attacks used by grounded Pokemon', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [{species: "Shaymin", ability: 'naturalcure', moves: ['grassyterrain']}]}); battle.setPlayer('p2', {team: [{species: "Shaymin-Sky", ability: 'serenegrace', moves: ['leechseed']}]}); battle.makeChoices('move grassyterrain', 'move leechseed'); let basePower; let move = Dex.getMove('gigadrain'); basePower = battle.runEvent('BasePower', battle.p1.active[0], battle.p2.active[0], move, move.basePower, true); assert.strictEqual(basePower, battle.modify(move.basePower, 1.5)); basePower = battle.runEvent('BasePower', battle.p2.active[0], battle.p1.active[0], move, move.basePower, true); assert.strictEqual(basePower, move.basePower); }); it('should heal grounded Pokemon by 1/16 of their max HP', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [{species: "Shaymin", ability: 'naturalcure', moves: ['grassyterrain', 'dragonrage']}]}); battle.setPlayer('p2', {team: [{species: "Magneton", ability: 'magnetpull', moves: ['magnetrise', 'dragonrage']}]}); battle.makeChoices('move grassyterrain', 'move magnetrise'); battle.makeChoices('move dragonrage', 'move dragonrage'); assert.strictEqual(battle.p1.active[0].hp, battle.p1.active[0].maxhp - 40 + Math.floor(battle.p1.active[0].maxhp / 16)); assert.strictEqual(battle.p2.active[0].hp, battle.p2.active[0].maxhp - 40); }); it('should not affect Pokemon in a semi-invulnerable state', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [{species: "Smeargle", ability: 'owntempo', moves: ['dragonrage', 'skydrop']}]}); battle.setPlayer('p2', {team: [{species: "Sableye", ability: 'prankster', moves: ['dragonrage', 'grassyterrain']}]}); battle.makeChoices('move dragonrage', 'move dragonrage'); battle.makeChoices('move skydrop', 'move grassyterrain'); assert.strictEqual(battle.p1.active[0].hp, battle.p1.active[0].maxhp - 40); assert.strictEqual(battle.p2.active[0].hp, battle.p2.active[0].maxhp - 40); }); it('should cause Nature Power to become Energy Ball', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [{species: "Whimsicott", ability: 'prankster', moves: ['grassyterrain']}]}); battle.setPlayer('p2', {team: [{species: "Shuckle", ability: 'sturdy', moves: ['naturepower']}]}); battle.makeChoices('move grassyterrain', 'move naturepower'); let resultMove = toID(battle.log[battle.lastMoveLine].split('|')[3]); assert.strictEqual(resultMove, 'energyball'); }); });
/* global console, LAMBDA */ (function() { "use strict"; var L = LAMBDA; var question = {}; var RP14part1 = { init: function() { var vs = "uvxyz"; var maxDepth = 6; var minDepth = 4; // David: all of these helper functions are duplicated in // RP14part2.js. Because... // When I moved them to a separate JS file that I loaded (with // use-require) in both RP14part1.html and RP14part2.html, // OpenDSA did not like it (error on loading the shared JS file) function pickRndCharacter(c,s) { var list = s.split("") .map(function (e,i) { return (e===c ? i : -1) ; }); list = list.filter(function (x) { return x >= 0; }); return list[L.getRnd(0,list.length-1)]; } function findMatchingParen(s,index) { s = s.split(""); var count = 0; for(var i=index+1; i<s.length; i++) { if (s[i] === ')') { if (count === 0) { return i; } else { count--; } } else { if (s[i] === '(') { count++; } } } throw new Error("Could not find closing paren for the one " + "at position " + index + " in " + s); } function removeParenPair(s) { var openParen = pickRndCharacter('(',s); var closeParen = findMatchingParen(s,openParen); return s.substring(0,openParen) + s.substring(openParen+1,closeParen) + s.substring(closeParen+1); } function removeDot(s) { var dot = pickRndCharacter('.',s); return s.substring(0,dot) + " " + s.substring(dot+1); } function addParens(s) { var n = s.length; var closing = n-1; while (s[closing] === ')') { closing--; } var p1 = L.getRnd(0,closing-1); var p2 = L.getRnd(closing+1,n-1); // do not insert in front of a space or a dot if (s[p1] === " " || s[p1] === ".") { p1++; } // do not insert after a lambda if (p1>0 && s[p1-1] === "\u03BB" ) { p1 += 2; } return s.substring(0,p1) + "(" + s.substring(p1,p2) + ")" + s.substring(p2); } function getSyntaxError(minDepth,maxDepth,vs) { var s = L.printExp( L.getRndExp(1,minDepth,maxDepth,vs,"")); var rnd = L.getRnd(1,3); question.answer = "True"; switch (rnd) { case 1: if (s.indexOf('(') !== -1) { s = removeParenPair(s); question.answer = "False"; } // leave s unchanged if it does not contain any parens break; case 2: if (s.indexOf('.') !== -1) { s = removeDot(s); question.answer = "False"; } // leave s unchanged if it does not contain any dot break; case 3: s = addParens(s); question.answer = "False"; break; } return s; }// getSyntaxError function if (L.getRnd(0,1) === 0) { // syntactically correct lambda exp this.expression = L.printExp( L.getRndExp(1,minDepth,maxDepth,vs,"")); this.answer = "True"; } else { this.expression = getSyntaxError(minDepth,maxDepth,vs); this.answer = question.answer; } } //init };// RP14part1 window.RP14part1 = window.RP14part1 || RP14part1; }());
{ "AD" : "ร ยฎย•ร ยฎยฟร ยฎยชร ยฎยฟ", "Africa/Abidjan_Z_abbreviated" : "ร ยฎยร ยฎยตร ยฎยฐร ยฎยฟ ร ยฎย•ร ยฏย‹ร ยฎยธร ยฏยร ยฎยŸร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Abidjan_Z_short" : "GMT", "Africa/Accra_Z_abbreviated" : "ร ยฎย•ร ยฎยพร ยฎยฉร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Accra_Z_short" : "GMT", "Africa/Addis_Ababa_Z_abbreviated" : "ร ยฎยŽร ยฎยคร ยฎยฟร ยฎยฏร ยฏย‹ร ยฎยชร ยฏยร ยฎยชร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Addis_Ababa_Z_short" : "EAT", "Africa/Algiers_Z_abbreviated" : "ร ยฎย…ร ยฎยฒร ยฏยร ยฎยœร ยฏย€ร ยฎยฐร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Algiers_Z_short" : "WET", "Africa/Asmara_Z_abbreviated" : "ร ยฎยŽร ยฎยฐร ยฎยฟร ยฎยŸร ยฏยร ยฎยฐร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Asmara_Z_short" : "EAT", "Africa/Bamako_Z_abbreviated" : "ร ยฎยฎร ยฎยพร ยฎยฒร ยฏย€ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Bamako_Z_short" : "GMT", "Africa/Bangui_Z_abbreviated" : "ร ยฎยฎร ยฎยคร ยฏยร ยฎยคร ยฎยฟร ยฎยฏ ร ยฎย†ร ยฎยชร ยฏยร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย•ร ยฎย•ร ยฏย ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Bangui_Z_short" : "WAT", "Africa/Banjul_Z_abbreviated" : "ร ยฎย•ร ยฎยพร ยฎยฎร ยฏยร ยฎยชร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Banjul_Z_short" : "GMT", "Africa/Bissau_Z_abbreviated" : "ร ยฎย•ร ยฎยฟร ยฎยฉร ยฎยฟ-ร ยฎยชร ยฎยฟร ยฎยธร ยฏยร ยฎยธร ยฎยพร ยฎยตร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Bissau_Z_short" : "GMT-01:00", "Africa/Blantyre_Z_abbreviated" : "ร ยฎยฎร ยฎยพร ยฎยฒร ยฎยตร ยฎยฟ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Blantyre_Z_short" : "CAT", "Africa/Brazzaville_Z_abbreviated" : "ร ยฎย•ร ยฎยพร ยฎย™ร ยฏยร ยฎย•ร ยฏย‹ - ร ยฎยชร ยฏยร ยฎยฐร ยฎยพร ยฎยธร ยฎยพร ยฎยตร ยฎยฟร ยฎยฒร ยฏยร ยฎยฒร ยฏย‡ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Brazzaville_Z_short" : "WAT", "Africa/Bujumbura_Z_abbreviated" : "ร ยฎยชร ยฏยร ยฎยฐร ยฏยร ยฎยฃร ยฏยร ยฎยŸร ยฎยฟ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Bujumbura_Z_short" : "CAT", "Africa/Cairo_Z_abbreviated" : "ร ยฎยŽร ยฎย•ร ยฎยฟร ยฎยชร ยฏยร ยฎยคร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Cairo_Z_short" : "EET", "Africa/Casablanca_Z_abbreviated" : "ร ยฎยฎร ยฏยŠร ยฎยฐร ยฎยพร ยฎย•ร ยฏยร ยฎย•ร ยฏย‹ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Casablanca_Z_short" : "WET", "Africa/Conakry_Z_abbreviated" : "ร ยฎย•ร ยฎยฟร ยฎยฉร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Conakry_Z_short" : "GMT", "Africa/Dakar_Z_abbreviated" : "ร ยฎยšร ยฏย†ร ยฎยฉร ยฏย†ร ยฎย•ร ยฎยฒร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Dakar_Z_short" : "GMT", "Africa/Dar_es_Salaam_Z_abbreviated" : "ร ยฎยŸร ยฎยพร ยฎยฉร ยฏยร ยฎยšร ยฎยพร ยฎยฉร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Dar_es_Salaam_Z_short" : "EAT", "Africa/Djibouti_Z_abbreviated" : "ร ยฎยœร ยฎยฟร ยฎยชร ยฏยŒร ยฎยŸร ยฏยร ยฎยŸร ยฎยฟ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Djibouti_Z_short" : "EAT", "Africa/Douala_Z_abbreviated" : "ร ยฎย•ร ยฏย‡ร ยฎยฎร ยฎยฐร ยฏย‚ร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Douala_Z_short" : "WAT", "Africa/El_Aaiun_Z_abbreviated" : "ร ยฎยฎร ยฏย‡ร ยฎยฑร ยฏยร ยฎย•ร ยฏย ร ยฎยšร ยฎยนร ยฎยพร ยฎยฐร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/El_Aaiun_Z_short" : "GMT-01:00", "Africa/Freetown_Z_abbreviated" : "ร ยฎยšร ยฎยฟร ยฎยฏร ยฎยฐร ยฏยร ยฎยฐร ยฎยพ ร ยฎยฒร ยฎยฟร ยฎยฏร ยฏย‹ร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Freetown_Z_short" : "GMT", "Africa/Gaborone_Z_abbreviated" : "ร ยฎยชร ยฏย‹ร ยฎยŸร ยฏยร ยฎยธร ยฏยร ยฎยตร ยฎยพร ยฎยฉร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Gaborone_Z_short" : "CAT", "Africa/Harare_Z_abbreviated" : "ร ยฎยœร ยฎยฟร ยฎยฎร ยฏยร ยฎยชร ยฎยพร ยฎยชร ยฏยร ยฎยตร ยฏย‡ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Harare_Z_short" : "CAT", "Africa/Johannesburg_Z_abbreviated" : "ร ยฎยคร ยฏย†ร ยฎยฉร ยฏย ร ยฎย†ร ยฎยชร ยฏยร ยฎยชร ยฎยฟร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย•ร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Johannesburg_Z_short" : "SAST", "Africa/Juba_Z_abbreviated" : "ร ยฎยšร ยฏย‚ร ยฎยŸร ยฎยพร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Juba_Z_short" : "CAT", "Africa/Kampala_Z_abbreviated" : "ร ยฎย‰ร ยฎย•ร ยฎยพร ยฎยฃร ยฏยร ยฎยŸร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Kampala_Z_short" : "EAT", "Africa/Khartoum_Z_abbreviated" : "ร ยฎยšร ยฏย‚ร ยฎยŸร ยฎยพร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Khartoum_Z_short" : "CAT", "Africa/Kigali_Z_abbreviated" : "ร ยฎยฐร ยฏยร ยฎยตร ยฎยพร ยฎยฉร ยฏยร ยฎยŸร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Kigali_Z_short" : "CAT", "Africa/Kinshasa_Z_abbreviated" : "ร ยฎย•ร ยฎยพร ยฎย™ร ยฏยร ยฎย•ร ยฏย‹ - ร ยฎย•ร ยฎยฟร ยฎยฉร ยฏยร ยฎยทร ยฎยพร ยฎยšร ยฎยพ (Kinshasa)", "Africa/Kinshasa_Z_short" : "WAT", "Africa/Lagos_Z_abbreviated" : "ร ยฎยจร ยฏยˆร ยฎยœร ยฏย€ร ยฎยฐร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Lagos_Z_short" : "WAT", "Africa/Libreville_Z_abbreviated" : "ร ยฎย•ร ยฏย‡ร ยฎยชร ยฎยพร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Libreville_Z_short" : "WAT", "Africa/Lome_Z_abbreviated" : "ร ยฎยŸร ยฏย‹ร ยฎย•ร ยฏย‹ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Lome_Z_short" : "GMT", "Africa/Luanda_Z_abbreviated" : "ร ยฎย…ร ยฎย™ร ยฏยร ยฎย•ร ยฏย‹ร ยฎยฒร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Luanda_Z_short" : "WAT", "Africa/Lusaka_Z_abbreviated" : "ร ยฎยšร ยฎยพร ยฎยฎร ยฏยร ยฎยชร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Lusaka_Z_short" : "CAT", "Africa/Malabo_Z_abbreviated" : "ร ยฎยˆร ยฎย•ร ยฏยร ยฎย•ร ยฏยร ยฎยตร ยฎยพร ยฎยŸร ยฏย‹ร ยฎยฐร ยฎยฟร ยฎยฏร ยฎยฒร ยฏย ร ยฎย•ร ยฎยฟร ยฎยฉร ยฎยฟ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Malabo_Z_short" : "WAT", "Africa/Maputo_Z_abbreviated" : "ร ยฎยฎร ยฏยŠร ยฎยšร ยฎยพร ยฎยฎร ยฏยร ยฎยชร ยฎยฟร ยฎย•ร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Maputo_Z_short" : "CAT", "Africa/Maseru_Z_abbreviated" : "ร ยฎยฒร ยฏย†ร ยฎยšร ยฏย‹ร ยฎยคร ยฏย‹ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Maseru_Z_short" : "SAST", "Africa/Mbabane_Z_abbreviated" : "ร ยฎยธร ยฏยร ยฎยตร ยฎยพร ยฎยธร ยฎยฟร ยฎยฒร ยฎยพร ยฎยฃร ยฏยร ยฎยŸร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Mbabane_Z_short" : "SAST", "Africa/Mogadishu_Z_abbreviated" : "ร ยฎยšร ยฏยŠร ยฎยฎร ยฎยพร ยฎยฒร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Mogadishu_Z_short" : "EAT", "Africa/Monrovia_Z_abbreviated" : "ร ยฎยฒร ยฏยˆร ยฎยชร ยฏย€ร ยฎยฐร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Monrovia_Z_short" : "GMT-00:44:30", "Africa/Nairobi_Z_abbreviated" : "ร ยฎย•ร ยฏย†ร ยฎยฉร ยฏยร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Nairobi_Z_short" : "EAT", "Africa/Ndjamena_Z_abbreviated" : "ร ยฎยšร ยฎยพร ยฎยŸร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Ndjamena_Z_short" : "WAT", "Africa/Niamey_Z_abbreviated" : "ร ยฎยจร ยฏยˆร ยฎยœร ยฎยฐร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Niamey_Z_short" : "WAT", "Africa/Nouakchott_Z_abbreviated" : "ร ยฎยฎร ยฏยŒร ยฎยฐร ยฎยฟร ยฎยŸร ยฎยพร ยฎยฉร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Nouakchott_Z_short" : "GMT", "Africa/Ouagadougou_Z_abbreviated" : "ร ยฎยชร ยฏยร ยฎยฐร ยฏยร ยฎย•ร ยฎยฟร ยฎยฉร ยฎยพ ร ยฎยƒร ยฎยชร ยฎยพร ยฎยธร ยฏย‹ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Ouagadougou_Z_short" : "GMT", "Africa/Porto-Novo_Z_abbreviated" : "ร ยฎยชร ยฏย†ร ยฎยฉร ยฎยฟร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Porto-Novo_Z_short" : "WAT", "Africa/Sao_Tome_Z_abbreviated" : "ร ยฎยšร ยฎยพร ยฎยตร ยฏย ร ยฎยคร ยฏย‹ร ยฎยฎร ยฏย ร ยฎยฎร ยฎยฑร ยฏยร ยฎยฑร ยฏยร ยฎยฎร ยฏย ร ยฎยชร ยฏยร ยฎยฐร ยฎยฟร ยฎยฉร ยฏยร ยฎยšร ยฎยฟร ยฎยชร ยฎยฟ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Sao_Tome_Z_short" : "GMT", "Africa/Tripoli_Z_abbreviated" : "ร ยฎยฒร ยฎยฟร ยฎยชร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Tripoli_Z_short" : "EET", "Africa/Tunis_Z_abbreviated" : "ร ยฎยŸร ยฏยร ยฎยฉร ยฎยฟร ยฎยšร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Tunis_Z_short" : "CET", "Africa/Windhoek_Z_abbreviated" : "ร ยฎยจร ยฎยฎร ยฏย€ร ยฎยชร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Africa/Windhoek_Z_short" : "SAST", "America/Anguilla_Z_abbreviated" : "ร ยฎย…ร ยฎย™ร ยฏยร ยฎย•ร ยฏยร ยฎยฏร ยฏยร ยฎยฒร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Anguilla_Z_short" : "AST", "America/Antigua_Z_abbreviated" : "ร ยฎย†ร ยฎยฃร ยฏยร ยฎยŸร ยฎยฟร ยฎย•ร ยฏยร ยฎยตร ยฎยพ ร ยฎยฎร ยฎยฑร ยฏยร ยฎยฑร ยฏยร ยฎยฎร ยฏย ร ยฎยชร ยฎยพร ยฎยฐร ยฏยร ยฎยชร ยฏยร ยฎยŸร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Antigua_Z_short" : "AST", "America/Araguaina_Z_abbreviated" : "ร ยฎยชร ยฎยฟร ยฎยฐร ยฏย‡ร ยฎยธร ยฎยฟร ยฎยฒร ยฏย (Araguaina)", "America/Araguaina_Z_short" : "BRT", "America/Argentina/Buenos_Aires_Z_abbreviated" : "ร ยฎย…ร ยฎยฐร ยฏยร ยฎยœร ยฏย†ร ยฎยฉร ยฏยร ยฎยŸร ยฎยฟร ยฎยฉร ยฎยพ (Buenos Aires)", "America/Argentina/Buenos_Aires_Z_short" : "ART", "America/Argentina/Catamarca_Z_abbreviated" : "ร ยฎย…ร ยฎยฐร ยฏยร ยฎยœร ยฏย†ร ยฎยฉร ยฏยร ยฎยŸร ยฎยฟร ยฎยฉร ยฎยพ (Catamarca)", "America/Argentina/Catamarca_Z_short" : "ART", "America/Argentina/Cordoba_Z_abbreviated" : "ร ยฎย…ร ยฎยฐร ยฏยร ยฎยœร ยฏย†ร ยฎยฉร ยฏยร ยฎยŸร ยฎยฟร ยฎยฉร ยฎยพ (Cordoba)", "America/Argentina/Cordoba_Z_short" : "ART", "America/Argentina/Jujuy_Z_abbreviated" : "ร ยฎย…ร ยฎยฐร ยฏยร ยฎยœร ยฏย†ร ยฎยฉร ยฏยร ยฎยŸร ยฎยฟร ยฎยฉร ยฎยพ (Jujuy)", "America/Argentina/Jujuy_Z_short" : "ART", "America/Argentina/La_Rioja_Z_abbreviated" : "ร ยฎย…ร ยฎยฐร ยฏยร ยฎยœร ยฏย†ร ยฎยฉร ยฏยร ยฎยŸร ยฎยฟร ยฎยฉร ยฎยพ (La Rioja)", "America/Argentina/La_Rioja_Z_short" : "ART", "America/Argentina/Mendoza_Z_abbreviated" : "ร ยฎย…ร ยฎยฐร ยฏยร ยฎยœร ยฏย†ร ยฎยฉร ยฏยร ยฎยŸร ยฎยฟร ยฎยฉร ยฎยพ (Mendoza)", "America/Argentina/Mendoza_Z_short" : "ART", "America/Argentina/Rio_Gallegos_Z_abbreviated" : "ร ยฎย…ร ยฎยฐร ยฏยร ยฎยœร ยฏย†ร ยฎยฉร ยฏยร ยฎยŸร ยฎยฟร ยฎยฉร ยฎยพ (Rio Gallegos)", "America/Argentina/Rio_Gallegos_Z_short" : "ART", "America/Argentina/Salta_Z_abbreviated" : "ร ยฎย…ร ยฎยฐร ยฏยร ยฎยœร ยฏย†ร ยฎยฉร ยฏยร ยฎยŸร ยฎยฟร ยฎยฉร ยฎยพ (Salta)", "America/Argentina/Salta_Z_short" : "ART", "America/Argentina/San_Juan_Z_abbreviated" : "ร ยฎย…ร ยฎยฐร ยฏยร ยฎยœร ยฏย†ร ยฎยฉร ยฏยร ยฎยŸร ยฎยฟร ยฎยฉร ยฎยพ (San Juan)", "America/Argentina/San_Juan_Z_short" : "ART", "America/Argentina/San_Luis_Z_abbreviated" : "ร ยฎย…ร ยฎยฐร ยฏยร ยฎยœร ยฏย†ร ยฎยฉร ยฏยร ยฎยŸร ยฎยฟร ยฎยฉร ยฎยพ (San Luis)", "America/Argentina/San_Luis_Z_short" : "ART", "America/Argentina/Tucuman_Z_abbreviated" : "ร ยฎย…ร ยฎยฐร ยฏยร ยฎยœร ยฏย†ร ยฎยฉร ยฏยร ยฎยŸร ยฎยฟร ยฎยฉร ยฎยพ (Tucuman)", "America/Argentina/Tucuman_Z_short" : "ART", "America/Argentina/Ushuaia_Z_abbreviated" : "ร ยฎย…ร ยฎยฐร ยฏยร ยฎยœร ยฏย†ร ยฎยฉร ยฏยร ยฎยŸร ยฎยฟร ยฎยฉร ยฎยพ (Ushuaia)", "America/Argentina/Ushuaia_Z_short" : "ART", "America/Aruba_Z_abbreviated" : "ร ยฎย…ร ยฎยฐร ยฏย‚ร ยฎยชร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Aruba_Z_short" : "AST", "America/Asuncion_Z_abbreviated" : "ร ยฎยชร ยฎยพร ยฎยฐร ยฎย•ร ยฏยร ยฎยตร ยฏย‡ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Asuncion_Z_short" : "PYT", "America/Bahia_Banderas_Z_abbreviated" : "ร ยฎยฎร ยฏย†ร ยฎย•ร ยฏยร ยฎยšร ยฎยฟร ยฎย•ร ยฏย‹ (Bahia Banderas)", "America/Bahia_Banderas_Z_short" : "PST", "America/Bahia_Z_abbreviated" : "ร ยฎยชร ยฎยฟร ยฎยฐร ยฏย‡ร ยฎยธร ยฎยฟร ยฎยฒร ยฏย (Bahia)", "America/Bahia_Z_short" : "BRT", "America/Barbados_Z_abbreviated" : "ร ยฎยชร ยฎยพร ยฎยฐร ยฏยร ยฎยชร ยฎยŸร ยฏย‹ร ยฎยธร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Barbados_Z_short" : "AST", "America/Belem_Z_abbreviated" : "ร ยฎยชร ยฎยฟร ยฎยฐร ยฏย‡ร ยฎยธร ยฎยฟร ยฎยฒร ยฏย (Belem)", "America/Belem_Z_short" : "BRT", "America/Belize_Z_abbreviated" : "ร ยฎยชร ยฏย†ร ยฎยฒร ยฎยฟร ยฎยธร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Belize_Z_short" : "CST", "America/Blanc-Sablon_Z_abbreviated" : "ร ยฎย•ร ยฎยฉร ยฎยŸร ยฎยพ (Blanc-Sablon)", "America/Blanc-Sablon_Z_short" : "AST", "America/Boa_Vista_Z_abbreviated" : "ร ยฎยชร ยฎยฟร ยฎยฐร ยฏย‡ร ยฎยธร ยฎยฟร ยฎยฒร ยฏย (Boa Vista)", "America/Boa_Vista_Z_short" : "AMT", "America/Bogota_Z_abbreviated" : "ร ยฎย•ร ยฏยŠร ยฎยฒร ยฎยฎร ยฏยร ยฎยชร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Bogota_Z_short" : "COT", "America/Boise_Z_abbreviated" : "ร ยฎยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยฎร ยฏย†ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย• ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย (Boise)", "America/Boise_Z_short" : "MST", "America/Cambridge_Bay_Z_abbreviated" : "ร ยฎย•ร ยฎยฉร ยฎยŸร ยฎยพ (ร ยฎย•ร ยฏย‡ร ยฎยฎร ยฏยร ยฎยชร ยฎยฟร ยฎยฐร ยฎยฟร ยฎยŸร ยฏยร ยฎยœร ยฏย ร ยฎยชร ยฏย‡)", "America/Cambridge_Bay_Z_short" : "MST", "America/Campo_Grande_Z_abbreviated" : "ร ยฎยชร ยฎยฟร ยฎยฐร ยฏย‡ร ยฎยธร ยฎยฟร ยฎยฒร ยฏย (ร ยฎย•ร ยฏย‡ร ยฎยฎร ยฏยร ยฎยชร ยฏย‹ ร ยฎย•ร ยฎยฟร ยฎยฐร ยฎยพร ยฎยฃร ยฏยร ยฎยŸร ยฏย‡)", "America/Campo_Grande_Z_short" : "AMT", "America/Cancun_Z_abbreviated" : "ร ยฎยฎร ยฏย†ร ยฎย•ร ยฏยร ยฎยšร ยฎยฟร ยฎย•ร ยฏย‹ (Cancun)", "America/Cancun_Z_short" : "CST", "America/Caracas_Z_abbreviated" : "ร ยฎยตร ยฏย†ร ยฎยฉร ยฎยœร ยฏยร ยฎยตร ยฏย‡ร ยฎยฒร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Caracas_Z_short" : "VET", "America/Cayenne_Z_abbreviated" : "ร ยฎยƒร ยฎยชร ยฏยร ยฎยฐร ยฏย†ร ยฎยฉร ยฏยร ยฎยšร ยฏย ร ยฎย•ร ยฎยฏร ยฎยพร ยฎยฉร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Cayenne_Z_short" : "GFT", "America/Cayman_Z_abbreviated" : "ร ยฎย•ร ยฏย‡ร ยฎยฎร ยฏย†ร ยฎยฉร ยฏย ร ยฎยคร ยฏย€ร ยฎยตร ยฏยร ยฎย•ร ยฎยณร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Cayman_Z_short" : "EST", "America/Chicago_Z_abbreviated" : "ร ยฎยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยฎร ยฏย†ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย• ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย (ร ยฎยšร ยฎยฟร ยฎย•ร ยฎยพร ยฎย•ร ยฏย‹)", "America/Chicago_Z_short" : "CST", "America/Chihuahua_Z_abbreviated" : "ร ยฎยฎร ยฏย†ร ยฎย•ร ยฏยร ยฎยšร ยฎยฟร ยฎย•ร ยฏย‹ (Chihuahua)", "America/Chihuahua_Z_short" : "CST", "America/Costa_Rica_Z_abbreviated" : "ร ยฎย•ร ยฏย‹ร ยฎยธร ยฏยร ยฎยŸร ยฎยพร ยฎยฐร ยฎยฟร ยฎย•ร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Costa_Rica_Z_short" : "CST", "America/Cuiaba_Z_abbreviated" : "ร ยฎยชร ยฎยฟร ยฎยฐร ยฏย‡ร ยฎยธร ยฎยฟร ยฎยฒร ยฏย (Cuiaba)", "America/Cuiaba_Z_short" : "AMT", "America/Curacao_Z_abbreviated" : "ร ยฎยจร ยฏย†ร ยฎยคร ยฎยฐร ยฏยร ยฎยฒร ยฎยพร ยฎยจร ยฏยร ยฎยคร ยฏย ร ยฎย†ร ยฎยฃร ยฏยร ยฎยŸร ยฎยฟร ยฎยฒร ยฏยร ยฎยฒร ยฏย†ร ยฎยธร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Curacao_Z_short" : "AST", "America/Danmarkshavn_Z_abbreviated" : "ร ยฎย•ร ยฎยฟร ยฎยฐร ยฏย€ร ยฎยฉร ยฏยร ยฎยฒร ยฎยพร ยฎยจร ยฏยร ยฎยคร ยฏย (Danmarkshavn)", "America/Danmarkshavn_Z_short" : "WGT", "America/Denver_Z_abbreviated" : "ร ยฎยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยฎร ยฏย†ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย• ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย (ร ยฎยคร ยฏย‡ร ยฎยฉร ยฏยร ยฎยตร ยฎยฐร ยฏย)", "America/Denver_Z_short" : "MST", "America/Detroit_Z_abbreviated" : "ร ยฎยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยฎร ยฏย†ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย• ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย (Detroit)", "America/Detroit_Z_short" : "EST", "America/Dominica_Z_abbreviated" : "ร ยฎยŸร ยฏยŠร ยฎยฎร ยฎยฟร ยฎยฉร ยฎยฟร ยฎย•ร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Dominica_Z_short" : "AST", "America/Edmonton_Z_abbreviated" : "ร ยฎย•ร ยฎยฉร ยฎยŸร ยฎยพ (Edmonton)", "America/Edmonton_Z_short" : "MST", "America/Eirunepe_Z_abbreviated" : "ร ยฎยชร ยฎยฟร ยฎยฐร ยฏย‡ร ยฎยธร ยฎยฟร ยฎยฒร ยฏย (Eirunepe)", "America/Eirunepe_Z_short" : "ACT (Acre)", "America/El_Salvador_Z_abbreviated" : "ร ยฎยŽร ยฎยฒร ยฏย ร ยฎยšร ยฎยพร ยฎยฒร ยฏยร ยฎยตร ยฎยŸร ยฎยพร ยฎยฐร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/El_Salvador_Z_short" : "CST", "America/Fortaleza_Z_abbreviated" : "ร ยฎยชร ยฎยฟร ยฎยฐร ยฏย‡ร ยฎยธร ยฎยฟร ยฎยฒร ยฏย (Fortaleza)", "America/Fortaleza_Z_short" : "BRT", "America/Goose_Bay_Z_abbreviated" : "ร ยฎย•ร ยฎยฉร ยฎยŸร ยฎยพ (Goose Bay)", "America/Goose_Bay_Z_short" : "AST", "America/Grand_Turk_Z_abbreviated" : "ร ยฎยŸร ยฎยฐร ยฏยร ยฎย•ร ยฏยร ยฎยธร ยฏย ร ยฎยฎร ยฎยฑร ยฏยร ยฎยฑร ยฏยร ยฎยฎร ยฏย ร ยฎย•ร ยฏยˆร ยฎย•ร ยฏย‹ร ยฎยธร ยฏย ร ยฎยคร ยฏย€ร ยฎยตร ยฏยร ยฎย•ร ยฎยณร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Grand_Turk_Z_short" : "EST", "America/Grenada_Z_abbreviated" : "ร ยฎย•ร ยฎยฟร ยฎยฐร ยฎยฉร ยฏย†ร ยฎยŸร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Grenada_Z_short" : "AST", "America/Guadeloupe_Z_abbreviated" : "ร ยฎย•ร ยฏยร ยฎยตร ยฎยพร ยฎยคร ยฏย‡ร ยฎยฒร ยฏย‹ร ยฎยชร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Guadeloupe_Z_short" : "AST", "America/Guatemala_Z_abbreviated" : "ร ยฎย•ร ยฏยร ยฎยตร ยฎยพร ยฎยคร ยฏยร ยฎยคร ยฎยพร ยฎยฎร ยฎยพร ยฎยฒร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Guatemala_Z_short" : "CST", "America/Guayaquil_Z_abbreviated" : "ร ยฎยˆร ยฎย•ร ยฏยร ยฎยตร ยฎยŸร ยฎยพร ยฎยฐร ยฏย (Guayaquil)", "America/Guayaquil_Z_short" : "ECT", "America/Guyana_Z_abbreviated" : "ร ยฎย•ร ยฎยฏร ยฎยพร ยฎยฉร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Guyana_Z_short" : "GYT", "America/Halifax_Z_abbreviated" : "ร ยฎย•ร ยฎยฉร ยฎยŸร ยฎยพ (Halifax)", "America/Halifax_Z_short" : "AST", "America/Havana_Z_abbreviated" : "ร ยฎย•ร ยฎยฟร ยฎยฏร ยฏย‚ร ยฎยชร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Havana_Z_short" : "CST (CU)", "America/Hermosillo_Z_abbreviated" : "ร ยฎยฎร ยฏย†ร ยฎย•ร ยฏยร ยฎยšร ยฎยฟร ยฎย•ร ยฏย‹ (Hermosillo)", "America/Hermosillo_Z_short" : "PST", "America/Indiana/Indianapolis_Z_abbreviated" : "ร ยฎยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยฎร ยฏย†ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย• ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย (ร ยฎย‡ร ยฎยจร ยฏยร ยฎยคร ยฎยฟร ยฎยฏร ยฎยพร ยฎยฉร ยฎยพร ยฎยชร ยฏย‹ร ยฎยฒร ยฎยฟร ยฎยธร ยฏย)", "America/Indiana/Indianapolis_Z_short" : "EST", "America/Indiana/Knox_Z_abbreviated" : "ร ยฎยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยฎร ยฏย†ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย• ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย (Knox, Indiana)", "America/Indiana/Knox_Z_short" : "CST", "America/Indiana/Marengo_Z_abbreviated" : "ร ยฎยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยฎร ยฏย†ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย• ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย (Marengo, Indiana)", "America/Indiana/Marengo_Z_short" : "EST", "America/Indiana/Petersburg_Z_abbreviated" : "ร ยฎยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยฎร ยฏย†ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย• ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย (Petersburg, Indiana)", "America/Indiana/Petersburg_Z_short" : "CST", "America/Indiana/Tell_City_Z_abbreviated" : "ร ยฎยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยฎร ยฏย†ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย• ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย (Tell City, Indiana)", "America/Indiana/Tell_City_Z_short" : "EST", "America/Indiana/Vevay_Z_abbreviated" : "ร ยฎยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยฎร ยฏย†ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย• ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย (Vevay, Indiana)", "America/Indiana/Vevay_Z_short" : "EST", "America/Indiana/Vincennes_Z_abbreviated" : "ร ยฎยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยฎร ยฏย†ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย• ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย (Vincennes, Indiana)", "America/Indiana/Vincennes_Z_short" : "EST", "America/Indiana/Winamac_Z_abbreviated" : "ร ยฎยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยฎร ยฏย†ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย• ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย (Winamac, Indiana)", "America/Indiana/Winamac_Z_short" : "EST", "America/Iqaluit_Z_abbreviated" : "ร ยฎย•ร ยฎยฉร ยฎยŸร ยฎยพ (Iqaluit)", "America/Iqaluit_Z_short" : "EST", "America/Jamaica_Z_abbreviated" : "ร ยฎยœร ยฎยฎร ยฏยˆร ยฎย•ร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Jamaica_Z_short" : "EST", "America/Juneau_Z_abbreviated" : "ร ยฎยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยฎร ยฏย†ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย• ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย (Juneau)", "America/Juneau_Z_short" : "PST", "America/Kentucky/Louisville_Z_abbreviated" : "ร ยฎยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยฎร ยฏย†ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย• ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย (Louisville)", "America/Kentucky/Louisville_Z_short" : "EST", "America/Kentucky/Monticello_Z_abbreviated" : "ร ยฎยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยฎร ยฏย†ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย• ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย (Monticello, Kentucky)", "America/Kentucky/Monticello_Z_short" : "CST", "America/La_Paz_Z_abbreviated" : "ร ยฎยชร ยฏยŠร ยฎยฒร ยฎยฟร ยฎยตร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/La_Paz_Z_short" : "BOT", "America/Lima_Z_abbreviated" : "ร ยฎยชร ยฏย†ร ยฎยฐร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Lima_Z_short" : "PET", "America/Los_Angeles_Z_abbreviated" : "ร ยฎยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยฎร ยฏย†ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย• ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย (ร ยฎยฒร ยฎยพร ยฎยธร ยฏย ร ยฎยร ยฎยžร ยฏยร ยฎยšร ยฎยฒร ยฏยร ยฎยธร ยฏย)", "America/Los_Angeles_Z_short" : "PST", "America/Maceio_Z_abbreviated" : "ร ยฎยชร ยฎยฟร ยฎยฐร ยฏย‡ร ยฎยธร ยฎยฟร ยฎยฒร ยฏย (Maceio)", "America/Maceio_Z_short" : "BRT", "America/Managua_Z_abbreviated" : "ร ยฎยจร ยฎยฟร ยฎย•ร ยฎยพร ยฎยฐร ยฎย•ร ยฏยร ยฎยตร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Managua_Z_short" : "CST", "America/Manaus_Z_abbreviated" : "ร ยฎยชร ยฎยฟร ยฎยฐร ยฏย‡ร ยฎยธร ยฎยฟร ยฎยฒร ยฏย (Manaus)", "America/Manaus_Z_short" : "AMT", "America/Martinique_Z_abbreviated" : "ร ยฎยฎร ยฎยพร ยฎยฐร ยฏยร ยฎยŸร ยฎยฟร ยฎยฉร ยฎยฟร ยฎย•ร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Martinique_Z_short" : "AST", "America/Matamoros_Z_abbreviated" : "ร ยฎยฎร ยฏย†ร ยฎย•ร ยฏยร ยฎยšร ยฎยฟร ยฎย•ร ยฏย‹ (Matamoros)", "America/Matamoros_Z_short" : "CST", "America/Mazatlan_Z_abbreviated" : "ร ยฎยฎร ยฏย†ร ยฎย•ร ยฏยร ยฎยšร ยฎยฟร ยฎย•ร ยฏย‹ (Mazatlan)", "America/Mazatlan_Z_short" : "PST", "America/Menominee_Z_abbreviated" : "ร ยฎยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยฎร ยฏย†ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย• ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย (Menominee)", "America/Menominee_Z_short" : "EST", "America/Merida_Z_abbreviated" : "ร ยฎยฎร ยฏย†ร ยฎย•ร ยฏยร ยฎยšร ยฎยฟร ยฎย•ร ยฏย‹ (Merida)", "America/Merida_Z_short" : "CST", "America/Mexico_City_Z_abbreviated" : "ร ยฎยฎร ยฏย†ร ยฎย•ร ยฏยร ยฎยšร ยฎยฟร ยฎย•ร ยฏย‹ (Mexico City)", "America/Mexico_City_Z_short" : "CST", "America/Miquelon_Z_abbreviated" : "ร ยฎยšร ยฏย†ร ยฎยฏร ยฎยฟร ยฎยฉร ยฏยร ยฎยŸร ยฏย ร ยฎยชร ยฎยฟร ยฎยฏร ยฎยฐร ยฏย ร ยฎยฎร ยฎยฑร ยฏยร ยฎยฑร ยฏยร ยฎยฎร ยฏย ร ยฎยฎร ยฎยฟร ยฎย•ร ยฏยร ยฎยตร ยฏย‡ร ยฎยฒร ยฎยพร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Miquelon_Z_short" : "AST", "America/Moncton_Z_abbreviated" : "ร ยฎย•ร ยฎยฉร ยฎยŸร ยฎยพ (Moncton)", "America/Moncton_Z_short" : "AST", "America/Monterrey_Z_abbreviated" : "ร ยฎยฎร ยฏย†ร ยฎย•ร ยฏยร ยฎยšร ยฎยฟร ยฎย•ร ยฏย‹ (Monterrey)", "America/Monterrey_Z_short" : "CST", "America/Montevideo_Z_abbreviated" : "ร ยฎย‰ร ยฎยฐร ยฏยร ยฎย•ร ยฏยร ยฎยตร ยฏย‡ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Montevideo_Z_short" : "UYT", "America/Montserrat_Z_abbreviated" : "ร ยฎยฎร ยฏยŒร ยฎยฉร ยฏยร ยฎยŸร ยฏยร ยฎยšร ยฏย†ร ยฎยฐร ยฎยพร ยฎยŸร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Montserrat_Z_short" : "AST", "America/Nassau_Z_abbreviated" : "ร ยฎยชร ยฎยนร ยฎยพร ยฎยฎร ยฎยพร ยฎยธร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Nassau_Z_short" : "EST", "America/New_York_Z_abbreviated" : "ร ยฎยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยฎร ยฏย†ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย• ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย (ร ยฎยจร ยฎยฟร ยฎยฏร ยฏย‚ร ยฎยฏร ยฎยพร ยฎยฐร ยฏยร ยฎย•ร ยฏย)", "America/New_York_Z_short" : "EST", "America/Noronha_Z_abbreviated" : "ร ยฎยชร ยฎยฟร ยฎยฐร ยฏย‡ร ยฎยธร ยฎยฟร ยฎยฒร ยฏย (Noronha)", "America/Noronha_Z_short" : "FNT", "America/North_Dakota/Beulah_Z_abbreviated" : "ร ยฎยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยฎร ยฏย†ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย• ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย (Beulah)", "America/North_Dakota/Beulah_Z_short" : "MST", "America/North_Dakota/Center_Z_abbreviated" : "ร ยฎยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยฎร ยฏย†ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย• ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย (ร ยฎยฎร ยฏยˆร ยฎยฏร ยฎยฎร ยฏย, ร ยฎยตร ยฎยŸร ยฎย•ร ยฏยร ยฎย•ร ยฏย ร ยฎยŸร ยฎย•ร ยฏย‹ร ยฎยŸร ยฎยพ)", "America/North_Dakota/Center_Z_short" : "MST", "America/North_Dakota/New_Salem_Z_abbreviated" : "ร ยฎยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยฎร ยฏย†ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย• ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย (New Salem, North Dakota)", "America/North_Dakota/New_Salem_Z_short" : "MST", "America/Ojinaga_Z_abbreviated" : "ร ยฎยฎร ยฏย†ร ยฎย•ร ยฏยร ยฎยšร ยฎยฟร ยฎย•ร ยฏย‹ (Ojinaga)", "America/Ojinaga_Z_short" : "CST", "America/Panama_Z_abbreviated" : "ร ยฎยชร ยฎยฉร ยฎยพร ยฎยฎร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Panama_Z_short" : "EST", "America/Pangnirtung_Z_abbreviated" : "ร ยฎย•ร ยฎยฉร ยฎยŸร ยฎยพ (Pangnirtung)", "America/Pangnirtung_Z_short" : "AST", "America/Paramaribo_Z_abbreviated" : "ร ยฎยšร ยฏย‚ร ยฎยฐร ยฎยฟร ยฎยฉร ยฎยพร ยฎยฎร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Paramaribo_Z_short" : "NEGT", "America/Phoenix_Z_abbreviated" : "ร ยฎยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยฎร ยฏย†ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย• ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย (ร ยฎยƒร ยฎยชร ยฏย‹ร ยฎยฉร ยฎยฟร ยฎย•ร ยฏยร ยฎยธร ยฏย)", "America/Phoenix_Z_short" : "MST", "America/Port-au-Prince_Z_abbreviated" : "ร ยฎยนร ยฏย†ร ยฎยฏร ยฏยร ยฎยคร ยฎยฟ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Port-au-Prince_Z_short" : "EST", "America/Port_of_Spain_Z_abbreviated" : "ร ยฎยŸร ยฏยร ยฎยฐร ยฎยฟร ยฎยฉร ยฎยฟร ยฎยŸร ยฎยพร ยฎยŸร ยฏย ร ยฎยฎร ยฎยฑร ยฏยร ยฎยฑร ยฏยร ยฎยฎร ยฏย ร ยฎยŸร ยฏยร ยฎยชร ยฎยพร ยฎย•ร ยฏย‹ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Port_of_Spain_Z_short" : "AST", "America/Porto_Velho_Z_abbreviated" : "ร ยฎยชร ยฎยฟร ยฎยฐร ยฏย‡ร ยฎยธร ยฎยฟร ยฎยฒร ยฏย (Porto Velho)", "America/Porto_Velho_Z_short" : "AMT", "America/Puerto_Rico_Z_abbreviated" : "ร ยฎยชร ยฎยฟร ยฎยฏร ยฏย‚ร ยฎยฐร ยฏยร ยฎยŸร ยฏย‹ ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏย‹ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Puerto_Rico_Z_short" : "AST", "America/Rankin_Inlet_Z_abbreviated" : "ร ยฎย•ร ยฎยฉร ยฎยŸร ยฎยพ (Rankin Inlet)", "America/Rankin_Inlet_Z_short" : "CST", "America/Recife_Z_abbreviated" : "ร ยฎยชร ยฎยฟร ยฎยฐร ยฏย‡ร ยฎยธร ยฎยฟร ยฎยฒร ยฏย (Recife)", "America/Recife_Z_short" : "BRT", "America/Regina_Z_abbreviated" : "ร ยฎย•ร ยฎยฉร ยฎยŸร ยฎยพ (Regina)", "America/Regina_Z_short" : "CST", "America/Resolute_Z_abbreviated" : "ร ยฎย•ร ยฎยฉร ยฎยŸร ยฎยพ (Resolute)", "America/Resolute_Z_short" : "CST", "America/Rio_Branco_Z_abbreviated" : "ร ยฎยชร ยฎยฟร ยฎยฐร ยฏย‡ร ยฎยธร ยฎยฟร ยฎยฒร ยฏย (Rio Branco)", "America/Rio_Branco_Z_short" : "ACT (Acre)", "America/Santa_Isabel_Z_abbreviated" : "ร ยฎยฎร ยฏย†ร ยฎย•ร ยฏยร ยฎยšร ยฎยฟร ยฎย•ร ยฏย‹ (Santa Isabel)", "America/Santa_Isabel_Z_short" : "PST", "America/Santarem_Z_abbreviated" : "ร ยฎยชร ยฎยฟร ยฎยฐร ยฏย‡ร ยฎยธร ยฎยฟร ยฎยฒร ยฏย (Santarem)", "America/Santarem_Z_short" : "AMT", "America/Santiago_Z_abbreviated" : "ร ยฎยšร ยฎยฟร ยฎยฒร ยฎยฟ (Santiago)", "America/Santiago_Z_short" : "CLST", "America/Santo_Domingo_Z_abbreviated" : "ร ยฎยŸร ยฏยŠร ยฎยฎร ยฎยฟร ยฎยฉร ยฎยฟร ยฎย•ร ยฎยฉร ยฏย ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Santo_Domingo_Z_short" : "GMT-04:30", "America/Sao_Paulo_Z_abbreviated" : "ร ยฎยชร ยฎยฟร ยฎยฐร ยฏย‡ร ยฎยธร ยฎยฟร ยฎยฒร ยฏย (Sao Paulo)", "America/Sao_Paulo_Z_short" : "BRT", "America/St_Johns_Z_abbreviated" : "ร ยฎย•ร ยฎยฉร ยฎยŸร ยฎยพ (St. John's)", "America/St_Johns_Z_short" : "NST", "America/St_Kitts_Z_abbreviated" : "ร ยฎยšร ยฏย†ร ยฎยฏร ยฎยฟร ยฎยฉร ยฏยร ยฎยŸร ยฏย ร ยฎย•ร ยฎยฟร ยฎยŸร ยฏยร ยฎยธร ยฏย ร ยฎยฎร ยฎยฑร ยฏยร ยฎยฑร ยฏยร ยฎยฎร ยฏย ร ยฎยจร ยฏย†ร ยฎยตร ยฎยฟร ยฎยธร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/St_Kitts_Z_short" : "AST", "America/St_Lucia_Z_abbreviated" : "ร ยฎยšร ยฏย†ร ยฎยฏร ยฎยฟร ยฎยฉร ยฏยร ยฎยŸร ยฏย ร ยฎยฒร ยฏย‚ร ยฎยšร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/St_Lucia_Z_short" : "AST", "America/St_Thomas_Z_abbreviated" : "ร ยฎยฏร ยฏย‚.ร ยฎยŽร ยฎยธร ยฏย ร ยฎย•ร ยฎยฉร ยฏยร ยฎยฉร ยฎยฟร ยฎยคร ยฏย ร ยฎยคร ยฏย€ร ยฎยตร ยฏยร ยฎย•ร ยฎยณร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/St_Thomas_Z_short" : "AST", "America/St_Vincent_Z_abbreviated" : "ร ยฎยšร ยฏย†ร ยฎยฏร ยฎยฟร ยฎยฉร ยฏย ร ยฎยตร ยฎยฟร ยฎยฉร ยฏยร ยฎยšร ยฎยฉร ยฏยร ยฎยŸร ยฏย ร ยฎยฎร ยฎยฑร ยฏยร ยฎยฑร ยฏยร ยฎยฎร ยฏย ร ยฎย•ร ยฎยฟร ยฎยฐร ยฏย†ร ยฎยฉร ยฎยŸร ยฏยˆร ยฎยฉร ยฏยร ยฎยธร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/St_Vincent_Z_short" : "AST", "America/Tegucigalpa_Z_abbreviated" : "ร ยฎยนร ยฎยพร ยฎยฃร ยฏยร ยฎยŸร ยฏยร ยฎยฐร ยฎยพร ยฎยธร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Tegucigalpa_Z_short" : "CST", "America/Tijuana_Z_abbreviated" : "ร ยฎยฎร ยฏย†ร ยฎย•ร ยฏยร ยฎยšร ยฎยฟร ยฎย•ร ยฏย‹ (Tijuana)", "America/Tijuana_Z_short" : "PST", "America/Toronto_Z_abbreviated" : "ร ยฎย•ร ยฎยฉร ยฎยŸร ยฎยพ (Toronto)", "America/Toronto_Z_short" : "EST", "America/Tortola_Z_abbreviated" : "ร ยฎยชร ยฎยฟร ยฎยฐร ยฎยฟร ยฎยŸร ยฏยร ยฎยŸร ยฏย€ร ยฎยทร ยฏย ร ยฎย•ร ยฎยฉร ยฏยร ยฎยฉร ยฎยฟร ยฎยคร ยฏย ร ยฎยคร ยฏย€ร ยฎยตร ยฏยร ยฎย•ร ยฎยณร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "America/Tortola_Z_short" : "AST", "America/Vancouver_Z_abbreviated" : "ร ยฎย•ร ยฎยฉร ยฎยŸร ยฎยพ (Vancouver)", "America/Vancouver_Z_short" : "PST", "America/Winnipeg_Z_abbreviated" : "ร ยฎย•ร ยฎยฉร ยฎยŸร ยฎยพ (Winnipeg)", "America/Winnipeg_Z_short" : "CST", "Antarctica/Casey_Z_abbreviated" : "ร ยฎย…ร ยฎยฃร ยฏยร ยฎยŸร ยฎยพร ยฎยฐร ยฏยร ยฎยŸร ยฎยฟร ยฎย•ร ยฎยพ (Casey)", "Antarctica/Casey_Z_short" : "AWST", "Antarctica/Davis_Z_abbreviated" : "ร ยฎย…ร ยฎยฃร ยฏยร ยฎยŸร ยฎยพร ยฎยฐร ยฏยร ยฎยŸร ยฎยฟร ยฎย•ร ยฎยพ (Davis)", "Antarctica/Davis_Z_short" : "DAVT", "Antarctica/DumontDUrville_Z_abbreviated" : "ร ยฎย…ร ยฎยฃร ยฏยร ยฎยŸร ยฎยพร ยฎยฐร ยฏยร ยฎยŸร ยฎยฟร ยฎย•ร ยฎยพ (Dumont d'Urville)", "Antarctica/DumontDUrville_Z_short" : "DDUT", "Antarctica/Macquarie_Z_abbreviated" : "ร ยฎย…ร ยฎยฃร ยฏยร ยฎยŸร ยฎยพร ยฎยฐร ยฏยร ยฎยŸร ยฎยฟร ยฎย•ร ยฎยพ (Macquarie)", "Antarctica/Macquarie_Z_short" : "AEDT", "Antarctica/McMurdo_Z_abbreviated" : "ร ยฎย…ร ยฎยฃร ยฏยร ยฎยŸร ยฎยพร ยฎยฐร ยฏยร ยฎยŸร ยฎยฟร ยฎย•ร ยฎยพ (McMurdo)", "Antarctica/McMurdo_Z_short" : "NZST", "Antarctica/Palmer_Z_abbreviated" : "ร ยฎย…ร ยฎยฃร ยฏยร ยฎยŸร ยฎยพร ยฎยฐร ยฏยร ยฎยŸร ยฎยฟร ยฎย•ร ยฎยพ (Palmer)", "Antarctica/Palmer_Z_short" : "ART", "Antarctica/Rothera_Z_abbreviated" : "ร ยฎย…ร ยฎยฃร ยฏยร ยฎยŸร ยฎยพร ยฎยฐร ยฏยร ยฎยŸร ยฎยฟร ยฎย•ร ยฎยพ (Rothera)", "Antarctica/Rothera_Z_short" : "ROTT", "Antarctica/Syowa_Z_abbreviated" : "ร ยฎย…ร ยฎยฃร ยฏยร ยฎยŸร ยฎยพร ยฎยฐร ยฏยร ยฎยŸร ยฎยฟร ยฎย•ร ยฎยพ (Syowa)", "Antarctica/Syowa_Z_short" : "SYOT", "Antarctica/Vostok_Z_abbreviated" : "ร ยฎย…ร ยฎยฃร ยฏยร ยฎยŸร ยฎยพร ยฎยฐร ยฏยร ยฎยŸร ยฎยฟร ยฎย•ร ยฎยพ (Vostok)", "Antarctica/Vostok_Z_short" : "VOST", "Asia/Aden_Z_abbreviated" : "ร ยฎยร ยฎยฎร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Aden_Z_short" : "AST (SA)", "Asia/Almaty_Z_abbreviated" : "ร ยฎย•ร ยฎยธร ยฎย•ร ยฎยธร ยฏยร ยฎยคร ยฎยพร ยฎยฉร ยฏย (Almaty)", "Asia/Almaty_Z_short" : "ALMT", "Asia/Amman_Z_abbreviated" : "ร ยฎยœร ยฏยŠร ยฎยฐร ยฏยร ยฎยŸร ยฎยพร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Amman_Z_short" : "EET", "Asia/Anadyr_Z_abbreviated" : "ร ยฎยฐร ยฎยทร ยฏยร ยฎยฏร ยฎยพ (Anadyr)", "Asia/Anadyr_Z_short" : "ANAT", "Asia/Aqtau_Z_abbreviated" : "ร ยฎย•ร ยฎยธร ยฎย•ร ยฎยธร ยฏยร ยฎยคร ยฎยพร ยฎยฉร ยฏย (Aqtau)", "Asia/Aqtau_Z_short" : "SHET", "Asia/Aqtobe_Z_abbreviated" : "ร ยฎย•ร ยฎยธร ยฎย•ร ยฎยธร ยฏยร ยฎยคร ยฎยพร ยฎยฉร ยฏย (Aqtobe)", "Asia/Aqtobe_Z_short" : "AKTT", "Asia/Ashgabat_Z_abbreviated" : "ร ยฎยคร ยฏยร ยฎยฐร ยฏยร ยฎย•ร ยฏยร ยฎยฎร ยฏย†ร ยฎยฉร ยฎยฟร ยฎยธร ยฏยร ยฎยคร ยฎยพร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Ashgabat_Z_short" : "ASHT", "Asia/Baghdad_Z_abbreviated" : "ร ยฎย‡ร ยฎยฐร ยฎยพร ยฎย•ร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Baghdad_Z_short" : "AST (SA)", "Asia/Bahrain_Z_abbreviated" : "ร ยฎยชร ยฎยนร ยฏยร ยฎยฐร ยฏยˆร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Bahrain_Z_short" : "GST", "Asia/Baku_Z_abbreviated" : "ร ยฎย…ร ยฎยœร ยฎยฐร ยฏยร ยฎยชร ยฏยˆร ยฎยœร ยฎยพร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Baku_Z_short" : "BAKT", "Asia/Bangkok_Z_abbreviated" : "ร ยฎยคร ยฎยพร ยฎยฏร ยฏยร ยฎยฒร ยฎยพร ยฎยจร ยฏยร ยฎยคร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Bangkok_Z_short" : "ICT", "Asia/Beirut_Z_abbreviated" : "ร ยฎยฒร ยฏย†ร ยฎยชร ยฎยฉร ยฎยพร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Beirut_Z_short" : "EET", "Asia/Bishkek_Z_abbreviated" : "ร ยฎย•ร ยฎยฟร ยฎยฐร ยฏยร ยฎย•ร ยฎยฟร ยฎยธร ยฏยร ยฎยคร ยฎยพร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Bishkek_Z_short" : "FRUT", "Asia/Brunei_Z_abbreviated" : "ร ยฎยชร ยฏยร ยฎยฐร ยฏย‚ร ยฎยฉร ยฏย‡ร ยฎยฏร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Brunei_Z_short" : "BNT", "Asia/Choibalsan_Z_abbreviated" : "ร ยฎยฎร ยฎย™ร ยฏยร ยฎย•ร ยฏย‹ร ยฎยฒร ยฎยฟร ยฎยฏร ยฎยพ (Choibalsan)", "Asia/Choibalsan_Z_short" : "ULAT", "Asia/Chongqing_Z_abbreviated" : "ร ยฎยšร ยฏย€ร ยฎยฉร ยฎยพ (Chongqing)", "Asia/Chongqing_Z_short" : "LONT", "Asia/Colombo_Z_abbreviated" : "IST", "Asia/Colombo_Z_short" : "IST", "Asia/Damascus_Z_abbreviated" : "ร ยฎยšร ยฎยฟร ยฎยฐร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Damascus_Z_short" : "EET", "Asia/Dhaka_Z_abbreviated" : "ร ยฎยชร ยฎย™ร ยฏยร ยฎย•ร ยฎยณร ยฎยพร ยฎยคร ยฏย‡ร ยฎยทร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Dhaka_Z_short" : "DACT", "Asia/Dili_Z_abbreviated" : "ร ยฎย•ร ยฎยฟร ยฎยดร ยฎย•ร ยฏยร ยฎย•ร ยฏย ร ยฎยคร ยฏยˆร ยฎยฎร ยฏย‚ร ยฎยฐร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Dili_Z_short" : "TLT", "Asia/Dubai_Z_abbreviated" : "ร ยฎยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยฐร ยฎยชร ยฏย ร ยฎย•ร ยฏย‚ร ยฎยŸร ยฏยร ยฎยŸร ยฎยพร ยฎยŸร ยฏยร ยฎยšร ยฎยฟ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Dubai_Z_short" : "GST", "Asia/Dushanbe_Z_abbreviated" : "ร ยฎยคร ยฎยพร ยฎยœร ยฎยฟร ยฎย•ร ยฎยฟร ยฎยธร ยฏยร ยฎยคร ยฎยพร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Dushanbe_Z_short" : "DUST", "Asia/Gaza_Z_abbreviated" : "ร ยฎยชร ยฎยพร ยฎยฒร ยฎยธร ยฏยร ยฎยคร ยฏย€ร ยฎยฉร ยฎยฟร ยฎยฏร ยฎยฉร ยฏย ร ยฎยฎร ยฎยพร ยฎยนร ยฎยพร ยฎยฃร ยฎย™ร ยฏยร ยฎย•ร ยฎยณร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Gaza_Z_short" : "IST (IL)", "Asia/Harbin_Z_abbreviated" : "ร ยฎยšร ยฏย€ร ยฎยฉร ยฎยพ (Harbin)", "Asia/Harbin_Z_short" : "CHAT", "Asia/Hebron_Z_abbreviated" : "ร ยฎยชร ยฎยพร ยฎยฒร ยฎยธร ยฏยร ยฎยคร ยฏย€ร ยฎยฉร ยฎยฟร ยฎยฏร ยฎยฉร ยฏย ร ยฎยฎร ยฎยพร ยฎยนร ยฎยพร ยฎยฃร ยฎย™ร ยฏยร ยฎย•ร ยฎยณร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Hebron_Z_short" : "IST (IL)", "Asia/Ho_Chi_Minh_Z_abbreviated" : "ร ยฎยตร ยฎยฟร ยฎยฏร ยฎยŸร ยฏยร ยฎยจร ยฎยพร ยฎยฎร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Ho_Chi_Minh_Z_short" : "ICT", "Asia/Hong_Kong_Z_abbreviated" : "ร ยฎยนร ยฎยพร ยฎย™ร ยฏยร ยฎย•ร ยฎยพร ยฎย™ร ยฏย ร ยฎยšร ยฎยพร ยฎยฐร ยฏย ร ยฎยšร ยฏย€ร ยฎยฉร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Hong_Kong_Z_short" : "HKT", "Asia/Hovd_Z_abbreviated" : "ร ยฎยฎร ยฎย™ร ยฏยร ยฎย•ร ยฏย‹ร ยฎยฒร ยฎยฟร ยฎยฏร ยฎยพ (Hovd)", "Asia/Hovd_Z_short" : "HOVT", "Asia/Irkutsk_Z_abbreviated" : "ร ยฎยฐร ยฎยทร ยฏยร ยฎยฏร ยฎยพ (Irkutsk)", "Asia/Irkutsk_Z_short" : "IRKT", "Asia/Jakarta_Z_abbreviated" : "ร ยฎย‡ร ยฎยจร ยฏยร ยฎยคร ยฏย‹ร ยฎยฉร ยฏย‡ร ยฎยทร ยฎยฟร ยฎยฏร ยฎยพ (ร ยฎยœร ยฎย•ร ยฎยพร ยฎยฐร ยฏยร ยฎยคร ยฏยร ยฎยคร ยฎยพ)", "Asia/Jakarta_Z_short" : "WIT", "Asia/Jerusalem_Z_abbreviated" : "ร ยฎย‡ร ยฎยธร ยฏยร ยฎยฐร ยฏย‡ร ยฎยฒร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Jerusalem_Z_short" : "IST (IL)", "Asia/Kabul_Z_abbreviated" : "ร ยฎย†ร ยฎยชร ยฏยร ยฎย•ร ยฎยพร ยฎยฉร ยฎยฟร ยฎยธร ยฏยร ยฎยคร ยฎยพร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Kabul_Z_short" : "AFT", "Asia/Kamchatka_Z_abbreviated" : "ร ยฎยฐร ยฎยทร ยฏยร ยฎยฏร ยฎยพ (Kamchatka)", "Asia/Kamchatka_Z_short" : "PETT", "Asia/Karachi_Z_abbreviated" : "ร ยฎยชร ยฎยพร ยฎย•ร ยฎยฟร ยฎยธร ยฏยร ยฎยคร ยฎยพร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Karachi_Z_short" : "KART", "Asia/Kashgar_Z_abbreviated" : "ร ยฎยšร ยฏย€ร ยฎยฉร ยฎยพ (Kashgar)", "Asia/Kashgar_Z_short" : "KAST", "Asia/Kathmandu_Z_abbreviated" : "ร ยฎยจร ยฏย‡ร ยฎยชร ยฎยพร ยฎยณร ยฎยฎร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Kathmandu_Z_short" : "NPT", "Asia/Kolkata_Z_abbreviated" : "IST", "Asia/Kolkata_Z_short" : "IST", "Asia/Krasnoyarsk_Z_abbreviated" : "ร ยฎยฐร ยฎยทร ยฏยร ยฎยฏร ยฎยพ (Krasnoyarsk)", "Asia/Krasnoyarsk_Z_short" : "KRAT", "Asia/Kuala_Lumpur_Z_abbreviated" : "ร ยฎยฎร ยฎยฒร ยฏย‡ร ยฎยทร ยฎยฟร ยฎยฏร ยฎยพ (Kuala Lumpur)", "Asia/Kuala_Lumpur_Z_short" : "MALT", "Asia/Kuching_Z_abbreviated" : "ร ยฎยฎร ยฎยฒร ยฏย‡ร ยฎยทร ยฎยฟร ยฎยฏร ยฎยพ (Kuching)", "Asia/Kuching_Z_short" : "BORT", "Asia/Kuwait_Z_abbreviated" : "ร ยฎย•ร ยฏยร ยฎยตร ยฏยˆร ยฎยคร ยฏยร ยฎยคร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Kuwait_Z_short" : "AST (SA)", "Asia/Macau_Z_abbreviated" : "ร ยฎยฎร ยฎย•ร ยฎยพร ยฎยตร ยฏย‹ ร ยฎยšร ยฎยพร ยฎยฐร ยฏย ร ยฎยšร ยฏย€ร ยฎยฉร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Macau_Z_short" : "MOT", "Asia/Magadan_Z_abbreviated" : "ร ยฎยฐร ยฎยทร ยฏยร ยฎยฏร ยฎยพ (Magadan)", "Asia/Magadan_Z_short" : "MAGT", "Asia/Manila_Z_abbreviated" : "ร ยฎยชร ยฎยฟร ยฎยฒร ยฎยฟร ยฎยชร ยฏยร ยฎยชร ยฏยˆร ยฎยฉร ยฏยร ยฎยธร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Manila_Z_short" : "PHT", "Asia/Muscat_Z_abbreviated" : "ร ยฎย“ร ยฎยฎร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Muscat_Z_short" : "GST", "Asia/Nicosia_Z_abbreviated" : "ร ยฎยšร ยฏยˆร ยฎยชร ยฏยร ยฎยฐร ยฎยธร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Nicosia_Z_short" : "EET", "Asia/Novokuznetsk_Z_abbreviated" : "ร ยฎยฐร ยฎยทร ยฏยร ยฎยฏร ยฎยพ (Novokuznetsk)", "Asia/Novokuznetsk_Z_short" : "KRAT", "Asia/Novosibirsk_Z_abbreviated" : "ร ยฎยฐร ยฎยทร ยฏยร ยฎยฏร ยฎยพ (Novosibirsk)", "Asia/Novosibirsk_Z_short" : "NOVT", "Asia/Omsk_Z_abbreviated" : "ร ยฎยฐร ยฎยทร ยฏยร ยฎยฏร ยฎยพ (Omsk)", "Asia/Omsk_Z_short" : "OMST", "Asia/Oral_Z_abbreviated" : "ร ยฎย•ร ยฎยธร ยฎย•ร ยฎยธร ยฏยร ยฎยคร ยฎยพร ยฎยฉร ยฏย (Oral)", "Asia/Oral_Z_short" : "URAT", "Asia/Phnom_Penh_Z_abbreviated" : "ร ยฎย•ร ยฎยฎร ยฏยร ยฎยชร ยฏย‹ร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Phnom_Penh_Z_short" : "ICT", "Asia/Pontianak_Z_abbreviated" : "ร ยฎย‡ร ยฎยจร ยฏยร ยฎยคร ยฏย‹ร ยฎยฉร ยฏย‡ร ยฎยทร ยฎยฟร ยฎยฏร ยฎยพ (Pontianak)", "Asia/Pontianak_Z_short" : "CIT", "Asia/Qatar_Z_abbreviated" : "ร ยฎย•ร ยฎยคร ยฎยพร ยฎยฐร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Qatar_Z_short" : "GST", "Asia/Qyzylorda_Z_abbreviated" : "ร ยฎย•ร ยฎยธร ยฎย•ร ยฎยธร ยฏยร ยฎยคร ยฎยพร ยฎยฉร ยฏย (Qyzylorda)", "Asia/Qyzylorda_Z_short" : "KIZT", "Asia/Rangoon_Z_abbreviated" : "ร ยฎยฎร ยฎยฟร ยฎยฏร ยฎยพร ยฎยฉร ยฏยร ยฎยฎร ยฎยพร ยฎยฐร ยฏย [ร ยฎยชร ยฎยฐร ยฏยร ยฎยฎร ยฎยพ] ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Rangoon_Z_short" : "MMT", "Asia/Riyadh87_Z_abbreviated" : "Asia/Riyadh87 ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Riyadh87_Z_short" : "GMT+03:07:04", "Asia/Riyadh88_Z_abbreviated" : "Asia/Riyadh88 ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Riyadh88_Z_short" : "GMT+03:07:04", "Asia/Riyadh89_Z_abbreviated" : "Asia/Riyadh89 ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Riyadh89_Z_short" : "GMT+03:07:04", "Asia/Riyadh_Z_abbreviated" : "ร ยฎยšร ยฎยตร ยฏย‚ร ยฎยคร ยฎยฟ ร ยฎย…ร ยฎยฐร ยฏย‡ร ยฎยชร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Riyadh_Z_short" : "AST (SA)", "Asia/Sakhalin_Z_abbreviated" : "ร ยฎยฐร ยฎยทร ยฏยร ยฎยฏร ยฎยพ (Sakhalin)", "Asia/Sakhalin_Z_short" : "SAKT", "Asia/Samarkand_Z_abbreviated" : "ร ยฎย‰ร ยฎยธร ยฏยร ยฎยชร ยฏย†ร ยฎย•ร ยฎยฟร ยฎยธร ยฏยร ยฎยคร ยฎยพร ยฎยฉร ยฏย (Samarkand)", "Asia/Samarkand_Z_short" : "SAMT (Samarkand)", "Asia/Seoul_Z_abbreviated" : "ร ยฎยคร ยฏย†ร ยฎยฉร ยฏย ร ยฎย•ร ยฏยŠร ยฎยฐร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Seoul_Z_short" : "KST", "Asia/Shanghai_Z_abbreviated" : "ร ยฎยšร ยฏย€ร ยฎยฉร ยฎยพ (Shanghai)", "Asia/Shanghai_Z_short" : "ร ยฎยšร ยฏย€ร ยฎยฉ ร ยฎยคร ยฎยฐ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Singapore_Z_abbreviated" : "ร ยฎยšร ยฎยฟร ยฎย™ร ยฏยร ยฎย•ร ยฎยชร ยฏยร ยฎยชร ยฏย‚ร ยฎยฐร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Singapore_Z_short" : "SGT", "Asia/Taipei_Z_abbreviated" : "ร ยฎยคร ยฏยˆร ยฎยตร ยฎยพร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Taipei_Z_short" : "CST (TW)", "Asia/Tbilisi_Z_abbreviated" : "ร ยฎยœร ยฎยพร ยฎยฐร ยฏยร ยฎยœร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Tbilisi_Z_short" : "TBIT", "Asia/Tehran_Z_abbreviated" : "ร ยฎยˆร ยฎยฐร ยฎยพร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Tehran_Z_short" : "IRST", "Asia/Thimphu_Z_abbreviated" : "IST", "Asia/Thimphu_Z_short" : "IST", "Asia/Tokyo_Z_abbreviated" : "ร ยฎยœร ยฎยชร ยฏยร ยฎยชร ยฎยพร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Tokyo_Z_short" : "JST", "Asia/Ulaanbaatar_Z_abbreviated" : "ร ยฎยฎร ยฎย™ร ยฏยร ยฎย•ร ยฏย‹ร ยฎยฒร ยฎยฟร ยฎยฏร ยฎยพ (Ulaanbaatar)", "Asia/Ulaanbaatar_Z_short" : "ULAT", "Asia/Urumqi_Z_abbreviated" : "ร ยฎยšร ยฏย€ร ยฎยฉร ยฎยพ (Urumqi)", "Asia/Urumqi_Z_short" : "URUT", "Asia/Vientiane_Z_abbreviated" : "ร ยฎยฒร ยฎยพร ยฎยตร ยฏย‹ร ยฎยธร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Vientiane_Z_short" : "ICT", "Asia/Vladivostok_Z_abbreviated" : "ร ยฎยฐร ยฎยทร ยฏยร ยฎยฏร ยฎยพ (Vladivostok)", "Asia/Vladivostok_Z_short" : "VLAT", "Asia/Yakutsk_Z_abbreviated" : "ร ยฎยฐร ยฎยทร ยฏยร ยฎยฏร ยฎยพ (Yakutsk)", "Asia/Yakutsk_Z_short" : "YAKT", "Asia/Yekaterinburg_Z_abbreviated" : "ร ยฎยฐร ยฎยทร ยฏยร ยฎยฏร ยฎยพ (Yekaterinburg)", "Asia/Yekaterinburg_Z_short" : "SVET", "Asia/Yerevan_Z_abbreviated" : "ร ยฎย†ร ยฎยฐร ยฏยร ยฎยฎร ยฏย‡ร ยฎยฉร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Asia/Yerevan_Z_short" : "YERT", "Atlantic/Bermuda_Z_abbreviated" : "ร ยฎยชร ยฏย†ร ยฎยฐร ยฏยร ยฎยฎร ยฏยร ยฎยŸร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Atlantic/Bermuda_Z_short" : "AST", "Atlantic/Cape_Verde_Z_abbreviated" : "ร ยฎย•ร ยฏย‡ร ยฎยชร ยฏย ร ยฎยตร ยฏย†ร ยฎยฐร ยฏยร ยฎยŸร ยฏย‡ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Atlantic/Cape_Verde_Z_short" : "CVT", "Atlantic/Reykjavik_Z_abbreviated" : "ร ยฎยร ยฎยธร ยฏยร ยฎยฒร ยฎยพร ยฎยจร ยฏยร ยฎยคร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Atlantic/Reykjavik_Z_short" : "GMT", "Atlantic/South_Georgia_Z_abbreviated" : "ร ยฎยคร ยฏย†ร ยฎยฉร ยฏย ร ยฎยœร ยฎยฟร ยฎยฏร ยฎยพร ยฎยฐร ยฏยร ยฎยœร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยฎร ยฎยฑร ยฏยร ยฎยฑร ยฏยร ยฎยฎร ยฏย ร ยฎยคร ยฏย†ร ยฎยฉร ยฏย ร ยฎยšร ยฎยพร ยฎยฉร ยฏยร ยฎยŸร ยฏยร ยฎยตร ยฎยฟร ยฎยšร ยฏย ร ยฎยคร ยฏย€ร ยฎยตร ยฏยร ยฎย•ร ยฎ", "Atlantic/South_Georgia_Z_short" : "GST (GS)", "Atlantic/St_Helena_Z_abbreviated" : "ร ยฎยšร ยฏย†ร ยฎยฏร ยฎยฟร ยฎยฉร ยฏยร ยฎยŸร ยฏย ร ยฎยนร ยฏย†ร ยฎยฒร ยฏย†ร ยฎยฉร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Atlantic/St_Helena_Z_short" : "GMT", "Atlantic/Stanley_Z_abbreviated" : "ร ยฎยƒร ยฎยชร ยฎยพร ยฎย•ร ยฏยร ยฎยฒร ยฎยพร ยฎยจร ยฏยร ยฎยคร ยฏย ร ยฎยคร ยฏย€ร ยฎยตร ยฏยร ยฎย•ร ยฎยณร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Atlantic/Stanley_Z_short" : "FKT", "Australia/Adelaide_Z_abbreviated" : "ร ยฎย†ร ยฎยธร ยฏยร ยฎยคร ยฎยฟร ยฎยฐร ยฏย‡ร ยฎยฒร ยฎยฟร ยฎยฏร ยฎยพ (Adelaide)", "Australia/Adelaide_Z_short" : "ACST", "Australia/Brisbane_Z_abbreviated" : "ร ยฎย†ร ยฎยธร ยฏยร ยฎยคร ยฎยฟร ยฎยฐร ยฏย‡ร ยฎยฒร ยฎยฟร ยฎยฏร ยฎยพ (ร ยฎยชร ยฎยฟร ยฎยฐร ยฎยฟร ยฎยธร ยฏยร ยฎยชร ยฏย‡ร ยฎยฉร ยฏย)", "Australia/Brisbane_Z_short" : "AEST", "Australia/Darwin_Z_abbreviated" : "ร ยฎย†ร ยฎยธร ยฏยร ยฎยคร ยฎยฟร ยฎยฐร ยฏย‡ร ยฎยฒร ยฎยฟร ยฎยฏร ยฎยพ (Darwin)", "Australia/Darwin_Z_short" : "ACST", "Australia/Hobart_Z_abbreviated" : "ร ยฎย†ร ยฎยธร ยฏยร ยฎยคร ยฎยฟร ยฎยฐร ยฏย‡ร ยฎยฒร ยฎยฟร ยฎยฏร ยฎยพ (Hobart)", "Australia/Hobart_Z_short" : "AEDT", "Australia/Lord_Howe_Z_abbreviated" : "ร ยฎย†ร ยฎยธร ยฏยร ยฎยคร ยฎยฟร ยฎยฐร ยฏย‡ร ยฎยฒร ยฎยฟร ยฎยฏร ยฎยพ (Lord Howe)", "Australia/Lord_Howe_Z_short" : "AEST", "Australia/Melbourne_Z_abbreviated" : "ร ยฎย†ร ยฎยธร ยฏยร ยฎยคร ยฎยฟร ยฎยฐร ยฏย‡ร ยฎยฒร ยฎยฟร ยฎยฏร ยฎยพ (Melbourne)", "Australia/Melbourne_Z_short" : "AEST", "Australia/Perth_Z_abbreviated" : "ร ยฎย†ร ยฎยธร ยฏยร ยฎยคร ยฎยฟร ยฎยฐร ยฏย‡ร ยฎยฒร ยฎยฟร ยฎยฏร ยฎยพ (Perth)", "Australia/Perth_Z_short" : "AWST", "Australia/Sydney_Z_abbreviated" : "ร ยฎย†ร ยฎยธร ยฏยร ยฎยคร ยฎยฟร ยฎยฐร ยฏย‡ร ยฎยฒร ยฎยฟร ยฎยฏร ยฎยพ (Sydney)", "Australia/Sydney_Z_short" : "AEST", "BC" : "ร ยฎย•ร ยฎยฟร ยฎยฎร ยฏย", "DateTimeCombination" : "{1} {0}", "DateTimeTimezoneCombination" : "{1} {0} {2}", "DateTimezoneCombination" : "{1} {2}", "EST_Z_abbreviated" : "GMT-05:00", "EST_Z_short" : "GMT-05:00", "Etc/GMT-14_Z_abbreviated" : "GMT+14:00", "Etc/GMT-14_Z_short" : "GMT+14:00", "Etc/GMT_Z_abbreviated" : "GMT+00:00", "Etc/GMT_Z_short" : "GMT+00:00", "Europe/Amsterdam_Z_abbreviated" : "ร ยฎยจร ยฏย†ร ยฎยคร ยฎยฐร ยฏยร ยฎยฒร ยฎยพร ยฎยจร ยฏยร ยฎยคร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Amsterdam_Z_short" : "CET", "Europe/Andorra_Z_abbreviated" : "ร ยฎย…ร ยฎยฉร ยฏยร ยฎยŸร ยฏย‹ร ยฎยฐร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Andorra_Z_short" : "CET", "Europe/Athens_Z_abbreviated" : "ร ยฎย•ร ยฎยฟร ยฎยฐร ยฏย€ร ยฎยธร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Athens_Z_short" : "EET", "Europe/Belgrade_Z_abbreviated" : "ร ยฎยšร ยฏย†ร ยฎยฐร ยฏยร ยฎยชร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Belgrade_Z_short" : "CET", "Europe/Berlin_Z_abbreviated" : "ร ยฎยœร ยฏย†ร ยฎยฐร ยฏยร ยฎยฎร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Berlin_Z_short" : "CET", "Europe/Brussels_Z_abbreviated" : "ร ยฎยชร ยฏย†ร ยฎยฒร ยฏยร ยฎยœร ยฎยฟร ยฎยฏร ยฎยฎร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Brussels_Z_short" : "CET", "Europe/Bucharest_Z_abbreviated" : "ร ยฎยฐร ยฏยร ยฎยฎร ยฏย‡ร ยฎยฉร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Bucharest_Z_short" : "EET", "Europe/Budapest_Z_abbreviated" : "ร ยฎยนร ยฎย™ร ยฏยร ยฎย•ร ยฏย‡ร ยฎยฐร ยฎยฟ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Budapest_Z_short" : "CET", "Europe/Chisinau_Z_abbreviated" : "ร ยฎยฎร ยฎยพร ยฎยฒร ยฏยร ยฎยŸร ยฏย‹ร ยฎยตร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Chisinau_Z_short" : "MSK", "Europe/Copenhagen_Z_abbreviated" : "ร ยฎยŸร ยฏย†ร ยฎยฉร ยฏยร ยฎยฎร ยฎยพร ยฎยฐร ยฏยร ยฎย•ร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Copenhagen_Z_short" : "CET", "Europe/Gibraltar_Z_abbreviated" : "ร ยฎยœร ยฎยฟร ยฎยชร ยฏยร ยฎยฐร ยฎยพร ยฎยฒร ยฏยร ยฎยŸร ยฎยฐร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Gibraltar_Z_short" : "CET", "Europe/Helsinki_Z_abbreviated" : "ร ยฎยชร ยฎยฟร ยฎยฉร ยฏยร ยฎยฒร ยฎยพร ยฎยจร ยฏยร ยฎยคร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Helsinki_Z_short" : "EET", "Europe/Istanbul_Z_abbreviated" : "ร ยฎยคร ยฏยร ยฎยฐร ยฏยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Istanbul_Z_short" : "EET", "Europe/Kaliningrad_Z_abbreviated" : "ร ยฎยฐร ยฎยทร ยฏยร ยฎยฏร ยฎยพ (Kaliningrad)", "Europe/Kaliningrad_Z_short" : "MSK", "Europe/Kiev_Z_abbreviated" : "ร ยฎย‰ร ยฎย•ร ยฏยร ยฎยฐร ยฏยˆร ยฎยฉร ยฏย (Kiev)", "Europe/Kiev_Z_short" : "MSK", "Europe/Lisbon_Z_abbreviated" : "ร ยฎยชร ยฏย‹ร ยฎยฐร ยฏยร ยฎยšร ยฏยร ยฎยšร ยฏยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฒร ยฏย (Lisbon)", "Europe/Lisbon_Z_short" : "CET", "Europe/London_Z_abbreviated" : "ร ยฎยชร ยฎยฟร ยฎยฐร ยฎยฟร ยฎยŸร ยฎยฟร ยฎยทร ยฏย ร ยฎย•ร ยฏย‚ร ยฎยŸร ยฏยร ยฎยŸร ยฎยฐร ยฎยšร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/London_Z_short" : "GMT+01:00", "Europe/Luxembourg_Z_abbreviated" : "ร ยฎยฒร ยฎย•ร ยฏยร ยฎยธร ยฏยร ยฎยšร ยฎยฎร ยฏยร ยฎยชร ยฎยฐร ยฏยร ยฎย•ร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Luxembourg_Z_short" : "CET", "Europe/Madrid_Z_abbreviated" : "ร ยฎยธร ยฏยร ยฎยชร ยฏย†ร ยฎยฏร ยฎยฟร ยฎยฉร ยฏย (Madrid)", "Europe/Madrid_Z_short" : "CET", "Europe/Malta_Z_abbreviated" : "ร ยฎยฎร ยฎยพร ยฎยฒร ยฏยร ยฎยŸร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Malta_Z_short" : "CET", "Europe/Minsk_Z_abbreviated" : "ร ยฎยชร ยฏย†ร ยฎยฒร ยฎยพร ยฎยฐร ยฏย‚ร ยฎยธร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Minsk_Z_short" : "MSK", "Europe/Monaco_Z_abbreviated" : "ร ยฎยฎร ยฏยŠร ยฎยฉร ยฎยพร ยฎย•ร ยฏยร ยฎย•ร ยฏย‹ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Monaco_Z_short" : "CET", "Europe/Moscow_Z_abbreviated" : "ร ยฎยฐร ยฎยทร ยฏยร ยฎยฏร ยฎยพ (Moscow)", "Europe/Moscow_Z_short" : "MSK", "Europe/Oslo_Z_abbreviated" : "ร ยฎยจร ยฎยพร ยฎยฐร ยฏยร ยฎยตร ยฏย‡ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Oslo_Z_short" : "CET", "Europe/Paris_Z_abbreviated" : "ร ยฎยชร ยฎยฟร ยฎยฐร ยฎยพร ยฎยฉร ยฏยร ยฎยธร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Paris_Z_short" : "CET", "Europe/Prague_Z_abbreviated" : "ร ยฎยšร ยฏย†ร ยฎย•ร ยฏย ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Prague_Z_short" : "CET", "Europe/Riga_Z_abbreviated" : "ร ยฎยฒร ยฎยพร ยฎยŸร ยฏยร ยฎยตร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Riga_Z_short" : "MSK", "Europe/Rome_Z_abbreviated" : "ร ยฎย‡ร ยฎยคร ยฏยร ยฎยคร ยฎยพร ยฎยฒร ยฎยฟ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Rome_Z_short" : "CET", "Europe/Samara_Z_abbreviated" : "ร ยฎยฐร ยฎยทร ยฏยร ยฎยฏร ยฎยพ (Samara)", "Europe/Samara_Z_short" : "KUYT", "Europe/Simferopol_Z_abbreviated" : "ร ยฎย‰ร ยฎย•ร ยฏยร ยฎยฐร ยฏยˆร ยฎยฉร ยฏย (Simferopol)", "Europe/Simferopol_Z_short" : "MSK", "Europe/Sofia_Z_abbreviated" : "ร ยฎยชร ยฎยฒร ยฏยร ยฎย•ร ยฏย‡ร ยฎยฐร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Sofia_Z_short" : "EET", "Europe/Stockholm_Z_abbreviated" : "ร ยฎยธร ยฏยร ยฎยตร ยฏย€ร ยฎยŸร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Stockholm_Z_short" : "CET", "Europe/Tallinn_Z_abbreviated" : "ร ยฎยŽร ยฎยธร ยฏยร ยฎยŸร ยฏย‹ร ยฎยฉร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Tallinn_Z_short" : "MSK", "Europe/Tirane_Z_abbreviated" : "ร ยฎย…ร ยฎยฒร ยฏยร ยฎยชร ยฏย‡ร ยฎยฉร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Tirane_Z_short" : "CET", "Europe/Uzhgorod_Z_abbreviated" : "ร ยฎย‰ร ยฎย•ร ยฏยร ยฎยฐร ยฏยˆร ยฎยฉร ยฏย (Uzhgorod)", "Europe/Uzhgorod_Z_short" : "MSK", "Europe/Vaduz_Z_abbreviated" : "ร ยฎยฒร ยฎยฟร ยฎยšร ยฏยร ยฎยšร ยฏย†ร ยฎยฃร ยฏยร ยฎยธร ยฏยร ยฎยŸร ยฏย†ร ยฎยฏร ยฏยร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Vaduz_Z_short" : "CET", "Europe/Vienna_Z_abbreviated" : "ร ยฎย†ร ยฎยธร ยฏยร ยฎยคร ยฎยฟร ยฎยฐร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Vienna_Z_short" : "CET", "Europe/Vilnius_Z_abbreviated" : "ร ยฎยฒร ยฎยฟร ยฎยคร ยฏยร ยฎยตร ยฏย‡ร ยฎยฉร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Vilnius_Z_short" : "MSK", "Europe/Volgograd_Z_abbreviated" : "ร ยฎยฐร ยฎยทร ยฏยร ยฎยฏร ยฎยพ (Volgograd)", "Europe/Volgograd_Z_short" : "VOLT", "Europe/Warsaw_Z_abbreviated" : "ร ยฎยชร ยฏย‹ร ยฎยฒร ยฎยจร ยฏยร ยฎยคร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Warsaw_Z_short" : "CET", "Europe/Zaporozhye_Z_abbreviated" : "ร ยฎย‰ร ยฎย•ร ยฏยร ยฎยฐร ยฏยˆร ยฎยฉร ยฏย (Zaporozhye)", "Europe/Zaporozhye_Z_short" : "MSK", "Europe/Zurich_Z_abbreviated" : "ร ยฎยธร ยฏยร ยฎยตร ยฎยฟร ยฎยŸร ยฏยร ยฎยšร ยฎยฐร ยฏยร ยฎยฒร ยฎยพร ยฎยจร ยฏยร ยฎยคร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Europe/Zurich_Z_short" : "CET", "HMS_long" : "{0} {1} {2}", "HMS_short" : "{0}:{1}:{2}", "HM_abbreviated" : "h:mm a", "HM_short" : "h:mm a", "H_abbreviated" : "h a", "Indian/Antananarivo_Z_abbreviated" : "ร ยฎยฎร ยฎยŸร ยฎย•ร ยฎยพร ยฎยธร ยฏยร ยฎย•ร ยฎยฐร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Indian/Antananarivo_Z_short" : "EAT", "Indian/Chagos_Z_abbreviated" : "ร ยฎยชร ยฎยฟร ยฎยฐร ยฎยฟร ยฎยŸร ยฏยร ยฎยŸร ยฎยฟร ยฎยทร ยฏย ร ยฎย‡ร ยฎยจร ยฏยร ยฎยคร ยฎยฟร ยฎยฏร ยฎยชร ยฏย ร ยฎยชร ยฏย†ร ยฎยฐร ยฏยร ยฎย™ร ยฏยร ยฎย•ร ยฎยŸร ยฎยฒร ยฏย ร ยฎยชร ยฎย•ร ยฏยร ยฎยคร ยฎยฟ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Indian/Chagos_Z_short" : "IOT", "Indian/Christmas_Z_abbreviated" : "ร ยฎย•ร ยฎยฟร ยฎยฑร ยฎยฟร ยฎยธร ยฏยร ยฎยคร ยฏยร ยฎยฎร ยฎยธร ยฏย ร ยฎยคร ยฏย€ร ยฎยตร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Indian/Christmas_Z_short" : "CXT", "Indian/Cocos_Z_abbreviated" : "ร ยฎย•ร ยฎยพร ยฎย•ร ยฏย‹ร ยฎยธร ยฏย ร ยฎยคร ยฏย€ร ยฎยตร ยฏยร ยฎย•ร ยฎยณร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Indian/Cocos_Z_short" : "CCT", "Indian/Comoro_Z_abbreviated" : "ร ยฎย•ร ยฏย‹ร ยฎยฎร ยฎยฐร ยฏย‹ร ยฎยธร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Indian/Comoro_Z_short" : "EAT", "Indian/Kerguelen_Z_abbreviated" : "ร ยฎยƒร ยฎยชร ยฏยร ยฎยฐร ยฏย†ร ยฎยฉร ยฏยร ยฎยšร ยฏย ร ยฎยคร ยฏย†ร ยฎยฑร ยฏยร ยฎย•ร ยฏย ร ยฎยฎร ยฎยพร ยฎยนร ยฎยพร ยฎยฃร ยฎย™ร ยฏยร ยฎย•ร ยฎยณร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Indian/Kerguelen_Z_short" : "TFT", "Indian/Mahe_Z_abbreviated" : "ร ยฎยธร ยฏย‡ร ยฎยšร ยฏย‡ร ยฎยฒร ยฏยร ยฎยธร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Indian/Mahe_Z_short" : "SCT", "Indian/Maldives_Z_abbreviated" : "ร ยฎยฎร ยฎยพร ยฎยฒร ยฎยคร ยฏยร ยฎยคร ยฏย€ร ยฎยตร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Indian/Maldives_Z_short" : "MVT", "Indian/Mauritius_Z_abbreviated" : "ร ยฎยฎร ยฏยŠร ยฎยฐร ยฎยฟร ยฎยšร ยฎยฟร ยฎยฏร ยฎยธร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Indian/Mauritius_Z_short" : "MUT", "Indian/Mayotte_Z_abbreviated" : "ร ยฎยฎร ยฎยฏร ยฏย‹ร ยฎยคร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Indian/Mayotte_Z_short" : "EAT", "Indian/Reunion_Z_abbreviated" : "ร ยฎยฐร ยฏย€ร ยฎยฏร ยฏย‚ร ยฎยฉร ยฎยฟร ยฎยฏร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Indian/Reunion_Z_short" : "RET", "MD_abbreviated" : "d MMM", "MD_long" : "d MMMM", "MD_short" : "d/M", "M_abbreviated" : "MMM", "M_long" : "MMMM", "Pacific/Apia_Z_abbreviated" : "ร ยฎยšร ยฎยฎร ยฏย‹ร ยฎยตร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Pacific/Apia_Z_short" : "BST (Bering)", "Pacific/Auckland_Z_abbreviated" : "ร ยฎยจร ยฎยฟร ยฎยฏร ยฏย‚ร ยฎยšร ยฎยฟร ยฎยฒร ยฎยพร ยฎยจร ยฏยร ยฎยคร ยฏย (Auckland)", "Pacific/Auckland_Z_short" : "NZST", "Pacific/Chuuk_Z_abbreviated" : "ร ยฎยฎร ยฏยˆร ยฎย•ร ยฏยร ยฎยฐร ยฏย‹ร ยฎยฉร ยฏย‡ร ยฎยทร ยฎยฟร ยฎยฏร ยฎยพ (Truk)", "Pacific/Chuuk_Z_short" : "TRUT", "Pacific/Efate_Z_abbreviated" : "ร ยฎยตร ยฎยฉร ยฏยร ยฎยตร ยฎยพร ยฎยŸร ยฏยร ยฎยŸร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Pacific/Efate_Z_short" : "VUT", "Pacific/Fakaofo_Z_abbreviated" : "ร ยฎยŸร ยฏย‹ร ยฎย•ร ยฏย‡ร ยฎยฒร ยฏย‹ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Pacific/Fakaofo_Z_short" : "TKT", "Pacific/Fiji_Z_abbreviated" : "ร ยฎยƒร ยฎยชร ยฎยฟร ยฎยœร ยฎยฟ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Pacific/Fiji_Z_short" : "FJT", "Pacific/Funafuti_Z_abbreviated" : "ร ยฎยคร ยฏยร ยฎยตร ยฎยพร ยฎยฒร ยฏย‚ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Pacific/Funafuti_Z_short" : "TVT", "Pacific/Gambier_Z_abbreviated" : "ร ยฎยƒร ยฎยชร ยฏยร ยฎยฐร ยฏย†ร ยฎยฉร ยฏยร ยฎยšร ยฏย ร ยฎยชร ยฎยพร ยฎยฒร ยฎยฟร ยฎยฉร ยฏย‡ร ยฎยทร ยฎยฟร ยฎยฏร ยฎยพ (Gambier)", "Pacific/Gambier_Z_short" : "GAMT", "Pacific/Guadalcanal_Z_abbreviated" : "ร ยฎยšร ยฎยพร ยฎยฒร ยฎยฎร ยฎยฉร ยฏย ร ยฎยคร ยฏย€ร ยฎยตร ยฏยร ยฎย•ร ยฎยณร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Pacific/Guadalcanal_Z_short" : "SBT", "Pacific/Guam_Z_abbreviated" : "ร ยฎย•ร ยฏยร ยฎยตร ยฎยพร ยฎยฎร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Pacific/Guam_Z_short" : "GST (GU)", "Pacific/Honolulu_Z_abbreviated" : "ร ยฎยร ยฎย•ร ยฏยร ยฎย•ร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยฎร ยฏย†ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย• ร ยฎย•ร ยฏยร ยฎยŸร ยฎยฟร ยฎยฏร ยฎยฐร ยฎยšร ยฏย (Honolulu)", "Pacific/Honolulu_Z_short" : "AHST", "Pacific/Johnston_Z_abbreviated" : "ร ยฎยฏร ยฏยร ยฎยฉร ยฏยˆร ยฎยŸร ยฏยร ยฎยŸร ยฎยŸร ยฏย ร ยฎยธร ยฏยร ยฎยŸร ยฏย‡ร ยฎยŸร ยฏยร ยฎยธร ยฏยร ยฎยฎร ยฏย ร ยฎยšร ยฎยฟร ยฎยฑร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยตร ยฏยร ยฎยŸร ยฏยร ยฎยฒร ยฏยˆร ยฎยฉร ยฏย ร ยฎยคร ยฏย€ร ยฎยตร ยฏยร ยฎย•ร ยฎยณร ยฏยร ยฎยฎ", "Pacific/Johnston_Z_short" : "AHST", "Pacific/Majuro_Z_abbreviated" : "ร ยฎยฎร ยฎยพร ยฎยฐร ยฏยร ยฎยทร ยฎยฒร ยฏย ร ยฎยคร ยฏย€ร ยฎยตร ยฏยร ยฎย•ร ยฎยณร ยฏย (Majuro)", "Pacific/Majuro_Z_short" : "MHT", "Pacific/Midway_Z_abbreviated" : "ร ยฎยฏร ยฏยร ยฎยฉร ยฏยˆร ยฎยŸร ยฏยร ยฎยŸร ยฎยŸร ยฏย ร ยฎยธร ยฏยร ยฎยŸร ยฏย‡ร ยฎยŸร ยฏยร ยฎยธร ยฏยร ยฎยฎร ยฏย ร ยฎยšร ยฎยฟร ยฎยฑร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยตร ยฏยร ยฎยŸร ยฏยร ยฎยฒร ยฏยˆร ยฎยฉร ยฏย ร ยฎยคร ยฏย€ร ยฎยตร ยฏยร ยฎย•ร ยฎยณร ยฏยร ยฎยฎ", "Pacific/Midway_Z_short" : "BST (Bering)", "Pacific/Nauru_Z_abbreviated" : "ร ยฎยจร ยฏยŒร ยฎยฐร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Pacific/Nauru_Z_short" : "NRT", "Pacific/Niue_Z_abbreviated" : "ร ยฎยจร ยฎยฟร ยฎยฏร ยฏย‚ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Pacific/Niue_Z_short" : "NUT", "Pacific/Norfolk_Z_abbreviated" : "ร ยฎยจร ยฎยพร ยฎยฐร ยฏยร ยฎยƒร ยฎยชร ยฎยพร ยฎย•ร ยฏย ร ยฎยคร ยฏย€ร ยฎยตร ยฏยร ยฎย•ร ยฎยณร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Pacific/Norfolk_Z_short" : "NFT", "Pacific/Noumea_Z_abbreviated" : "ร ยฎยจร ยฎยฟร ยฎยฏร ยฏย‚ ร ยฎย•ร ยฏย‡ร ยฎยฒร ยฎยฟร ยฎยŸร ยฏย‹ร ยฎยฉร ยฎยฟร ยฎยฏร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Pacific/Noumea_Z_short" : "NCT", "Pacific/Pago_Pago_Z_abbreviated" : "ร ยฎย…ร ยฎยฎร ยฏย†ร ยฎยฐร ยฎยฟร ยฎย•ร ยฏยร ยฎย• ร ยฎยšร ยฎยฎร ยฏย‹ร ยฎยตร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Pacific/Pago_Pago_Z_short" : "BST (Bering)", "Pacific/Palau_Z_abbreviated" : "ร ยฎยชร ยฎยพร ยฎยฒร ยฏย‹ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Pacific/Palau_Z_short" : "PWT", "Pacific/Pitcairn_Z_abbreviated" : "ร ยฎยชร ยฎยฟร ยฎยŸร ยฏยร ยฎย•ร ยฏย†ร ยฎยฏร ยฏยร ยฎยฐร ยฏยร ยฎยฉร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Pacific/Pitcairn_Z_short" : "PNT", "Pacific/Port_Moresby_Z_abbreviated" : "ร ยฎยชร ยฎยพร ยฎยชร ยฏยร ยฎยชร ยฏยร ยฎยตร ยฎยพ ร ยฎยจร ยฎยฟร ยฎยฏร ยฏย‚ ร ยฎย•ร ยฎยฟร ยฎยฉร ยฎยฟ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Pacific/Port_Moresby_Z_short" : "PGT", "Pacific/Rarotonga_Z_abbreviated" : "ร ยฎย•ร ยฏยร ยฎย•ร ยฏย ร ยฎยคร ยฏย€ร ยฎยตร ยฏยร ยฎย•ร ยฎยณร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Pacific/Rarotonga_Z_short" : "CKT", "Pacific/Saipan_Z_abbreviated" : "ร ยฎยตร ยฎยŸร ยฎย•ร ยฏยร ยฎย•ร ยฏย ร ยฎยฎร ยฎยฐร ยฎยฟร ยฎยฏร ยฎยพร ยฎยฉร ยฎยพ ร ยฎยคร ยฏย€ร ยฎยตร ยฏยร ยฎย•ร ยฎยณร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Pacific/Saipan_Z_short" : "MPT", "Pacific/Tarawa_Z_abbreviated" : "ร ยฎย•ร ยฎยฟร ยฎยฐร ยฎยฟร ยฎยชร ยฎยŸร ยฎยฟ (Tarawa)", "Pacific/Tarawa_Z_short" : "GILT", "Pacific/Tongatapu_Z_abbreviated" : "ร ยฎยŸร ยฏย‹ร ยฎย™ร ยฏยร ยฎย•ร ยฎยพ ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Pacific/Tongatapu_Z_short" : "TOT", "Pacific/Wake_Z_abbreviated" : "ร ยฎยฏร ยฏยร ยฎยฉร ยฏยˆร ยฎยŸร ยฏยร ยฎยŸร ยฎยŸร ยฏย ร ยฎยธร ยฏยร ยฎยŸร ยฏย‡ร ยฎยŸร ยฏยร ยฎยธร ยฏยร ยฎยฎร ยฏย ร ยฎยšร ยฎยฟร ยฎยฑร ยฎยฟร ยฎยฏ ร ยฎย…ร ยฎยตร ยฏยร ยฎยŸร ยฏยร ยฎยฒร ยฏยˆร ยฎยฉร ยฏย ร ยฎยคร ยฏย€ร ยฎยตร ยฏยร ยฎย•ร ยฎยณร ยฏยร ยฎยฎ", "Pacific/Wake_Z_short" : "WAKT", "Pacific/Wallis_Z_abbreviated" : "ร ยฎยตร ยฎยพร ยฎยฒร ยฎยฟร ยฎยธร ยฏย ร ยฎยฎร ยฎยฑร ยฏยร ยฎยฑร ยฏยร ยฎยฎร ยฏย ร ยฎยƒร ยฎยชร ยฏยร ยฎยŸร ยฏยร ยฎยฉร ยฎยพ ร ยฎยคร ยฏย€ร ยฎยตร ยฏยร ยฎย•ร ยฎยณร ยฏย ร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "Pacific/Wallis_Z_short" : "WFT", "RelativeTime/oneUnit" : "{0} ร ยฎยฎร ยฏยร ยฎยฉร ยฏย", "RelativeTime/twoUnits" : "{0} {1} ร ยฎยฎร ยฏยร ยฎยฉร ยฏย", "TimeTimezoneCombination" : "{0} {2}", "WET_Z_abbreviated" : "GMT+00:00", "WET_Z_short" : "GMT+00:00", "WMD_abbreviated" : "E, d MMM", "WMD_long" : "EEEE, d MMMM", "WMD_short" : "E, d/M", "WYMD_abbreviated" : "EEE, d MMM, y", "WYMD_long" : "EEEE, d MMMM, y", "WYMD_short" : "EEE, d-M-yy", "W_abbreviated" : "EEE", "W_long" : "EEEE", "YMD_abbreviated" : "d MMM, y", "YMD_full" : "d-M-yy", "YMD_long" : "d MMMM, y", "YMD_short" : "d-M-yy", "YM_long" : "MMMM y", "currencyFormat" : "ร‚ยคร‚ย #,##,##0.00", "currencyPatternPlural" : "e u", "currencyPatternSingular" : "{0} {1}", "day" : "ร ยฎยจร ยฎยพร ยฎยณร ยฏย", "day_abbr" : "ร ยฎยจร ยฎยพร ยฎยณร ยฏย", "dayperiod" : "Dayperiod", "days" : "ร ยฎยจร ยฎยพร ยฎยŸร ยฏยร ยฎย•ร ยฎยณร ยฏย", "days_abbr" : "ร ยฎยจร ยฎยพร ยฎยŸร ยฏยร ยฎย•ร ยฎยณร ยฏย", "decimalFormat" : "#,##,##0.###", "decimalSeparator" : ".", "exponentialSymbol" : "E", "groupingSeparator" : ",", "hour" : "ร ยฎยฎร ยฎยฃร ยฎยฟร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "hour_abbr" : "ร ยฎยฎร ยฎยฃร ยฎยฟร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "hours" : "ร ยฎยฎร ยฎยฃร ยฎยฟร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "hours_abbr" : "ร ยฎยฎร ยฎยฃร ยฎยฟร ยฎยจร ยฏย‡ร ยฎยฐร ยฎยฎร ยฏย", "infinitySign" : "รขยˆยž", "listPatternEnd" : "{0} ร ยฎยฎร ยฎยฑร ยฏยร ยฎยฑร ยฏยร ยฎยฎร ยฏย {1}", "listPatternTwo" : "{0} ร ยฎยฎร ยฎยฑร ยฏยร ยฎยฑร ยฏยร ยฎยฎร ยฏย {1}", "minusSign" : "-", "minute" : "ร ยฎยจร ยฎยฟร ยฎยฎร ยฎยฟร ยฎยŸร ยฎยฎร ยฏย", "minute_abbr" : "ร ยฎยจร ยฎยฟร ยฎยฎร ยฎยฟร ยฎยŸร ยฎยฎร ยฏย", "minutes" : "ร ยฎยจร ยฎยฟร ยฎยฎร ยฎยฟร ยฎยŸร ยฎย™ร ยฏยร ยฎย•ร ยฎยณร ยฏย", "minutes_abbr" : "ร ยฎยจร ยฎยฟร ยฎยฎร ยฎยฟร ยฎยŸร ยฎย™ร ยฏยร ยฎย•ร ยฎยณร ยฏย", "month" : "ร ยฎยฎร ยฎยพร ยฎยคร ยฎยฎร ยฏย", "monthAprLong" : "ร ยฎยร ยฎยชร ยฏยร ยฎยฐร ยฎยฒร ยฏย", "monthAprMedium" : "ร ยฎยร ยฎยชร ยฏย.", "monthAugLong" : "ร ยฎย†ร ยฎย•ร ยฎยธร ยฏยร ยฎยŸร ยฏย", "monthAugMedium" : "ร ยฎย†ร ยฎย•.", "monthDecLong" : "ร ยฎยŸร ยฎยฟร ยฎยšร ยฎยฎร ยฏยร ยฎยชร ยฎยฐร ยฏย", "monthDecMedium" : "ร ยฎยŸร ยฎยฟร ยฎยš.", "monthFebLong" : "ร ยฎยชร ยฎยฟร ยฎยชร ยฏยร ยฎยฐร ยฎยตร ยฎยฐร ยฎยฟ", "monthFebMedium" : "ร ยฎยชร ยฎยฟร ยฎยชร ยฏย.", "monthJanLong" : "ร ยฎยœร ยฎยฉร ยฎยตร ยฎยฐร ยฎยฟ", "monthJanMedium" : "ร ยฎยœร ยฎยฉ.", "monthJulLong" : "ร ยฎยœร ยฏย‚ร ยฎยฒร ยฏยˆ", "monthJulMedium" : "ร ยฎยœร ยฏย‚ร ยฎยฒร ยฏยˆ", "monthJunLong" : "ร ยฎยœร ยฏย‚ร ยฎยฉร ยฏย", "monthJunMedium" : "ร ยฎยœร ยฏย‚ร ยฎยฉร ยฏย", "monthMarLong" : "ร ยฎยฎร ยฎยพร ยฎยฐร ยฏยร ยฎยšร ยฏย", "monthMarMedium" : "ร ยฎยฎร ยฎยพร ยฎยฐร ยฏย.", "monthMayLong" : "ร ยฎยฎร ยฏย‡", "monthMayMedium" : "ร ยฎยฎร ยฏย‡", "monthNovLong" : "ร ยฎยจร ยฎยตร ยฎยฎร ยฏยร ยฎยชร ยฎยฐร ยฏย", "monthNovMedium" : "ร ยฎยจร ยฎยต.", "monthOctLong" : "ร ยฎย…ร ยฎย•ร ยฏยร ยฎยŸร ยฏย‹ร ยฎยชร ยฎยฐร ยฏย", "monthOctMedium" : "ร ยฎย…ร ยฎย•ร ยฏย.", "monthSepLong" : "ร ยฎยšร ยฏย†ร ยฎยชร ยฏยร ยฎยŸร ยฏย†ร ยฎยฎร ยฏยร ยฎยชร ยฏยร ยฎยฐร ยฏย", "monthSepMedium" : "ร ยฎยšร ยฏย†ร ยฎยชร ยฏย.", "month_abbr" : "ร ยฎยฎร ยฎยพร ยฎยคร ยฎยฎร ยฏย", "months" : "ร ยฎยฎร ยฎยพร ยฎยคร ยฎย™ร ยฏยร ยฎย•ร ยฎยณร ยฏย", "months_abbr" : "ร ยฎยฎร ยฎยพร ยฎยคร ยฎย™ร ยฏยร ยฎย•ร ยฎยณร ยฏย", "nanSymbol" : "NaN", "numberZero" : "0", "perMilleSign" : "รขย€ยฐ", "percentFormat" : "#,##,##0%", "percentSign" : "%", "periodAm" : "Dayperiod", "periodPm" : "Dayperiod", "pluralRule" : "set3", "plusSign" : "+", "scientificFormat" : "#E0", "second" : "ร ยฎยตร ยฎยฟร ยฎยฉร ยฎยพร ยฎยŸร ยฎยฟ", "second_abbr" : "ร ยฎยตร ยฎยฟร ยฎยฉร ยฎยพร ยฎยŸร ยฎยฟ", "seconds" : "ร ยฎยตร ยฎยฟร ยฎยฉร ยฎยพร ยฎยŸร ยฎยฟร ยฎย•ร ยฎยณร ยฏย", "seconds_abbr" : "ร ยฎยตร ยฎยฟร ยฎยฉร ยฎยพร ยฎยŸร ยฎยฟร ยฎย•ร ยฎยณร ยฏย", "today" : "Today", "tomorrow" : "Tomorrow", "weekdayFriLong" : "ร ยฎยตร ยฏย†ร ยฎยณร ยฏยร ยฎยณร ยฎยฟ", "weekdayFriMedium" : "ร ยฎยตร ยฏย†", "weekdayMonLong" : "ร ยฎยคร ยฎยฟร ยฎย™ร ยฏยร ยฎย•ร ยฎยณร ยฏย", "weekdayMonMedium" : "ร ยฎยคร ยฎยฟ", "weekdaySatLong" : "ร ยฎยšร ยฎยฉร ยฎยฟ", "weekdaySatMedium" : "ร ยฎยš", "weekdaySunLong" : "ร ยฎยžร ยฎยพร ยฎยฏร ยฎยฟร ยฎยฑร ยฏย", "weekdaySunMedium" : "ร ยฎยžร ยฎยพ", "weekdayThuLong" : "ร ยฎยตร ยฎยฟร ยฎยฏร ยฎยพร ยฎยดร ยฎยฉร ยฏย", "weekdayThuMedium" : "ร ยฎยตร ยฎยฟ", "weekdayTueLong" : "ร ยฎยšร ยฏย†ร ยฎยตร ยฏยร ยฎยตร ยฎยพร ยฎยฏร ยฏย", "weekdayTueMedium" : "ร ยฎยšร ยฏย†", "weekdayWedLong" : "ร ยฎยชร ยฏยร ยฎยคร ยฎยฉร ยฏย", "weekdayWedMedium" : "ร ยฎยชร ยฏย", "year" : "ร ยฎยตร ยฎยฐร ยฏยร ยฎยŸร ยฎยฎร ยฏย", "year_abbr" : "ร ยฎยตร ยฎยฐร ยฏยร ยฎยŸร ยฎยฎร ยฏย", "years" : "ร ยฎยตร ยฎยฐร ยฏยร ยฎยŸร ยฎย™ร ยฏยร ยฎย•ร ยฎยณร ยฏย", "years_abbr" : "ร ยฎยตร ยฎยฐร ยฏยร ยฎยŸร ยฎย™ร ยฏยร ยฎย•ร ยฎยณร ยฏย", "yesterday" : "Yesterday" }
'use strict'; angular.module('core').directive('featuredProjects', function () { return { restrict: 'EA', templateUrl: 'modules/core/client/directives/views/featured-projects.html', controller: function ($scope, $http) { (function getFeaturedProjs() { $http.get('/api/v1/featured', { cache: true }) .then(function successCallback(resolved) { $scope.featuredProjects = resolved.data; }, function errorCallback(rejected) { return console.log('rejected:\n', rejected); }); })(); } }; });
'use strict'; var createPluginError, failOnWarningReporter, failReporter, loadReporter, reporter, reporterStream, through2; through2 = require('through2'); createPluginError = require('./utils').createPluginError; reporterStream = function(reporterType) { return through2.obj(function(file, enc, cb) { var c, ref, rpt; c = file.coffeelint; if (!c || (c.errorCount === (ref = c.warningCount) && ref === 0)) { this.push(file); return cb(); } rpt = new reporterType(file.coffeelint.results); rpt.publish(); this.push(file); return cb(); }); }; failReporter = function() { return through2.obj(function(file, enc, cb) { if (!file.coffeelint || file.coffeelint.success) { this.push(file); return cb(); } this.emit('error', createPluginError("CoffeeLint failed for " + file.relative)); return cb(); }); }; failOnWarningReporter = function() { return through2.obj(function(file, enc, cb) { var c, ref; c = file.coffeelint; if (!c || (c.errorCount === (ref = c.warningCount) && ref === 0)) { this.push(file); return cb(); } this.emit('error', createPluginError("CoffeeLint failed for " + file.relative)); return cb(); }); }; reporter = function(type) { if (type === 'fail') { return failReporter(); } if (type === 'failOnWarning') { return failOnWarningReporter(); } if (type == null) { type = 'coffeelint-stylish'; } reporter = loadReporter(type); if (typeof reporter !== 'function') { throw createPluginError(type + " is not a valid reporter"); } return reporterStream(reporter); }; loadReporter = function(reporter) { if (typeof reporter === 'function') { return reporter; } if (typeof reporter === 'string') { try { return require("coffeelint/lib/reporters/" + reporter); } catch (undefined) {} try { return require(reporter); } catch (undefined) {} } }; module.exports = reporter;
// Copyright: 2015 AlignAlytics // License: "https://github.com/PMSI-AlignAlytics/dimple/blob/master/MIT-LICENSE.txt" // Source: /src/chart/methods/_handleTransition.js this._handleTransition = function (input, duration, chart, series) { var returnShape = null; if (duration === 0) { returnShape = input; } else { returnShape = input.transition() .duration(duration) .delay(chart._getDelay(duration, chart, series)); dimple._ease(returnShape, chart.ease); } return returnShape; };
const path = require('path'); const ip = require('ip'); module.exports = app => { const exports = {}; exports.view = { cache: false }; exports.static = { maxAge: 0 // maxAge ็ผ“ๅญ˜๏ผŒ้ป˜่ฎค 1 ๅนด }; exports.development = { watchDirs: [], // ๆŒ‡ๅฎš็›‘่ง†็š„็›ฎๅฝ•๏ผˆๅŒ…ๆ‹ฌๅญ็›ฎๅฝ•๏ผ‰๏ผŒๅฝ“็›ฎๅฝ•ไธ‹็š„ๆ–‡ไปถๅ˜ๅŒ–็š„ๆ—ถๅ€™่‡ชๅŠจ้‡่ฝฝๅบ”็”จ๏ผŒ่ทฏๅพ„ไปŽ้กน็›ฎๆ น็›ฎๅฝ•ๅผ€ๅง‹ๅ†™ ignoreDirs: ['app/web', 'public', 'config/manifest.json'] // ๆŒ‡ๅฎš่ฟ‡ๆปค็š„็›ฎๅฝ•๏ผˆๅŒ…ๆ‹ฌๅญ็›ฎๅฝ•๏ผ‰ }; exports.logview = { dir: path.join(app.baseDir, 'logs') }; exports.webpack = { browser: false, webpackConfigList: require('easywebpack-vue').getWebpackConfig() }; const localIP = ip.address(); const domainWhiteList = []; [7001, 9000, 9001].forEach(port => { domainWhiteList.push(`http://localhost:${port}`); domainWhiteList.push(`http://127.0.0.1:${port}`); domainWhiteList.push(`http://${localIP}:${port}`); }); exports.security = { domainWhiteList }; return exports; };
describe('[github/milestone/factory]', function () { var $httpBackend, GithubMilestone, GithubIssue, json; beforeEach(module('ed.github')); beforeEach( inject ( function ( _$httpBackend_, _GithubMilestone_, _GithubIssue_ ) { $httpBackend = _$httpBackend_; GithubMilestone = _GithubMilestone_; GithubIssue = _GithubIssue_; // Example from Github's API docs json = { "url": "https://api.github.com/repos/octocat/Hello-World/milestones/1", "number": 1, "state": "open", "title": "v1.0", "description": "", "creator": { "login": "octocat", "id": 1, "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "open_issues": 4, "closed_issues": 8, "created_at": "2011-04-10T20:09:31Z", "updated_at": "2014-03-03T18:58:10Z", "closed_at": "2013-02-12T13:22:01Z", "due_on": null }; })); // Construction // ------------------------- describe('Construction', function () { it('should be a constructor', function() { expect(GithubMilestone).toEqual( jasmine.any(Function) ); }); // args = 1 it('should store all data properties', function() { var milestone = new GithubMilestone(json); for( var prop in json ) { expect(milestone[prop]).toEqual( json[prop] ); } }); // args = 2 it('should be possible to call with auth token', function() { var token = '123456789', milestone = new GithubMilestone(json, token); expect(milestone._token).toEqual(token); for( var prop in json ) { expect(milestone[prop]).toEqual( json[prop] ); } }); it('should automaticall generate `repo` and `owner', function() { var token = '123456789', milestone = new GithubMilestone(json, token); expect(milestone._owner).toEqual('octocat'); expect(milestone._repo).toEqual('Hello-World'); }); // args = 3 it('should be possible to call with [owner, repo]', function() { var owner = 'mps-gmbh', repo = 'ed', milestone = new GithubMilestone(json, owner, repo); expect(milestone._owner).toEqual(owner); expect(milestone._repo).toEqual(repo); expect(milestone._token).toBeUndefined(); for( var prop in json ) { expect(milestone[prop]).toEqual( json[prop] ); } }); // args = 4 it('should be possible to call with [owner, repo and token]', function() { var owner = 'mps-gmbh', repo = 'ed', token = '123456789', milestone = new GithubMilestone(json, owner, repo, token); expect(milestone._owner).toEqual(owner); expect(milestone._repo).toEqual(repo); expect(milestone._token).toEqual(token); for( var prop in json ) { expect(milestone[prop]).toEqual( json[prop] ); } }); // args = 0 || >4 it('should throw errors if constructor was invoked with falsy arguments', function() { expect(function () { new GithubMilestone(); }).toThrow(); expect(function () { new GithubMilestone( json, 1, 2, 3, 4); }).toThrow(); }); it('should set `html_url` if possible', function() { var owner = 'mps-gmbh', repo = 'ed', milestone = new GithubMilestone(json, owner, repo), data = angular.copy(json); expect(milestone.html_url).toEqual( jasmine.any(String) ); milestone = new GithubMilestone(json); expect(milestone.html_url).toEqual( jasmine.any(String) ); delete data.url; milestone = new GithubMilestone(data); expect(milestone.html_url).toBeUndefined(); data = angular.copy(json); delete data.title; milestone = new GithubMilestone(data); expect(milestone.html_url).toBeUndefined(); }); it('should set `new_issue_url` if possible', function() { var owner = 'mps-gmbh', repo = 'ed', milestone = new GithubMilestone(json, owner, repo), data = angular.copy(json); expect(milestone.new_issue_url).toEqual( jasmine.any(String) ); milestone = new GithubMilestone(json); expect(milestone.new_issue_url).toEqual( jasmine.any(String) ); delete data.url; milestone = new GithubMilestone(data); expect(milestone.new_issue_url).toBeUndefined(); data = angular.copy(json); delete data.title; milestone = new GithubMilestone(data); expect(milestone.new_issue_url).toBeUndefined(); }); }); // Update Progress // ------------------------- describe('Update Progress', function () { var owner, repo, token, milestone; beforeEach(function() { owner = 'mps-gmbh'; repo = 'ed'; token = '123456789'; milestone = new GithubMilestone(json, owner, repo, token); milestone.issues = [{ title: 'I want this to be implemented! Yesterday!', number: 55, state: 'open' }, { title: 'Yet another feature request', number: 1234, state: 'closed' }, { title: 'I found a bug', number: 55, state: 'open', pull_request: { url: 'http://example.com/pull_request' } }, { title: 'Make button "cornflower blue" instead of "deep sky blue"', number: 1234, state: 'open' }]; }); it('should espose a method to update progress', function() { expect(milestone.updateProgress).toEqual( jasmine.any(Function) ); }); it('should be possible to update progress', function() { expect(milestone.progress).toBeUndefined(); milestone.updateProgress(); expect(milestone.progress).toBeDefined(); }); it('should correctly calculate progress (ignore PRs)', function() { milestone.updateProgress(); expect(milestone.progress).toEqual(1/3); milestone.issues[0].state = 'closed'; milestone.updateProgress(); expect(milestone.progress).toEqual(2/3); }); }); // Refresh // ------------------------- describe('Refresh', function () { var owner, repo, token, milestone, milestoneResponse; beforeEach(function() { owner = 'mps-gmbh'; repo = 'ed'; token = '123456789'; milestone = new GithubMilestone(json, owner, repo, token); milestoneResponse = { title: 'Empty Milestone'}; $httpBackend.whenGET(json.url).respond(milestoneResponse); spyOn(GithubMilestone.prototype, 'getIssues'); }); it('should expose a method to refresh', function() { expect(milestone.refresh).toEqual( jasmine.any(Function) ); }); it('should be possible to refresh milestone', function() { milestone.refresh(); $httpBackend.flush(); angular.forEach( json, function ( value, key ) { expect(json[key]).not.toEqual(milestone[key]); }); angular.forEach( milestoneResponse, function ( value, key ) { expect(milestoneResponse[key]).toEqual(milestone[key]); }); }); it('should keep repository data when refreshing', function() { milestone.refresh(); $httpBackend.flush(); expect(milestone._owner).toEqual(owner); expect(milestone._repo).toEqual(repo); expect(milestone._token).toEqual(token); }); it('should return the refreshed milestone (as promise)', function() { var m; milestone.refresh().then(function ( r ) { m = r; }); $httpBackend.flush(); expect(m).toEqual(milestone); }); it('should use auth token if possible', function() { $httpBackend.expectGET(json.url, { 'Authorization': 'token ' + token, 'Accept': 'application/json, text/plain, */*' }); milestone.refresh(); $httpBackend.flush(); }); it('should throw an error if no `url` is specified', function() { expect(function () { delete json.url; milestone = new GithubMilestone(json); milestone.refresh(); }).toThrow(); }); it('should set a loading flag', function() { expect(milestone.isRefreshing).toBeUndefined(); milestone.refresh(); expect(milestone.isRefreshing).toBeTruthy(); $httpBackend.flush(); expect(milestone.isRefreshing).toBeUndefined(); }); it('should fetch issues', function() { milestone.refresh(); $httpBackend.flush(); expect(GithubMilestone.prototype.getIssues).toHaveBeenCalled(); }); }); // Issues // ------------------------- describe('Issues', function () { var owner = 'mps-gmbh', repo = 'ed', token = '123456789', prURL = 'https://api.github.com/repos/mps-gmbh/ed/pulls/1', milestone, issueResponse, prResponse; beforeEach(function() { milestone = new GithubMilestone(json, owner, repo, token); // Fake Backend issueResponse = { '1': [{ title: 'I want this to be implemented! Yesterday!', number: 55, state: 'open' }, { title: 'Yet another feature request', number: 1234, state: 'closed' }], '11': [{ title: 'I found a bug', number: 55, state: 'open', pull_request: { url: prURL } }, { title: 'Make button "cornflower blue" instead of "deep sky blue"', number: 1234, state: 'open' }] }; prResponse = { merged: false, someOtherData: 'that-should-be-merged' }; // Mock server $httpBackend.whenGET(new RegExp('/repos/' + owner + '/' + repo + '/issues')) .respond(function ( method, url ) { var number = url.match(/milestone=(\d+)/)[1]; return [ 200, issueResponse[number] ]; }); $httpBackend.whenGET(prURL) .respond(prResponse); // Spies spyOn( GithubMilestone.prototype, 'updateProgress' ).and.callThrough(); }); it('should expose a method to fetch issues', function() { expect(milestone.getIssues).toEqual( jasmine.any(Function) ); }); it('should be possible to fetch issues', function() { expect(milestone.issues).toBeUndefined(); milestone.getIssues(); $httpBackend.flush(); expect(milestone.issues).toEqual(issueResponse[milestone.number]); }); it('should cast fetched issues to `GithubIssue` objects', function() { milestone.getIssues(); $httpBackend.flush(); milestone.issues.forEach( function ( issue ) { expect( issue instanceof GithubIssue ).toBeTruthy(); }); }); it('should return fetched issues (as promise)', function() { var i; milestone.getIssues().then(function ( r ) { i = r; }); $httpBackend.flush(); expect(milestone.issues).toEqual(i); }); it('should set a loading flag', function() { expect(milestone.isLoadingIssues).toBeUndefined(); milestone.getIssues(); expect(milestone.isLoadingIssues).toBeTruthy(); $httpBackend.flush(); expect(milestone.isLoadingIssues).toBeUndefined(); }); it('should update progress after updating issues', function() { milestone.getIssues(); $httpBackend.flush(); expect(GithubMilestone.prototype.updateProgress).toHaveBeenCalled(); }); // Pull Requests // ------------------------- describe('Pull Requests', function () { beforeEach(function() { angular.extend( milestone, { "url": "https://api.github.com/repos/octocat/Hello-World/milestones/11", "number": 11, }); }); it('should fetch additional PR data for "PR issues"', function() { milestone.getIssues(); $httpBackend.flush(); expect(milestone.pull_requests.length).toEqual(1); }); }); }); });
/* global React */ /* global ReactQuill */ 'use strict'; var Editor = React.createClass({ getInitialState: function() { return { theme: 'snow', enabled: true, readOnly: false, value: '<h1>It works!</h1>', events: [] }; }, formatRange: function(range) { return range ? [range.start, range.end].join(',') : 'none'; }, onTextareaChange: function(event) { var value = event.target.value; this.setState({ value:value }); }, onEditorChange: function(value, delta, source) { this.setState({ value: value, events: [ 'text-change('+this.state.value+' -> '+value+')' ].concat(this.state.events) }); }, onEditorChangeSelection: function(range, source) { this.setState({ selection: range, events: [ 'selection-change('+ this.formatRange(this.state.selection) +' -> '+ this.formatRange(range) +')' ].concat(this.state.events) }); }, onToggle: function() { this.setState({ enabled: !this.state.enabled }); }, onToggleReadOnly: function() { this.setState({ readOnly: !this.state.readOnly }); }, render: function() { return ( React.DOM.div({}, this.renderToolbar(), React.DOM.hr(), this.renderSidebar(), this.state.enabled && ReactQuill({ theme: this.state.theme, value: this.state.value, readOnly: this.state.readOnly, onChange: this.onEditorChange, onChangeSelection: this.onEditorChangeSelection }) ) ); }, renderToolbar: function() { var state = this.state; var enabled = state.enabled; var readOnly = state.readOnly; var selection = this.formatRange(state.selection); return ( React.DOM.div({}, React.DOM.button({ onClick: this.onToggle }, enabled? 'Disable' : 'Enable' ), React.DOM.button({ onClick: this.onToggleReadOnly }, 'Set ' + (readOnly? 'read/Write' : 'read-only') ), React.DOM.button({ disabled: true }, 'Selection: ('+selection+')' ) ) ); }, renderSidebar: function() { return ( React.DOM.div({ style: { overflow:'hidden', float:'right' }}, React.DOM.textarea({ style: { display:'block', width:300, height:300 }, value: this.state.value, onChange: this.onTextareaChange }), React.DOM.textarea({ style: { display:'block', width:300, height:300 }, value: this.state.events.join('\n') }) ) ); } }); Editor = React.createFactory(Editor); ReactQuill = React.createFactory(ReactQuill); ReactDOM.render( Editor(), document.getElementById('app') );
import React from 'react' import Icon from 'react-icon-base' const FaMixcloud = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m28.8 23.5q0-1-0.6-1.8t-1.5-1.2q-0.1 0.8-0.4 1.6-0.1 0.4-0.5 0.6t-0.8 0.3q-0.2 0-0.4-0.1-0.5-0.1-0.8-0.6t-0.1-1.1q0.4-1.2 0.4-2.5 0-2.1-1-3.9t-2.9-2.9-4-1.1q-2.4 0-4.3 1.3t-3 3.4q1.9 0.5 3.3 1.8 0.4 0.4 0.4 1t-0.4 0.9-0.9 0.4-1-0.4q-1.3-1.3-3.1-1.3-1.9 0-3.2 1.3t-1.3 3.2 1.3 3.1 3.2 1.3h18.3q1.4 0 2.3-0.9t1-2.4z m2.7 0q0 2.5-1.8 4.3t-4.2 1.7h-18.3q-3 0-5.1-2.1t-2.1-5q0-2.7 1.8-4.7t4.3-2.4q1.1-3.2 3.9-5.2t6.2-2q4.1 0 7.1 2.8t3.5 6.8q2 0.4 3.3 2.1t1.4 3.7z m4.4 0q0 3.1-1.7 5.6-0.4 0.6-1.2 0.6-0.4 0-0.7-0.2-0.5-0.3-0.6-0.9t0.2-1q1.3-1.8 1.3-4.1t-1.3-4q-0.3-0.5-0.2-1t0.6-0.9 1-0.2 0.9 0.6q1.7 2.5 1.7 5.5z m4.4 0q0 4.3-2.3 7.8-0.4 0.6-1.1 0.6-0.4 0-0.8-0.2-0.4-0.4-0.5-0.9t0.2-1q1.9-2.9 1.9-6.3 0-3.4-1.9-6.2-0.3-0.5-0.2-1t0.5-0.9q0.5-0.3 1-0.2t0.9 0.6q2.3 3.5 2.3 7.7z"/></g> </Icon> ) export default FaMixcloud
module.exports = function() { return { files: [ "src/**/*.js", "spec/testUtil.js", { pattern: "spec/**/*.jsx", instrument: false, load: false, ignore: false } ], tests: ["spec/**/*.js", "!spec/tests.js", "!spec/testUtil.js"], env: { type: "node", runner: "node" }, setup: function(wallaby) { var plugin = require("./src/index"); require("@babel/register")({ presets: ["@babel/preset-react"], plugins: [plugin], cache: false }); } }; };
'use strict'; angular.module('scenarioEditor.manageView', ['ngRoute', 'scenarioServices']) .config(['$routeProvider', function ($routeProvider) { $routeProvider.when('/manageView', { templateUrl: '/scenario/manageView/', controller: 'manageCtrl' }); }]) .controller('manageCtrl', ['$scope', '$http', 'triggerService', 'scenarioService', 'charService', function ($scope, $http, triggerService, scenarioService, charService) { $scope.pendingTrigger = null; $scope.triggerPending = false; $scope.fetchTriggers = function () { triggerService.fetchTriggers(); }; $scope.triggers = function () { return triggerService.triggers(); }; $scope.dataTypes = function () { return triggerService.dataTypes(); }; $scope.addTrigger = function () { $scope.pendingTrigger = new TriggerResource(); $scope.triggerPending = true; }; $scope.scenario = function () { return scenarioService.scenario(); }; $scope.scenarioTypes = function(){ return SCENARIO_TYPES; }; $scope.scenarioOrders = function(){ return SCENARIO_ORDER; }; $scope.submitTrigger = function () { if ($scope.pendingTrigger.id == -1) { for (var i = 0; i < triggerService.triggers().length; i++) { if ($scope.pendingTrigger.type == triggerService.triggers()[i].type) { $scope.$emit('showMessage', ['Trigger Name Must Be Unique', 'danger']); return; } } triggerService.createTrigger($scope.pendingTrigger); } else { triggerService.updateTrigger($scope.pendingTrigger); } $scope.triggerPending = false; $scope.pendingTrigger = null; }; $scope.addArgument = function () { if ($scope.pendingTrigger != null) { $scope.pendingTrigger.args.push(new TriggerArgumentResource()); } }; $scope.deleteTrigger = function (trigger) { triggerService.deleteTrigger(trigger); if ($scope.pendingTrigger != null && $scope.pendingTrigger) { $scope.pendingTrigger = null; $scope.triggerPending = false; } }; $scope.editTrigger = function (trigger) { $scope.pendingTrigger = trigger; $scope.triggerPending = true; }; $scope.getDependsOnOptions = function(arg, trigger){ var options = []; if(arg.dataType == "CHARACTER_STATE"){ for(var i = 0; i < trigger.args.length; i++){ if(trigger.args[i].dataType == "CHARACTER"){ options.push(trigger.args[i]); } } } return options; }; $scope.showDependsOn = function(arg){ return arg.dataType == "CHARACTER_STATE"; } }]);
import classNames from 'classnames'; import keycode from 'keycode'; import React, { cloneElement } from 'react'; import ReactDOM from 'react-dom'; import all from 'react-prop-types/lib/all'; import warning from 'warning'; import { bsClass, bsStyles, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; import createChainedFunction from './utils/createChainedFunction'; import ValidComponentChildren from './utils/ValidComponentChildren'; // TODO: Should we expose `<NavItem>` as `<Nav.Item>`? // TODO: This `bsStyle` is very unlike the others. Should we rename it? // TODO: `pullRight` and `pullLeft` don't render right outside of `navbar`. // Consider renaming or replacing them. const propTypes = { /** * Marks the NavItem with a matching `eventKey` as active. Has a * higher precedence over `activeHref`. */ activeKey: React.PropTypes.any, /** * Marks the child NavItem with a matching `href` prop as active. */ activeHref: React.PropTypes.string, /** * NavItems are be positioned vertically. */ stacked: React.PropTypes.bool, justified: all( React.PropTypes.bool, ({ justified, navbar }) => ( justified && navbar ? Error('justified navbar `Nav`s are not supported') : null ) ), /** * A callback fired when a NavItem is selected. * * ```js * function ( * Any eventKey, * SyntheticEvent event? * ) * ``` */ onSelect: React.PropTypes.func, /** * ARIA role for the Nav, in the context of a TabContainer, the default will * be set to "tablist", but can be overridden by the Nav when set explicitly. * * When the role is set to "tablist" NavItem focus is managed according to * the ARIA authoring practices for tabs: * https://www.w3.org/TR/2013/WD-wai-aria-practices-20130307/#tabpanel */ role: React.PropTypes.string, /** * Apply styling an alignment for use in a Navbar. This prop will be set * automatically when the Nav is used inside a Navbar. */ navbar: React.PropTypes.bool, /** * Float the Nav to the right. When `navbar` is `true` the appropriate * contextual classes are added as well. */ pullRight: React.PropTypes.bool, /** * Float the Nav to the left. When `navbar` is `true` the appropriate * contextual classes are added as well. */ pullLeft: React.PropTypes.bool, }; const defaultProps = { justified: false, pullRight: false, pullLeft: false, stacked: false, }; const contextTypes = { $bs_navbar: React.PropTypes.shape({ bsClass: React.PropTypes.string, onSelect: React.PropTypes.func, }), $bs_tabContainer: React.PropTypes.shape({ activeKey: React.PropTypes.any, onSelect: React.PropTypes.func.isRequired, getTabId: React.PropTypes.func.isRequired, getPaneId: React.PropTypes.func.isRequired, }), }; class Nav extends React.Component { componentDidUpdate() { if (!this._needsRefocus) { return; } this._needsRefocus = false; const { children } = this.props; const { activeKey, activeHref } = this.getActiveProps(); const activeChild = ValidComponentChildren.find(children, child => ( this.isActive(child, activeKey, activeHref) )); const childrenArray = ValidComponentChildren.toArray(children); const activeChildIndex = childrenArray.indexOf(activeChild); const childNodes = ReactDOM.findDOMNode(this).children; const activeNode = childNodes && childNodes[activeChildIndex]; if (!activeNode || !activeNode.firstChild) { return; } activeNode.firstChild.focus(); } handleTabKeyDown(onSelect, event) { let nextActiveChild; switch (event.keyCode) { case keycode.codes.left: case keycode.codes.up: nextActiveChild = this.getNextActiveChild(-1); break; case keycode.codes.right: case keycode.codes.down: nextActiveChild = this.getNextActiveChild(1); break; default: // It was a different key; don't handle this keypress. return; } event.preventDefault(); if (onSelect && nextActiveChild && nextActiveChild.props.eventKey) { onSelect(nextActiveChild.props.eventKey); } this._needsRefocus = true; } getNextActiveChild(offset) { const { children } = this.props; const validChildren = children.filter(child => ( child.props.eventKey && !child.props.disabled )); const { activeKey, activeHref } = this.getActiveProps(); const activeChild = ValidComponentChildren.find(children, child => ( this.isActive(child, activeKey, activeHref) )); // This assumes the active child is not disabled. const activeChildIndex = validChildren.indexOf(activeChild); if (activeChildIndex === -1) { // Something has gone wrong. Select the first valid child we can find. return validChildren[0]; } let nextIndex = activeChildIndex + offset; const numValidChildren = validChildren.length; if (nextIndex >= numValidChildren) { nextIndex = 0; } else if (nextIndex < 0) { nextIndex = numValidChildren - 1; } return validChildren[nextIndex]; } getActiveProps() { const tabContainer = this.context.$bs_tabContainer; if (tabContainer) { warning(this.props.activeKey == null && !this.props.activeHref, 'Specifying a `<Nav>` `activeKey` or `activeHref` in the context of ' + 'a `<TabContainer>` is not supported. Instead use `<TabContainer ' + `activeKey={${this.props.activeKey}} />\`.` ); return tabContainer; } return this.props; } isActive({ props }, activeKey, activeHref) { if ( props.active || activeKey != null && props.eventKey === activeKey || activeHref && props.href === activeHref ) { return true; } return props.active; } getTabProps(child, tabContainer, navRole, active, onSelect) { if (!tabContainer && navRole !== 'tablist') { // No tab props here. return null; } let { id, 'aria-controls': controls, eventKey, role, onKeyDown, tabIndex, } = child.props; if (tabContainer) { warning(!id && !controls, 'In the context of a `<TabContainer>`, `<NavItem>`s are given ' + 'generated `id` and `aria-controls` attributes for the sake of ' + 'proper component accessibility. Any provided ones will be ignored. ' + 'To control these attributes directly, provide a `generateChildId` ' + 'prop to the parent `<TabContainer>`.' ); id = tabContainer.getTabId(eventKey); controls = tabContainer.getPaneId(eventKey); } if (navRole === 'tablist') { role = role || 'tab'; onKeyDown = createChainedFunction( event => this.handleTabKeyDown(onSelect, event), onKeyDown ); tabIndex = active ? tabIndex : -1; } return { id, role, onKeyDown, 'aria-controls': controls, tabIndex, }; } render() { const { stacked, justified, onSelect, role: propsRole, navbar: propsNavbar, pullRight, pullLeft, className, children, ...props } = this.props; const tabContainer = this.context.$bs_tabContainer; const role = propsRole || (tabContainer ? 'tablist' : null); const { activeKey, activeHref } = this.getActiveProps(); delete props.activeKey; // Accessed via this.getActiveProps(). delete props.activeHref; // Accessed via this.getActiveProps(). const [bsProps, elementProps] = splitBsProps(props); const classes = { ...getClassSet(bsProps), [prefix(bsProps, 'stacked')]: stacked, [prefix(bsProps, 'justified')]: justified, }; const navbar = propsNavbar != null ? propsNavbar : this.context.$bs_navbar; let pullLeftClassName; let pullRightClassName; if (navbar) { const navbarProps = this.context.$bs_navbar || { bsClass: 'navbar' }; classes[prefix(navbarProps, 'nav')] = true; pullRightClassName = prefix(navbarProps, 'right'); pullLeftClassName = prefix(navbarProps, 'left'); } else { pullRightClassName = 'pull-right'; pullLeftClassName = 'pull-left'; } classes[pullRightClassName] = pullRight; classes[pullLeftClassName] = pullLeft; return ( <ul {...elementProps} role={role} className={classNames(className, classes)} > {ValidComponentChildren.map(children, child => { const active = this.isActive(child, activeKey, activeHref); const childOnSelect = createChainedFunction( child.props.onSelect, onSelect, navbar && navbar.onSelect, tabContainer && tabContainer.onSelect ); return cloneElement(child, { ...this.getTabProps( child, tabContainer, role, active, childOnSelect ), active, activeKey, activeHref, onSelect: childOnSelect, }); })} </ul> ); } } Nav.propTypes = propTypes; Nav.defaultProps = defaultProps; Nav.contextTypes = contextTypes; export default bsClass('nav', bsStyles(['tabs', 'pills'], Nav) );
/** * fs.watch wrapper that among other things checks SHA1 * of the file to prevent multiple callback calls. * * Related: http://stackoverflow.com/q/12978924/1637178 * * Usage is the same as fs.watch * * var onFileChange = require("on-file-change"); * * // same as fs.watch * onFileChange("myAwesomeFile.txt", function() * { * console.log("Awesome file change!"); * }); * * @author Jan ลšwiฤ™cki <jan.swiecki@gmail.com> */ module.exports = (function() { var crypto = require("crypto"); var fs = require("fs"); var hashSums = {}; var fileWatchers = {}; var getSha1 = function(string) { return crypto.createHash("sha1").update(string).digest("hex"); } var getSha1FromFile = function(path) { if(fs.existsSync(path)) { return getSha1(fs.readFileSync(path)); } else { // if file is moved/deleted then do nothing return hashSums[path]; } } // actual onFileChange function return function(path, callback) { function hasDifferentHash() { var h = getSha1FromFile(path); if(h !== hashSums[path]) { hashSums[path] = h; return true; } else { return false; } } function init() { if(! fs.existsSync(path)) { console.error("Path "+path+" does not exists"); return false; } else { hashSums[path] || (hashSums[path] = getSha1FromFile(path)); // Try to prevent many events to fire at the same time. // When someone is making many almost simultaneous file saves // then SHA1 is sometimes not calculated properly. It happens // probably because halfly saved file is being read. In that // case the only thing we could try to do is to create file lock // in NodeJS that is included by Operating System while saving file. // Later I will try to experiment with fs-ext flock // (https://github.com/baudehlo/node-fs-ext). var execute = true; fileWatchers[path] = fs.watch(path, function(event) { if(execute === true && event === 'change' && hasDifferentHash()) { execute = false; fileWatchers[path].close(); callback(path); init(); } }); } } if(typeof callback === 'function') { if(init() === false) { throw new Error("Cannot initialize"); } return { "close": fileWatchers[path].close }; } else { throw new Error("No callback for onFileChange"); } } }());
// Backbone.BabySitter // ------------------- // v0.0.5 // // Copyright (c)2013 Derick Bailey, Muted Solutions, LLC. // Distributed under MIT license // // http://github.com/babysitterjs/backbone.babysitter // Backbone.ChildViewContainer // --------------------------- // // Provide a container to store, retrieve and // shut down child views. define(function(require){return Backbone.ChildViewContainer = (function(Backbone, _){ // Container Constructor // --------------------- var Container = function(initialViews){ this._views = {}; this._indexByModel = {}; this._indexByCollection = {}; this._indexByCustom = {}; this._updateLength(); this._addInitialViews(initialViews); }; // Container Methods // ----------------- _.extend(Container.prototype, { // Add a view to this container. Stores the view // by `cid` and makes it searchable by the model // and/or collection of the view. Optionally specify // a custom key to store an retrieve the view. add: function(view, customIndex){ var viewCid = view.cid; // store the view this._views[viewCid] = view; // index it by model if (view.model){ this._indexByModel[view.model.cid] = viewCid; } // index it by collection if (view.collection){ this._indexByCollection[view.collection.cid] = viewCid; } // index by custom if (customIndex){ this._indexByCustom[customIndex] = viewCid; } this._updateLength(); }, // Find a view by the model that was attached to // it. Uses the model's `cid` to find it, and // retrieves the view by it's `cid` from the result findByModel: function(model){ var viewCid = this._indexByModel[model.cid]; return this.findByCid(viewCid); }, // Find a view by the collection that was attached to // it. Uses the collection's `cid` to find it, and // retrieves the view by it's `cid` from the result findByCollection: function(col){ var viewCid = this._indexByCollection[col.cid]; return this.findByCid(viewCid); }, // Find a view by a custom indexer. findByCustom: function(index){ var viewCid = this._indexByCustom[index]; return this.findByCid(viewCid); }, // Find by index. This is not guaranteed to be a // stable index. findByIndex: function(index){ return _.values(this._views)[index]; }, // retrieve a view by it's `cid` directly findByCid: function(cid){ return this._views[cid]; }, // Remove a view remove: function(view){ var viewCid = view.cid; // delete model index if (view.model){ delete this._indexByModel[view.model.cid]; } // delete collection index if (view.collection){ delete this._indexByCollection[view.collection.cid]; } // delete custom index var cust; for (var key in this._indexByCustom){ if (this._indexByCustom.hasOwnProperty(key)){ if (this._indexByCustom[key] === viewCid){ cust = key; break; } } } if (cust){ delete this._indexByCustom[cust]; } // remove the view from the container delete this._views[viewCid]; // update the length this._updateLength(); }, // Call a method on every view in the container, // passing parameters to the call method one at a // time, like `function.call`. call: function(method, args){ args = Array.prototype.slice.call(arguments, 1); this.apply(method, args); }, // Apply a method on every view in the container, // passing parameters to the call method one at a // time, like `function.apply`. apply: function(method, args){ var view; // fix for IE < 9 args = args || []; _.each(this._views, function(view, key){ if (_.isFunction(view[method])){ view[method].apply(view, args); } }); }, // Update the `.length` attribute on this container _updateLength: function(){ this.length = _.size(this._views); }, // set up an initial list of views _addInitialViews: function(views){ if (!views){ return; } var view, i, length = views.length; for (i=0; i<length; i++){ view = views[i]; this.add(view); } } }); // Borrowing this code from Backbone.Collection: // http://backbonejs.org/docs/backbone.html#section-106 // // Mix in methods from Underscore, for iteration, and other // collection related features. var methods = ['forEach', 'each', 'map', 'find', 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke', 'toArray', 'first', 'initial', 'rest', 'last', 'without', 'isEmpty', 'pluck']; _.each(methods, function(method) { Container.prototype[method] = function() { var views = _.values(this._views); var args = [views].concat(_.toArray(arguments)); return _[method].apply(_, args); }; }); // return the public API return Container; })(Backbone, _);});
typeof console !== 'undefined' && console.log && console.log('unit-test.js loaded');
/// <reference path="../typings/index.d.ts" /> export * from './zone_utils'; export * from './mongo_cursor_observer'; export * from './mongo_cursor_differ'; export * from './meteor_reactive'; export * from './providers';
'use strict'; describe('Service: resEidolon', function () { // load the service's module beforeEach(module('tbsApp')); // instantiate service var resEidolon; beforeEach(inject(function (_resEidolon_) { resEidolon = _resEidolon_; })); it('should do something', function () { expect(!!resEidolon).toBe(true); }); });
import { messages, ruleName, } from ".." import rules from "../../../rules" import { testRule } from "../../../testUtils" const rule = rules[ruleName] testRule(rule, { ruleName, config: ["always"], accept: [ { code: "a {}", description: "first node ignored", }, { code: "@media { a {} }", description: "nested node ignored", }, { code: "b {}\n\na {}", }, { code: "b {}\r\n\r\na {}", description: "CRLF", }, { code: "b {}\n\r\na {}", description: "Mixed", }, { code: "b {}\n \t\n\na {}", }, { code: "b {}\n\n\ta {}", }, { code: "b {}\r\n\r\n\ta {}", description: "CRLF", } ], reject: [ { code: "b {} a {}", message: messages.expected, }, { code: "b {}\na {}", message: messages.expected, }, { code: "b {}\n\n/* comment here*/\na {}", message: messages.expected, }, { code: "b {}\r\n\r\n/* comment here*/\r\na {}", description: "CRLF", message: messages.expected, } ], }) testRule(rule, { ruleName, config: [ "always", { except: ["after-single-line-comment"] } ], skipBasicChecks: true, accept: [ { code: "/**\n * comment\n*/\n\na {}", }, { code: "/* comment */\na {}", } ], reject: [ { code: "/**\n * comment\n*/\na {}", message: messages.expected, }, { code: "/* comment */\n\na {}", message: messages.rejected, } ], }) testRule(rule, { ruleName, config: [ "always", { ignore: ["after-comment"] } ], skipBasicChecks: true, accept: [ { code: "/* foo */\na {}", }, { code: "/* foo */\n\na {}", }, { code: "/* foo */\r\n\r\na {}", description: "CRLF", } ], reject: [{ code: "b {} a {}", message: messages.expected, }], }) testRule(rule, { ruleName, config: ["never"], accept: [ { code: "\n\na {}", description: "first node ignored", }, { code: "\r\n\r\na {}", description: "first node ignored and CRLF", }, { code: "@media {\n\na {} }", description: "nested node ignored", }, { code: "b {}\na {}", }, { code: "b {}\n \t\na {}", }, { code: "b {}\r\n \t\r\na {}", description: "CRLF", }, { code: "b {}\ta {}", } ], reject: [ { code: "b {}\n\na {}", message: messages.rejected, }, { code: "b {}\t\n\n\ta {}", message: messages.rejected, }, { code: "b {}\t\r\n\r\n\ta {}", description: "CRLF", message: messages.rejected, }, { code: "b {}\n\n/* comment here*/\n\na {}", message: messages.rejected, } ], }) testRule(rule, { ruleName, config: [ "never", { except: ["after-single-line-comment"] } ], skipBasicChecks: true, accept: [ { code: "/**\n * comment\n*/\na {}", }, { code: "/* comment */\n\na {}", } ], reject: [ { code: "/**\n * comment\n*/\n\na {}", message: messages.rejected, }, { code: "/* comment */\na {}", message: messages.expected, } ], }) testRule(rule, { ruleName, config: [ "never", { ignore: ["after-comment"] } ], skipBasicChecks: true, accept: [ { code: "/* foo */\na {}", }, { code: "/* foo */\r\na {}", description: "CRLF", }, { code: "/* foo */\n\na {}", } ], reject: [ { code: "b {}\n\na {}", message: messages.rejected, }, { code: "b {}\r\n\r\na {}", description: "CRLF", message: messages.rejected, } ], }) testRule(rule, { ruleName, config: ["always-multi-line"], accept: [ { code: "a {}", description: "first node ignored", }, { code: "@media { a\n{} }", description: "nested node ignored", }, { code: "b {}\na {}", description: "single-line ignored", }, { code: "b\n{}\n\na\n{}", }, { code: "b\r\n{}\r\n\r\na\r\n{}", description: "CRLF", }, { code: "b\n{}\n \t\n\na\n{}", }, { code: "b {}\n\n\ta\n{}", }, { code: "b {}\r\n\r\n\ta\r\n{}", description: "CRLF", } ], reject: [ { code: "b {} a\n{}", message: messages.expected, }, { code: "b\n{}\na\n{}", message: messages.expected, }, { code: "b\r\n{}\r\na\r\n{}", description: "CRLF", message: messages.expected, }, { code: "b {}\n\n/* comment here*/\na\n{}", message: messages.expected, } ], }) testRule(rule, { ruleName, config: ["never-multi-line"], accept: [ { code: "\n\na\n{}", description: "first node ignored", }, { code: "@media\n{\n\na\n{} }", description: "nested node ignored", }, { code: "@media\r\n{\r\n\r\na\r\n{} }", description: "nested node ignored and CRLF", }, { code: "b {}\n\na {}", description: "single-line ignored", }, { code: "b\n{}\n \t\na\n{}", }, { code: "b\r\n{}\r\n \t\r\na\r\n{}", description: "CRLF", }, { code: "b {}\ta\n{}", } ], reject: [ { code: "b {}\n\na\n{}", message: messages.rejected, }, { code: "b {}\t\n\n\ta\n{}", message: messages.rejected, }, { code: "b {}\t\r\n\r\n\ta\r\n{}", description: "CRLF", message: messages.rejected, }, { code: "b {}\n\n/* comment here*/\n\na\n{}", message: messages.rejected, }, { code: "b {}\r\n\r\n/* comment here*/\r\n\r\na\r\n{}", description: "CRLF", message: messages.rejected, } ], }) testRule(rule, { ruleName, syntax: "less", config: ["always"], accept: [{ code: "a {}\n.mixin-call() {}", description: "ignore non-ouputting Less class mixin definition", }], })
'use strict'; var convert = require('./convert'), func = convert('toArray', require('../toArray'), require('./_falseOptions')); func.placeholder = require('./placeholder'); module.exports = func; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL2NsaWVudC9saWIvbG9kYXNoL2ZwL3RvQXJyYXkuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxJQUFJLFVBQVUsUUFBUSxXQUFSLENBQWQ7SUFDSSxPQUFPLFFBQVEsU0FBUixFQUFtQixRQUFRLFlBQVIsQ0FBbkIsRUFBMEMsUUFBUSxpQkFBUixDQUExQyxDQURYOztBQUdBLEtBQUssV0FBTCxHQUFtQixRQUFRLGVBQVIsQ0FBbkI7QUFDQSxPQUFPLE9BQVAsR0FBaUIsSUFBakIiLCJmaWxlIjoidG9BcnJheS5qcyIsInNvdXJjZXNDb250ZW50IjpbInZhciBjb252ZXJ0ID0gcmVxdWlyZSgnLi9jb252ZXJ0JyksXG4gICAgZnVuYyA9IGNvbnZlcnQoJ3RvQXJyYXknLCByZXF1aXJlKCcuLi90b0FycmF5JyksIHJlcXVpcmUoJy4vX2ZhbHNlT3B0aW9ucycpKTtcblxuZnVuYy5wbGFjZWhvbGRlciA9IHJlcXVpcmUoJy4vcGxhY2Vob2xkZXInKTtcbm1vZHVsZS5leHBvcnRzID0gZnVuYztcbiJdfQ==
import React from "react" import classnames from "classnames" import { SHOW_ALL, SHOW_COMPLETED, SHOW_ACTIVE } from "../constants/TodoFilters" import { observer } from "mobx-react-lite" const FILTER_TITLES = { [SHOW_ALL]: "All", [SHOW_ACTIVE]: "Active", [SHOW_COMPLETED]: "Completed" } function Footer({ store }) { function renderTodoCount() { const { activeCount } = store const itemWord = activeCount === 1 ? "item" : "items" return ( <span className="todo-count"> <strong>{activeCount || "No"}</strong> {itemWord} left </span> ) } function renderFilterLink(filter) { const title = FILTER_TITLES[filter] const selectedFilter = store.filter return ( // eslint-disable-next-line <a className={classnames({ selected: filter === selectedFilter })} style={{ cursor: "pointer" }} onClick={() => store.setFilter(filter)} > {title} </a> ) } function renderClearButton() { const { completedCount, clearCompleted } = store if (completedCount > 0) { return ( <button className="clear-completed" onClick={() => clearCompleted()}> Clear completed </button> ) } } return ( <footer className="footer"> {renderTodoCount()} <ul className="filters"> {[SHOW_ALL, SHOW_ACTIVE, SHOW_COMPLETED].map((filter) => ( <li key={filter}>{renderFilterLink(filter)}</li> ))} </ul> {renderClearButton()} </footer> ) } export default observer(Footer)
var _recentDataOpts = { limit: 5, sort: { createTimeMillis: -1 } }; Template.dataHome.helpers({ recentDatasets: function () { return Collections.Datasets.find({}, _recentDataOpts); } }); Template.dataHome.events({ });
import { combineReducers } from 'redux'; import data from 'reducers/data'; import errors from 'reducers/errors'; import loading from 'reducers/loading'; jest.mock('redux'); jest.mock('reducers/data'); jest.mock('reducers/errors'); jest.mock('reducers/loading'); describe('reducer index', () => { it('combines all my reducers', () => { // neccessary because the combining is done on export require('reducers'); // eslint-disable-line global-require expect(combineReducers).lastCalledWith({ data, errors, loading }); }); });
Elm.Native.TestUtil = {}; Elm.Native.TestUtil.make = function (localRuntime) { localRuntime.Native = localRuntime.Native || {}; localRuntime.Native.TestUtil = localRuntime.Native.TestUtil || {}; if (!localRuntime.Native.TestUtil.values) { var Task = Elm.Native.Task.make(localRuntime); var Signal = Elm.Native.Signal.make(localRuntime); var sample = function (signal) { // Use closure to track value var val = signal.value; var handler = function (value) { val = value; }; // We construct a new "output" node, because otherwise the incoming // signal may be pruned by trimDeadNodes() in Runtime.js // (if trimDeadNodes() sees that it is not otherwise used). var output = Signal.output("sample-" + signal.name, handler, signal); return Task.asyncFunction(function (callback) { // Need to return the value inside setTimeout, because // otherwise we can be called out-of-order ... that is, a // previous `Task.andThen` which updated a Signal may not have // actually completed yet unless we do this inside a timeout. localRuntime.setTimeout(function () { callback(Task.succeed(val)); }, 0); }); }; localRuntime.Native.TestUtil.values = { sample: sample }; } return localRuntime.Native.TestUtil.values; };
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = memoize; var _identity = require('lodash/identity'); var _identity2 = _interopRequireDefault(_identity); var _slice = require('./internal/slice'); var _slice2 = _interopRequireDefault(_slice); var _setImmediate = require('./internal/setImmediate'); var _setImmediate2 = _interopRequireDefault(_setImmediate); var _initialParams = require('./internal/initialParams'); var _initialParams2 = _interopRequireDefault(_initialParams); var _wrapAsync = require('./internal/wrapAsync'); var _wrapAsync2 = _interopRequireDefault(_wrapAsync); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function has(obj, key) { return key in obj; } /** * Caches the results of an async function. When creating a hash to store * function results against, the callback is omitted from the hash and an * optional hash function can be used. * * If no hash function is specified, the first argument is used as a hash key, * which may work reasonably if it is a string or a data type that converts to a * distinct string. Note that objects and arrays will not behave reasonably. * Neither will cases where the other arguments are significant. In such cases, * specify your own hash function. * * The cache of results is exposed as the `memo` property of the function * returned by `memoize`. * * @name memoize * @static * @memberOf module:Utils * @method * @category Util * @param {AsyncFunction} fn - The async function to proxy and cache results from. * @param {Function} hasher - An optional function for generating a custom hash * for storing results. It has all the arguments applied to it apart from the * callback, and must be synchronous. * @returns {AsyncFunction} a memoized version of `fn` * @example * * var slow_fn = function(name, callback) { * // do something * callback(null, result); * }; * var fn = async.memoize(slow_fn); * * // fn can now be used as if it were slow_fn * fn('some name', function() { * // callback * }); */ function memoize(fn, hasher) { var memo = Object.create(null); var queues = Object.create(null); hasher = hasher || _identity2.default; var _fn = (0, _wrapAsync2.default)(fn); var memoized = (0, _initialParams2.default)(function memoized(args, callback) { var key = hasher.apply(null, args); if (has(memo, key)) { (0, _setImmediate2.default)(function () { callback.apply(null, memo[key]); }); } else if (has(queues, key)) { queues[key].push(callback); } else { queues[key] = [callback]; _fn.apply(null, args.concat(function () /*args*/{ var args = (0, _slice2.default)(arguments); memo[key] = args; var q = queues[key]; delete queues[key]; for (var i = 0, l = q.length; i < l; i++) { q[i].apply(null, args); } })); } }); memoized.memo = memo; memoized.unmemoized = fn; return memoized; } module.exports = exports['default'];
export const Server = { loadJSON: function(url, json_data, done=()=>{}, error=()=>{}) { let response = {}; switch(url) { case '/your/path/to/action': fetch('/your/path/to/data.json') .then(response => { return response.json(); }) .then(data => { response = data; }); break; } setTimeout(() => { done(response); }, 500); }, saveJSON: function(url, json_data, done=()=>{}, error=()=>{}) { let response = true; switch(url) { case '/your/path/to/action': response = { id: Math.floor(Math.random() * (1000000 - 1000 + 1)) + 1000 }; break; } setTimeout(() => { done(response); }, 500); } };
var assert = require('assert'); var Kareem = require('../'); /* Much like [hooks](https://npmjs.org/package/hooks), kareem lets you define * pre and post hooks: pre hooks are called before a given function executes. * Unlike hooks, kareem stores hooks and other internal state in a separate * object, rather than relying on inheritance. Furthermore, kareem exposes * an `execPre()` function that allows you to execute your pre hooks when * appropriate, giving you more fine-grained control over your function hooks. */ describe('pre hooks', function() { var hooks; beforeEach(function() { hooks = new Kareem(); }); it('runs without any hooks specified', function(done) { hooks.execPre('cook', null, function() { done(); }); }); /* pre hook functions take one parameter, a "done" function that you execute * when your pre hook is finished. */ it('runs basic serial pre hooks', function(done) { var count = 0; hooks.pre('cook', function(done) { ++count; done(); }); hooks.execPre('cook', null, function() { assert.equal(1, count); done(); }); }); it('can run multipe pre hooks', function(done) { var count1 = 0; var count2 = 0; hooks.pre('cook', function(done) { ++count1; done(); }); hooks.pre('cook', function(done) { ++count2; done(); }); hooks.execPre('cook', null, function() { assert.equal(1, count1); assert.equal(1, count2); done(); }); }); /* If your pre hook function takes no parameters, its assumed to be * fully synchronous. */ it('can run fully synchronous pre hooks', function(done) { var count1 = 0; var count2 = 0; hooks.pre('cook', function() { ++count1; }); hooks.pre('cook', function() { ++count2; }); hooks.execPre('cook', null, function(error) { assert.equal(null, error); assert.equal(1, count1); assert.equal(1, count2); done(); }); }); /* Pre save hook functions are bound to the second parameter to `execPre()` */ it('properly attaches context to pre hooks', function(done) { hooks.pre('cook', function(done) { this.bacon = 3; done(); }); hooks.pre('cook', function(done) { this.eggs = 4; done(); }); var obj = { bacon: 0, eggs: 0 }; // In the pre hooks, `this` will refer to `obj` hooks.execPre('cook', obj, function(error) { assert.equal(null, error); assert.equal(3, obj.bacon); assert.equal(4, obj.eggs); done(); }); }); /* Like the hooks module, you can declare "async" pre hooks - these take two * parameters, the functions `next()` and `done()`. `next()` passes control to * the next pre hook, but the underlying function won't be called until all * async pre hooks have called `done()`. */ it('can execute parallel (async) pre hooks', function(done) { hooks.pre('cook', true, function(next, done) { this.bacon = 3; next(); setTimeout(function() { done(); }, 5); }); hooks.pre('cook', true, function(next, done) { next(); var _this = this; setTimeout(function() { _this.eggs = 4; done(); }, 10); }); hooks.pre('cook', function(next) { this.waffles = false; next(); }); var obj = { bacon: 0, eggs: 0 }; hooks.execPre('cook', obj, function() { assert.equal(3, obj.bacon); assert.equal(4, obj.eggs); assert.equal(false, obj.waffles); done(); }); }); }); describe('post hooks', function() { var hooks; beforeEach(function() { hooks = new Kareem(); }); it('runs without any hooks specified', function(done) { hooks.execPost('cook', null, [1], function(error, eggs) { assert.ifError(error); assert.equal(1, eggs); done(); }); }); it('executes with parameters passed in', function(done) { hooks.post('cook', function(eggs, bacon, callback) { assert.equal(1, eggs); assert.equal(2, bacon); callback(); }); hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { assert.ifError(error); assert.equal(1, eggs); assert.equal(2, bacon); done(); }); }); it('can use synchronous post hooks', function(done) { var execed = {}; hooks.post('cook', function(eggs, bacon) { execed.first = true; assert.equal(1, eggs); assert.equal(2, bacon); }); hooks.post('cook', function(eggs, bacon, callback) { execed.second = true; assert.equal(1, eggs); assert.equal(2, bacon); callback(); }); hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { assert.ifError(error); assert.equal(2, Object.keys(execed).length); assert.ok(execed.first); assert.ok(execed.second); assert.equal(1, eggs); assert.equal(2, bacon); done(); }); }); }); describe('wrap()', function() { var hooks; beforeEach(function() { hooks = new Kareem(); }); it('wraps pre and post calls into one call', function(done) { hooks.pre('cook', true, function(next, done) { this.bacon = 3; next(); setTimeout(function() { done(); }, 5); }); hooks.pre('cook', true, function(next, done) { next(); var _this = this; setTimeout(function() { _this.eggs = 4; done(); }, 10); }); hooks.pre('cook', function(next) { this.waffles = false; next(); }); hooks.post('cook', function(obj) { obj.tofu = 'no'; }); var obj = { bacon: 0, eggs: 0 }; var args = [obj]; args.push(function(error, result) { assert.ifError(error); assert.equal(null, error); assert.equal(3, obj.bacon); assert.equal(4, obj.eggs); assert.equal(false, obj.waffles); assert.equal('no', obj.tofu); assert.equal(obj, result); done(); }); hooks.wrap( 'cook', function(o, callback) { assert.equal(3, obj.bacon); assert.equal(4, obj.eggs); assert.equal(false, obj.waffles); assert.equal(undefined, obj.tofu); callback(null, o); }, obj, args); }); }); describe('createWrapper()', function() { var hooks; beforeEach(function() { hooks = new Kareem(); }); it('wraps wrap() into a callable function', function(done) { hooks.pre('cook', true, function(next, done) { this.bacon = 3; next(); setTimeout(function() { done(); }, 5); }); hooks.pre('cook', true, function(next, done) { next(); var _this = this; setTimeout(function() { _this.eggs = 4; done(); }, 10); }); hooks.pre('cook', function(next) { this.waffles = false; next(); }); hooks.post('cook', function(obj) { obj.tofu = 'no'; }); var obj = { bacon: 0, eggs: 0 }; var cook = hooks.createWrapper( 'cook', function(o, callback) { assert.equal(3, obj.bacon); assert.equal(4, obj.eggs); assert.equal(false, obj.waffles); assert.equal(undefined, obj.tofu); callback(null, o); }, obj); cook(obj, function(error, result) { assert.ifError(error); assert.equal(3, obj.bacon); assert.equal(4, obj.eggs); assert.equal(false, obj.waffles); assert.equal('no', obj.tofu); assert.equal(obj, result); done(); }); }); }); describe('clone()', function() { it('clones a Kareem object', function() { var k1 = new Kareem(); k1.pre('cook', function() {}); k1.post('cook', function() {}); var k2 = k1.clone(); assert.deepEqual(['cook'], Object.keys(k2._pres)); assert.deepEqual(['cook'], Object.keys(k2._posts)); }); });
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @generated SignedSource<<713bfba9717046b5de96c3132c59fb0c>> * @flow * @lightSyntaxTransform * @nogrep */ /* eslint-disable */ 'use strict'; /*:: import type { ConcreteRequest } from 'relay-runtime'; type RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserProfile$ref = any; export type RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserQueryVariables = {||}; export type RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserQueryResponse = {| +me: ?{| +$fragmentRefs: RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserProfile$ref, |}, |}; export type RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserQuery = {| variables: RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserQueryVariables, response: RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserQueryResponse, |}; */ var node/*: ConcreteRequest*/ = { "fragment": { "argumentDefinitions": [], "kind": "Fragment", "metadata": null, "name": "RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserQuery", "selections": [ { "alias": null, "args": null, "concreteType": "User", "kind": "LinkedField", "name": "me", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserProfile" } ], "storageKey": null } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": [], "kind": "Operation", "name": "RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserQuery", "selections": [ { "alias": null, "args": null, "concreteType": "User", "kind": "LinkedField", "name": "me", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "profilePicture", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "uri", "storageKey": null } ], "storageKey": null } ], "storageKey": null } ] }, "params": { "cacheID": "67244ccc67f3b73bf01392a31b0627a6", "id": null, "metadata": {}, "name": "RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserQuery", "operationKind": "query", "text": "query RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserQuery {\n me {\n ...RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserProfile\n id\n }\n}\n\nfragment RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserProfile on User {\n id\n ...RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserProfilePicture_273SL1\n}\n\nfragment RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserProfilePicture_273SL1 on User {\n profilePicture {\n uri\n }\n}\n" } }; if (__DEV__) { (node/*: any*/).hash = "7a9eaa1476798159533ae048a3ff048a"; } module.exports = node;
import Ember from 'ember'; export default Ember.Component.extend({ session: Ember.inject.service('session'), actions: { invalidateSession: function() { this.get('session').invalidate(); } } });
var Entity = require('./entity'); var Globals = require('./globals'); /* Bullet entity. */ module.exports = function () { "use strict"; this.velocity = 0.0; this.damage = 1; this.till_death = Globals.BULLET_LIVE_TIME; this.type = Globals.BULLET_ENTITY; this.radius = Globals.BULLET_RADIUS; this.owner = null; }; module.exports.prototype = new Entity();
/** * ClusterStatus module. * @module components/ClusterStatus */ import ClusterStatus from './cluster-status.component.jsx'; /** * The ClusterStatus component * @return {object} The ClusterStatus component. */ module.exports = ClusterStatus;
require('dotenv').config(); const path = require('path'); const cp = require('child_process'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const S3Plugin = require('webpack-s3-plugin'); const RollbarSourcemapPlugin = require('../../dist/RollbarSourceMapPlugin'); const rollbarClientAccessToken = process.env.ROLLBAR_CLIENT_TOKEN; const rollbarServerAccessToken = process.env.ROLLBAR_SERVER_TOKEN; const bucket = process.env.AWS_S3_BUCKET; const s3Options = { accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, region: process.env.AWS_REGION }; const basePath = 'assets'; const publicPath = `https://s3-${s3Options.region}.amazonaws.com/${bucket}/${basePath}`; let version; try { version = cp.execSync('git rev-parse HEAD', { cwd: __dirname, encoding: 'utf8' }); } catch (err) { console.log('Error getting revision', err); // eslint-disable-line no-console process.exit(1); } module.exports = { mode: 'production', devtool: 'hidden-source-map', entry: { app: './src/index' }, output: { path: path.join(__dirname, 'dist'), publicPath, filename: '[name]-[chunkhash].js', chunkFilename: '[name]-[chunkhash].js' }, optimization: { minimize: true, splitChunks: { chunks: 'initial' } }, plugins: [ new webpack.DefinePlugin({ /* eslint-disable quote-props */ 'process.env': { NODE_ENV: JSON.stringify(process.env.NODE_ENV) }, /* eslint-enable quote-props */ __ROLLBAR_ACCESS_TOKEN__: JSON.stringify(rollbarClientAccessToken), __GIT_REVISION__: JSON.stringify(version) }), new HtmlWebpackPlugin({ template: 'src/index.html' }), // Publish minified source new S3Plugin({ include: /\.js$/, basePath, s3Options, s3UploadOptions: { Bucket: bucket, ACL: 'public-read', ContentType: 'application/javascript' } }), // Publish sourcemap, but keep it private new S3Plugin({ include: /\.map$/, basePath: `${basePath}`, s3Options, s3UploadOptions: { Bucket: bucket, ACL: 'private', ContentType: 'application/json' } }), // Upload emitted sourcemaps to rollbar new RollbarSourcemapPlugin({ accessToken: rollbarServerAccessToken, version, publicPath }) ], module: { rules: [ { test: /\.js$/, exclude: /node_modules/, include: path.join(__dirname, 'src'), use: [ { loader: 'babel-loader', options: { babelrc: false, presets: [ '@babel/preset-react', [ '@babel/preset-env', { targets: { browsers: ['last 2 versions'] } } ] ] } } ] } ] } };
/** * Copyright 2016 Facebook, Inc. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to * use, copy, modify, and distribute this software in source code or binary * form for use in connection with the web services and APIs provided by * Facebook. * * As with any software that integrates with the Facebook platform, your use * of this software is subject to the Facebook Developer Principles and * Policies [http://developers.facebook.com/policy/]. This copyright 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 * * @providesModule F8FriendGoing * @flow */ 'use strict'; var ProfilePicture = require('../../common/ProfilePicture'); var React = require('React'); var StyleSheet = require('StyleSheet'); var { Text } = require('F8Text'); var View = require('View'); var Image = require('Image'); var F8Touchable = require('F8Touchable'); import type {FriendsSchedule} from '../../reducers/friendsSchedules'; class F8FriendGoing extends React.Component { props: { onPress: () => void; friend: FriendsSchedule; }; render() { return ( <F8Touchable onPress={this.props.onPress}> <View style={styles.container}> <ProfilePicture userID={this.props.friend.id} size={18} /> <Text style={styles.name}> {this.props.friend.name} </Text> <Image source={require('../../common/img/disclosure.png')} /> </View> </F8Touchable> ); } } var styles = StyleSheet.create({ container: { flexDirection: 'row', alignItems: 'center', paddingVertical: 10, backgroundColor: 'white', }, name: { marginLeft: 10, fontSize: 15, flex: 1, }, }); module.exports = F8FriendGoing;
/** * @license * Pixi.JS - v1.0.0 * Copyright (c) 2012, Mat Groves * http://goodboydigital.com/ * * Compiled: 2013-04-08 * * Pixi.JS is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license.php */ /** * @author Mat Groves http://matgroves.com/ @Doormat23 */ /** @module PIXI */ var PIXI = PIXI || {}; /** * @author Mat Groves http://matgroves.com/ @Doormat23 */ /** * The Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis. * @class Point * @constructor * @param x {Number} position of the point * @param y {Number} position of the point */ PIXI.Point = function(x, y) { /** * @property x * @type Number * @default 0 */ this.x = x || 0; /** * @property y * @type Number * @default 0 */ this.y = y || 0; } /** * @method clone * @return a copy of the point */ PIXI.Point.clone = function() { return new PIXI.Point(this.x, this.y); } // constructor PIXI.Point.constructor = PIXI.Point; /** * @author Mat Groves http://matgroves.com/ */ /** * the Rectangle object is an area defined by its position, as indicated by its top-left corner point (x, y) and by its width and its height. * @class Rectangle * @constructor * @param x {Number} position of the rectangle * @param y {Number} position of the rectangle * @param width {Number} of the rectangle * @param height {Number} of the rectangle */ PIXI.Rectangle = function(x, y, width, height) { /** * @property x * @type Number * @default 0 */ this.x = x || 0; /** * @property y * @type Number * @default 0 */ this.y = y || 0; /** * @property width * @type Number * @default 0 */ this.width = width || 0; /** * @property height * @type Number * @default 0 */ this.height = height || 0; } /** * @method clone * @return a copy of the rectangle */ PIXI.Rectangle.clone = function() { return new PIXI.Rectangle(this.x, this.y, this.width, this.height); } // constructor PIXI.Rectangle.constructor = PIXI.Rectangle; /** * @author Mat Groves http://matgroves.com/ @Doormat23 */ /** * this is the base class for all objects that are rendered on the screen. * @class DisplayObject * @constructor */ PIXI.DisplayObject = function() { /** * The coordinate of the object relative to the local coordinates of the parent. * @property position * @type Point */ this.position = new PIXI.Point(); /** * The scale factor of the object. * @property scale * @type Point */ this.scale = new PIXI.Point(1,1);//{x:1, y:1}; /** * The rotation of the object in radians. * @property rotation * @type Number */ this.rotation = 0; /** * The opacity of the object. * @property alpha * @type Number */ this.alpha = 1; /** * The visibility of the object. * @property visible * @type Boolean */ this.visible = true; this.cacheVisible = false; /** * [read-only] The display object container that contains this display object. * @property parent * @type DisplayObjectContainer */ this.parent = null; /** * [read-only] The stage the display object is connected to, or undefined if it is not connected to the stage. * @property stage * @type Stage */ this.stage = null; this.worldAlpha = 1; this.color = []; this.worldTransform = PIXI.mat3.create()//mat3.identity(); this.localTransform = PIXI.mat3.create()//mat3.identity(); this.dynamic = true; // chach that puppy! this._sr = 0; this._cr = 1; this.renderable = false; // NOT YET :/ This only applies to children within the container.. this.interactive = true; } // constructor PIXI.DisplayObject.constructor = PIXI.DisplayObject; /** * @private */ PIXI.DisplayObject.prototype.updateTransform = function() { // TODO OPTIMIZE THIS!! with dirty if(this.rotation != this.rotationCache) { this.rotationCache = this.rotation; this._sr = Math.sin(this.rotation); this._cr = Math.cos(this.rotation); } var localTransform = this.localTransform; var parentTransform = this.parent.worldTransform; var worldTransform = this.worldTransform; //console.log(localTransform) localTransform[0] = this._cr * this.scale.x; localTransform[1] = -this._sr * this.scale.y localTransform[3] = this._sr * this.scale.x; localTransform[4] = this._cr * this.scale.y; ///AAARR GETTER SETTTER! localTransform[2] = this.position.x; localTransform[5] = this.position.y; // Cache the matrix values (makes for huge speed increases!) var a00 = localTransform[0], a01 = localTransform[1], a02 = localTransform[2], a10 = localTransform[3], a11 = localTransform[4], a12 = localTransform[5], b00 = parentTransform[0], b01 = parentTransform[1], b02 = parentTransform[2], b10 = parentTransform[3], b11 = parentTransform[4], b12 = parentTransform[5]; worldTransform[0] = b00 * a00 + b01 * a10; worldTransform[1] = b00 * a01 + b01 * a11; worldTransform[2] = b00 * a02 + b01 * a12 + b02; worldTransform[3] = b10 * a00 + b11 * a10; worldTransform[4] = b10 * a01 + b11 * a11; worldTransform[5] = b10 * a02 + b11 * a12 + b12; // because we are using affine transformation, we can optimise the matrix concatenation process.. wooo! // mat3.multiply(this.localTransform, this.parent.worldTransform, this.worldTransform); this.worldAlpha = this.alpha * this.parent.worldAlpha; } /** * @author Mat Groves http://matgroves.com/ @Doormat23 */ /** * A DisplayObjectContainer represents a collection of display objects. It is the base class of all display objects that act as a container for other objects. * @class DisplayObjectContainer * @extends DisplayObject * @constructor */ PIXI.DisplayObjectContainer = function() { PIXI.DisplayObject.call( this ); /** * [read-only] The of children of this container. * @property children {Array} */ this.children = []; //s this.renderable = false; } // constructor PIXI.DisplayObjectContainer.constructor = PIXI.DisplayObjectContainer; PIXI.DisplayObjectContainer.prototype = Object.create( PIXI.DisplayObject.prototype ); /** * Adds a child to the container. * @method addChild * @param DisplayObject {DisplayObject} */ PIXI.DisplayObjectContainer.prototype.addChild = function(child) { if(child.parent != undefined) { child.parent.removeChild(child) } child.parent = this; child.childIndex = this.children.length; this.children.push(child); if(this.stage) { this.stage.__addChild(child); } } /** * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown * @method addChildAt * @param DisplayObject {DisplayObject} * @param index {Number} */ PIXI.DisplayObjectContainer.prototype.addChildAt = function(child, index) { if(index >= 0 && index <= this.children.length) { if(child.parent != undefined) { child.parent.removeChild(child); } if (index == this.children.length) { this.children.push(child); } else { this.children.splice(index, 0, child); } child.parent = this; child.childIndex = index; var length = this.children.length; for (var i=index; i < length; i++) { this.children[i].childIndex = i; } if(this.stage) { this.stage.__addChild(child); } } else { // error! throw new Error(child + " The index "+ index +" supplied is out of bounds " + this.children.length); } } /** * Removes a child from the container. * @method removeChild * @param DisplayObject {DisplayObject} */ PIXI.DisplayObjectContainer.prototype.removeChild = function(child) { var index = this.children.indexOf( child ); if ( index !== -1 ) { if(this.stage)this.stage.__removeChild(child); child.parent = undefined; //child.childIndex = 0 this.children.splice( index, 1 ); // update in dexs! for(var i=index,j=this.children.length; i<j; i++) { this.children[i].childIndex -= 1; } } else { throw new Error(child + " The supplied DisplayObject must be a child of the caller " + this); } } /** * @private */ PIXI.DisplayObjectContainer.prototype.updateTransform = function() { if(!this.visible)return; PIXI.DisplayObject.prototype.updateTransform.call( this ); for(var i=0,j=this.children.length; i<j; i++) { this.children[i].updateTransform(); } } /** * @author Mat Groves http://matgroves.com/ @Doormat23 */ PIXI.blendModes = {}; PIXI.blendModes.NORMAL = 0; PIXI.blendModes.SCREEN = 1; /** @class Sprite @extends DisplayObjectContainer @constructor @param texture {Texture} @type String */ PIXI.Sprite = function(texture) { PIXI.DisplayObjectContainer.call( this ); /** * The anchor sets the origin point of the texture. * The default is 0,0 this means the textures origin is the top left * Setting than anchor to 0.5,0.5 means the textures origin is centered * Setting the anchor to 1,1 would mean the textures origin points will be the bottom right * @property anchor * @type Point */ this.anchor = new PIXI.Point(); /** * The texture that the sprite is using * @property texture * @type Texture */ this.texture = texture; /** * The blend mode of sprite. * currently supports PIXI.blendModes.NORMAL and PIXI.blendModes.SCREEN * @property blendMode * @type uint */ this.blendMode = PIXI.blendModes.NORMAL; /** * The width of the sprite (this is initially set by the texture) * @property width * @type #Number */ this.width = 1; /** * The height of the sprite (this is initially set by the texture) * @property height * @type #Number */ this.height = 1; if(texture.baseTexture.hasLoaded) { this.width = this.texture.frame.width; this.height = this.texture.frame.height; this.updateFrame = true; } else { this.onTextureUpdateBind = this.onTextureUpdate.bind(this); this.texture.addEventListener( 'update', this.onTextureUpdateBind ); } this.renderable = true; // [readonly] best not to toggle directly! use setInteractive() this.interactive = false; // thi next bit is here for the docs... /* * MOUSE Callbacks */ /** * A callback that is used when the users clicks on the sprite with thier mouse * @method click * @param interactionData {InteractionData} */ /** * A callback that is used when the user clicks the mouse down over the sprite * @method mousedown * @param interactionData {InteractionData} */ /** * A callback that is used when the user releases the mouse that was over the sprite * for this callback to be fired the mouse must have been pressed down over the sprite * @method mouseup * @param interactionData {InteractionData} */ /** * A callback that is used when the users mouse rolls over the sprite * @method mouseover * @param interactionData {InteractionData} */ /** * A callback that is used when the users mouse leaves the sprite * @method mouseout * @param interactionData {InteractionData} */ /* * TOUCH Callbacks */ /** * A callback that is used when the users taps on the sprite with thier finger * basically a touch version of click * @method tap * @param interactionData {InteractionData} */ /** * A callback that is used when the user touch's over the sprite * @method touchstart * @param interactionData {InteractionData} */ /** * A callback that is used when the user releases the touch that was over the sprite * for this callback to be fired. The touch must have started over the sprite * @method touchend * @param interactionData {InteractionData} */ } // constructor PIXI.Sprite.constructor = PIXI.Sprite; PIXI.Sprite.prototype = Object.create( PIXI.DisplayObjectContainer.prototype ); /** @method setTexture @param texture {Texture} The PIXI texture that is displayed by the sprite */ PIXI.Sprite.prototype.setTexture = function(texture) { // stop current texture; if(this.texture.baseTexture != texture.baseTexture) { this.textureChange = true; } this.texture = texture; this.width = texture.frame.width; this.height = texture.frame.height; this.updateFrame = true; } /** * Indicates if the sprite will have touch and mouse interactivity. It is false by default * @method setInteractive * @param interactive {Boolean} */ PIXI.Sprite.prototype.setInteractive = function(interactive) { this.interactive = interactive; // TODO more to be done here.. // need to sort out a re-crawl! if(this.stage)this.stage.dirty = true; } /** * @private */ PIXI.Sprite.prototype.onTextureUpdate = function(event) { this.width = this.texture.frame.width; this.height = this.texture.frame.height; this.updateFrame = true; } // some helper functions.. /** * * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId * The frame ids are created when a Texture packer file has been loaded * @method fromFrame * @static * @param frameId {String} The frame Id of the texture in the cache * @return {Sprite} A new Sprite using a texture from the texture cache matching the frameId */ PIXI.Sprite.fromFrame = function(frameId) { var texture = PIXI.TextureCache[frameId]; if(!texture)throw new Error("The frameId '"+ frameId +"' does not exist in the texture cache" + this); return new PIXI.Sprite(texture); } /** * * Helper function that creates a sprite that will contain a texture based on an image url * If the image is not in the texture cache it will be loaded * @method fromImage * @static * @param The image url of the texture * @return {Sprite} A new Sprite using a texture from the texture cache matching the image id */ PIXI.Sprite.fromImage = function(imageId) { var texture = PIXI.Texture.fromImage(imageId); return new PIXI.Sprite(texture); } /** * @author Mat Groves http://matgroves.com/ @Doormat23 */ /** * A MovieClip is a simple way to display an animation depicted by a list of textures. * @class MovieClip * @extends Sprite * @constructor * @param textures {Array} an array of {Texture} objects that make up the animation */ PIXI.MovieClip = function(textures) { PIXI.Sprite.call( this, textures[0]); /** * The array of textures that make up the animation * @property textures * @type Array */ this.textures = textures; /** * [read only] The index MovieClips current frame (this may not have to be a whole number) * @property currentFrame * @type Number */ this.currentFrame = 0; /** * The speed that the MovieClip will play at. Higher is faster, lower is slower * @property animationSpeed * @type Number */ this.animationSpeed = 1; /** * [read only] indicates if the MovieClip is currently playing * @property playing * @type Boolean */ this.playing; } // constructor PIXI.MovieClip.constructor = PIXI.MovieClip; PIXI.MovieClip.prototype = Object.create( PIXI.Sprite.prototype ); /** * Stops the MovieClip * @method stop */ PIXI.MovieClip.prototype.stop = function() { this.playing = false; } /** * Plays the MovieClip * @method play */ PIXI.MovieClip.prototype.play = function() { this.playing = true; } /** * Stops the MovieClip and goes to a specific frame * @method gotoAndStop * @param frameNumber {Number} frame index to stop at */ PIXI.MovieClip.prototype.gotoAndStop = function(frameNumber) { this.playing = false; this.currentFrame = frameNumber; var round = (this.currentFrame + 0.5) | 0; this.setTexture(this.textures[round % this.textures.length]); } /** * Goes to a specific frame and begins playing the MovieClip * @method gotoAndPlay * @param frameNumber {Number} frame index to start at */ PIXI.MovieClip.prototype.gotoAndPlay = function(frameNumber) { this.currentFrame = frameNumber; this.playing = true; } PIXI.MovieClip.prototype.updateTransform = function() { PIXI.Sprite.prototype.updateTransform.call(this); if(!this.playing)return; this.currentFrame += this.animationSpeed; var round = (this.currentFrame + 0.5) | 0; this.setTexture(this.textures[round % this.textures.length]); } /** * @author Mat Groves http://matgroves.com/ @Doormat23 */ /** The interaction manager deals with mouse and touch events. At this moment only Sprite's can be interactive. This manager also supports multitouch. @class InteractionManager @constructor @param stage {Stage} @type Stage */ PIXI.InteractionManager = function(stage) { /** * a refference to the stage * @property stage * @type Stage */ this.stage = stage; // helpers this.tempPoint = new PIXI.Point(); //this.tempMatrix = mat3.create(); this.mouseoverEnabled = true; /** * the mouse data * @property mouse * @type InteractionData */ this.mouse = new PIXI.InteractionData(); /** * an object that stores current touches (InteractionData) by id reference * @property touchs * @type Object */ this.touchs = {}; //tiny little interactiveData pool! this.pool = []; this.interactiveItems = []; } // constructor PIXI.InteractionManager.constructor = PIXI.InteractionManager; /** * This method will disable rollover/rollout for ALL interactive items * You may wish to use this an optimization if your app does not require rollover/rollout funcitonality * @method disableMouseOver */ PIXI.InteractionManager.prototype.disableMouseOver = function() { if(!this.mouseoverEnabled)return; this.mouseoverEnabled = false; if(this.target)this.target.view.removeEventListener('mousemove', this.onMouseMove.bind(this)); } /** * This method will enable rollover/rollout for ALL interactive items * It is enabled by default * @method enableMouseOver */ PIXI.InteractionManager.prototype.enableMouseOver = function() { if(this.mouseoverEnabled)return; this.mouseoverEnabled = false; if(this.target)this.target.view.addEventListener('mousemove', this.onMouseMove.bind(this)); } PIXI.InteractionManager.prototype.collectInteractiveSprite = function(displayObject) { var children = displayObject.children; var length = children.length; for (var i = length - 1; i >= 0; i--) { var child = children[i]; // only sprite's right now... if(child instanceof PIXI.Sprite) { if(child.interactive)this.interactiveItems.push(child); } else { // use this to optimize.. if(!child.interactive)continue; } if(child.children.length > 0) { this.collectInteractiveSprite(child); } } } PIXI.InteractionManager.prototype.setTarget = function(target) { this.target = target; if(this.mouseoverEnabled)target.view.addEventListener('mousemove', this.onMouseMove.bind(this), true); target.view.addEventListener('mousedown', this.onMouseDown.bind(this), true); target.view.addEventListener('mouseup', this.onMouseUp.bind(this), true); target.view.addEventListener('mouseout', this.onMouseUp.bind(this), true); // aint no multi touch just yet! target.view.addEventListener("touchstart", this.onTouchStart.bind(this), true); target.view.addEventListener("touchend", this.onTouchEnd.bind(this), true); target.view.addEventListener("touchmove", this.onTouchMove.bind(this), true); } PIXI.InteractionManager.prototype.hitTest = function(interactionData) { if(this.dirty) { this.dirty = false; this.interactiveItems = []; // go through and collect all the objects that are interactive.. this.collectInteractiveSprite(this.stage); } var tempPoint = this.tempPoint; var tempMatrix = this.tempMatrix; var global = interactionData.global; var length = this.interactiveItems.length; for (var i = 0; i < length; i++) { var item = this.interactiveItems[i]; if(!item.visible)continue; // TODO this could do with some optimizing! // maybe store the inverse? // or do a lazy check first? //mat3.inverse(item.worldTransform, tempMatrix); //tempPoint.x = tempMatrix[0] * global.x + tempMatrix[1] * global.y + tempMatrix[2]; //tempPoint.y = tempMatrix[4] * global.y + tempMatrix[3] * global.x + tempMatrix[5]; // OPTIMIZED! assuming the matrix transform is affine.. which it totally shold be! var worldTransform = item.worldTransform; var a00 = worldTransform[0], a01 = worldTransform[1], a02 = worldTransform[2], a10 = worldTransform[3], a11 = worldTransform[4], a12 = worldTransform[5], id = 1 / (a00 * a11 + a01 * -a10); tempPoint.x = a11 * id * global.x + -a01 * id * global.y + (a12 * a01 - a02 * a11) * id; tempPoint.y = a00 * id * global.y + -a10 * id * global.x + (-a12 * a00 + a02 * a10) * id; var x1 = -item.width * item.anchor.x; if(tempPoint.x > x1 && tempPoint.x < x1 + item.width) { var y1 = -item.height * item.anchor.y; if(tempPoint.y > y1 && tempPoint.y < y1 + item.height) { interactionData.local.x = tempPoint.x; interactionData.local.y = tempPoint.y; return item; } } } return null; } PIXI.InteractionManager.prototype.onMouseMove = function(event) { event.preventDefault(); // TODO optimize by not check EVERY TIME! maybe half as often? // var rect = this.target.view.getBoundingClientRect(); this.mouse.global.x = (event.clientX - rect.left) * (this.target.width / rect.width); this.mouse.global.y = (event.clientY - rect.top) * ( this.target.height / rect.height); var item = this.hitTest(this.mouse); if(this.currentOver != item) { if(this.currentOver) { this.mouse.target = this.currentOver; if(this.currentOver.mouseout)this.currentOver.mouseout(this.mouse); this.currentOver = null; } this.target.view.style.cursor = "default"; } if(item) { if(this.currentOver == item)return; this.currentOver = item; this.target.view.style.cursor = "pointer"; this.mouse.target = item; if(item.mouseover)item.mouseover(this.mouse); } } PIXI.InteractionManager.prototype.onMouseDown = function(event) { var rect = this.target.view.getBoundingClientRect(); this.mouse.global.x = (event.clientX - rect.left) * (this.target.width / rect.width); this.mouse.global.y = (event.clientY - rect.top) * (this.target.height / rect.height); var item = this.hitTest(this.mouse); if(item) { this.currentDown = item; this.mouse.target = item; if(item.mousedown)item.mousedown(this.mouse); } } PIXI.InteractionManager.prototype.onMouseUp = function(event) { if(this.currentOver) { this.mouse.target = this.currentOver; if(this.currentOver.mouseup)this.currentOver.mouseup(this.mouse); } if(this.currentDown) { this.mouse.target = this.currentDown; // click! if(this.currentOver == this.currentDown)if(this.currentDown.click)this.currentDown.click(this.mouse); this.currentDown = null; } } PIXI.InteractionManager.prototype.onTouchMove = function(event) { event.preventDefault(); var rect = this.target.view.getBoundingClientRect(); var changedTouches = event.changedTouches; for (var i=0; i < changedTouches.length; i++) { var touchEvent = changedTouches[i]; var touchData = this.touchs[touchEvent.identifier]; // update the touch position touchData.global.x = (touchEvent.clientX - rect.left) * (this.target.width / rect.width); touchData.global.y = (touchEvent.clientY - rect.top) * (this.target.height / rect.height); } } PIXI.InteractionManager.prototype.onTouchStart = function(event) { event.preventDefault(); var rect = this.target.view.getBoundingClientRect(); var changedTouches = event.changedTouches; for (var i=0; i < changedTouches.length; i++) { var touchEvent = changedTouches[i]; var touchData = this.pool.pop(); if(!touchData)touchData = new PIXI.InteractionData(); this.touchs[touchEvent.identifier] = touchData; touchData.global.x = (touchEvent.clientX - rect.left) * (this.target.width / rect.width); touchData.global.y = (touchEvent.clientY - rect.top) * (this.target.height / rect.height); var item = this.hitTest(touchData); if(item) { touchData.currentDown = item; touchData.target = item; if(item.touchstart)item.touchstart(touchData); } } } PIXI.InteractionManager.prototype.onTouchEnd = function(event) { event.preventDefault(); var rect = this.target.view.getBoundingClientRect(); var changedTouches = event.changedTouches; for (var i=0; i < changedTouches.length; i++) { var touchEvent = changedTouches[i]; var touchData = this.touchs[touchEvent.identifier]; touchData.global.x = (touchEvent.clientX - rect.left) * (this.target.width / rect.width); touchData.global.y = (touchEvent.clientY - rect.top) * (this.target.height / rect.height); if(touchData.currentDown) { if(touchData.currentDown.touchend)touchData.currentDown.touchend(touchData); var item = this.hitTest(touchData); if(item == touchData.currentDown) { if(touchData.currentDown.tap)touchData.currentDown.tap(touchData); } touchData.currentDown = null; } // remove the touch.. this.pool.push(touchData); this.touchs[touchEvent.identifier] = null; } } /** @class InteractionData @constructor */ PIXI.InteractionData = function() { /** * This point stores the global coords of where the touch/mouse event happened * @property global * @type Point */ this.global = new PIXI.Point(); /** * This point stores the local coords of where the touch/mouse event happened * @property local * @type Point */ this.local = new PIXI.Point(); /** * The target Sprite that was interacted with * @property target * @type Sprite */ this.target; } // constructor PIXI.InteractionData.constructor = PIXI.InteractionData; /** * @author Mat Groves http://matgroves.com/ @Doormat23 */ /** A Stage represents the root of the display tree. Everything connected to the stage is rendered @class Stage @extends DisplayObjectContainer @constructor @param backgroundColor {Number} the background color of the stage @param interactive {Boolean} enable / disable interaction (default is false) */ PIXI.Stage = function(backgroundColor, interactive) { PIXI.DisplayObjectContainer.call( this ); this.worldTransform = PIXI.mat3.create()//.//identity(); this.__childrenAdded = []; this.__childrenRemoved = []; this.childIndex = 0; this.stage= this; // interaction! this.interactive = !!interactive; this.interactionManager = new PIXI.InteractionManager(this); this.setBackgroundColor(backgroundColor); } // constructor PIXI.Stage.constructor = PIXI.Stage; PIXI.Stage.prototype = Object.create( PIXI.DisplayObjectContainer.prototype ); /** @method updateTransform @internal */ PIXI.Stage.prototype.updateTransform = function() { this.worldAlpha = 1; for(var i=0,j=this.children.length; i<j; i++) { this.children[i].updateTransform(); } if(this.dirty) { this.dirty = false; // update interactive! this.interactionManager.dirty = true; } } /** * @method setBackgroundColor * @param backgroundColor {Number} */ PIXI.Stage.prototype.setBackgroundColor = function(backgroundColor) { this.backgroundColor = backgroundColor || 0x000000; this.backgroundColorSplit = HEXtoRGB(this.backgroundColor); this.backgroundColorString = "#" + this.backgroundColor.toString(16); } PIXI.Stage.prototype.__addChild = function(child) { if(child.interactive)this.dirty = true; child.stage = this; if(child.children) { for (var i=0; i < child.children.length; i++) { this.__addChild(child.children[i]); }; } } PIXI.Stage.prototype.__removeChild = function(child) { if(child.interactive)this.dirty = true; this.__childrenRemoved.push(child); child.stage = undefined; if(child.children) { for(var i=0,j=child.children.length; i<j; i++) { this.__removeChild(child.children[i]) } } } /** * Provides requestAnimationFrame in a cross browser way. */ window.requestAnimFrame = (function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(/* function FrameRequestCallback */ callback, /* DOMElement Element */ element) { window.setTimeout(callback, 1000/60); }; })(); function HEXtoRGB(hex) { return [(hex >> 16 & 0xFF) / 255, ( hex >> 8 & 0xFF) / 255, (hex & 0xFF)/ 255]; } /** * Provides bind in a cross browser way. */ if (typeof Function.prototype.bind != 'function') { Function.prototype.bind = (function () { var slice = Array.prototype.slice; return function (thisArg) { var target = this, boundArgs = slice.call(arguments, 1); if (typeof target != 'function') throw new TypeError(); function bound() { var args = boundArgs.concat(slice.call(arguments)); target.apply(this instanceof bound ? this : thisArg, args); } bound.prototype = (function F(proto) { proto && (F.prototype = proto); if (!(this instanceof F)) return new F; })(target.prototype); return bound; }; })(); } var AjaxRequest = function() { var activexmodes = ["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE if (window.ActiveXObject) { //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) for (var i=0; i<activexmodes.length; i++) { try{ return new ActiveXObject(activexmodes[i]) } catch(e){ //suppress error } } } else if (window.XMLHttpRequest) // if Mozilla, Safari etc { return new XMLHttpRequest() } else { return false; } } /** * https://github.com/mrdoob/eventtarget.js/ * THankS mr DOob! */ PIXI.EventTarget = function () { var listeners = {}; this.addEventListener = this.on = function ( type, listener ) { if ( listeners[ type ] === undefined ) { listeners[ type ] = []; } if ( listeners[ type ].indexOf( listener ) === - 1 ) { listeners[ type ].push( listener ); } }; this.dispatchEvent = this.emit = function ( event ) { for ( var listener in listeners[ event.type ] ) { listeners[ event.type ][ listener ]( event ); } }; this.removeEventListener = this.off = function ( type, listener ) { var index = listeners[ type ].indexOf( listener ); if ( index !== - 1 ) { listeners[ type ].splice( index, 1 ); } }; }; /* * A lighter version of the rad gl-matrix created by Brandon Jones, Colin MacKenzie IV * you both rock! */ function determineMatrixArrayType() { PIXI.Matrix = (typeof Float32Array !== 'undefined') ? Float32Array : Array; return PIXI.Matrix; } determineMatrixArrayType(); PIXI.mat3 = {}; PIXI.mat3.create = function() { var matrix = new PIXI.Matrix(9); matrix[0] = 1; matrix[1] = 0; matrix[2] = 0; matrix[3] = 0; matrix[4] = 1; matrix[5] = 0; matrix[6] = 0; matrix[7] = 0; matrix[8] = 1; return matrix; } PIXI.mat4 = {}; PIXI.mat4.create = function() { var matrix = new PIXI.Matrix(16); matrix[0] = 1; matrix[1] = 0; matrix[2] = 0; matrix[3] = 0; matrix[4] = 0; matrix[5] = 1; matrix[6] = 0; matrix[7] = 0; matrix[8] = 0; matrix[9] = 0; matrix[10] = 1; matrix[11] = 0; matrix[12] = 0; matrix[13] = 0; matrix[14] = 0; matrix[15] = 1; return matrix; } PIXI.mat3.multiply = function (mat, mat2, dest) { if (!dest) { dest = mat; } // Cache the matrix values (makes for huge speed increases!) var a00 = mat[0], a01 = mat[1], a02 = mat[2], a10 = mat[3], a11 = mat[4], a12 = mat[5], a20 = mat[6], a21 = mat[7], a22 = mat[8], b00 = mat2[0], b01 = mat2[1], b02 = mat2[2], b10 = mat2[3], b11 = mat2[4], b12 = mat2[5], b20 = mat2[6], b21 = mat2[7], b22 = mat2[8]; dest[0] = b00 * a00 + b01 * a10 + b02 * a20; dest[1] = b00 * a01 + b01 * a11 + b02 * a21; dest[2] = b00 * a02 + b01 * a12 + b02 * a22; dest[3] = b10 * a00 + b11 * a10 + b12 * a20; dest[4] = b10 * a01 + b11 * a11 + b12 * a21; dest[5] = b10 * a02 + b11 * a12 + b12 * a22; dest[6] = b20 * a00 + b21 * a10 + b22 * a20; dest[7] = b20 * a01 + b21 * a11 + b22 * a21; dest[8] = b20 * a02 + b21 * a12 + b22 * a22; return dest; } PIXI.mat3.toMat4 = function (mat, dest) { if (!dest) { dest = PIXI.mat4.create(); } dest[15] = 1; dest[14] = 0; dest[13] = 0; dest[12] = 0; dest[11] = 0; dest[10] = mat[8]; dest[9] = mat[7]; dest[8] = mat[6]; dest[7] = 0; dest[6] = mat[5]; dest[5] = mat[4]; dest[4] = mat[3]; dest[3] = 0; dest[2] = mat[2]; dest[1] = mat[1]; dest[0] = mat[0]; return dest; } ///// PIXI.mat4.create = function() { var matrix = new PIXI.Matrix(16); matrix[0] = 1; matrix[1] = 0; matrix[2] = 0; matrix[3] = 0; matrix[4] = 0; matrix[5] = 1; matrix[6] = 0; matrix[7] = 0; matrix[8] = 0; matrix[9] = 0; matrix[10] = 1; matrix[11] = 0; matrix[12] = 0; matrix[13] = 0; matrix[14] = 0; matrix[15] = 1; return matrix; } PIXI.mat4.transpose = function (mat, dest) { // If we are transposing ourselves we can skip a few steps but have to cache some values if (!dest || mat === dest) { var a01 = mat[1], a02 = mat[2], a03 = mat[3], a12 = mat[6], a13 = mat[7], a23 = mat[11]; mat[1] = mat[4]; mat[2] = mat[8]; mat[3] = mat[12]; mat[4] = a01; mat[6] = mat[9]; mat[7] = mat[13]; mat[8] = a02; mat[9] = a12; mat[11] = mat[14]; mat[12] = a03; mat[13] = a13; mat[14] = a23; return mat; } dest[0] = mat[0]; dest[1] = mat[4]; dest[2] = mat[8]; dest[3] = mat[12]; dest[4] = mat[1]; dest[5] = mat[5]; dest[6] = mat[9]; dest[7] = mat[13]; dest[8] = mat[2]; dest[9] = mat[6]; dest[10] = mat[10]; dest[11] = mat[14]; dest[12] = mat[3]; dest[13] = mat[7]; dest[14] = mat[11]; dest[15] = mat[15]; return dest; } PIXI.mat4.multiply = function (mat, mat2, dest) { if (!dest) { dest = mat; } // Cache the matrix values (makes for huge speed increases!) var a00 = mat[ 0], a01 = mat[ 1], a02 = mat[ 2], a03 = mat[3]; var a10 = mat[ 4], a11 = mat[ 5], a12 = mat[ 6], a13 = mat[7]; var a20 = mat[ 8], a21 = mat[ 9], a22 = mat[10], a23 = mat[11]; var a30 = mat[12], a31 = mat[13], a32 = mat[14], a33 = mat[15]; // Cache only the current line of the second matrix var b0 = mat2[0], b1 = mat2[1], b2 = mat2[2], b3 = mat2[3]; dest[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30; dest[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31; dest[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32; dest[3] = b0*a03 + b1*a13 + b2*a23 + b3*a33; b0 = mat2[4]; b1 = mat2[5]; b2 = mat2[6]; b3 = mat2[7]; dest[4] = b0*a00 + b1*a10 + b2*a20 + b3*a30; dest[5] = b0*a01 + b1*a11 + b2*a21 + b3*a31; dest[6] = b0*a02 + b1*a12 + b2*a22 + b3*a32; dest[7] = b0*a03 + b1*a13 + b2*a23 + b3*a33; b0 = mat2[8]; b1 = mat2[9]; b2 = mat2[10]; b3 = mat2[11]; dest[8] = b0*a00 + b1*a10 + b2*a20 + b3*a30; dest[9] = b0*a01 + b1*a11 + b2*a21 + b3*a31; dest[10] = b0*a02 + b1*a12 + b2*a22 + b3*a32; dest[11] = b0*a03 + b1*a13 + b2*a23 + b3*a33; b0 = mat2[12]; b1 = mat2[13]; b2 = mat2[14]; b3 = mat2[15]; dest[12] = b0*a00 + b1*a10 + b2*a20 + b3*a30; dest[13] = b0*a01 + b1*a11 + b2*a21 + b3*a31; dest[14] = b0*a02 + b1*a12 + b2*a22 + b3*a32; dest[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33; return dest; } /** * @author Mat Groves http://matgroves.com/ @Doormat23 */ /** * This helper function will automatically detect which renderer you should be using. * WebGL is the preferred renderer as it is a lot fastest. If webGL is not supported by the browser then this function will return a canvas renderer * @method autoDetectRenderer * @static * @param width {Number} the width of the renderers view * @param height {Number} the height of the renderers view * @param view {Canvas} the canvas to use as a view, optional * @param transparent {Boolean} the transparency of the render view, default false * @default false */ PIXI.autoDetectRenderer = function(width, height, view, transparent) { if(!width)width = 800; if(!height)height = 600; // BORROWED from Mr Doob (mrdoob.com) var webgl = ( function () { try { return !! window.WebGLRenderingContext && !! document.createElement( 'canvas' ).getContext( 'experimental-webgl' ); } catch( e ) { return false; } } )(); //console.log(webgl); if( webgl ) { return new PIXI.WebGLRenderer(width, height, view, transparent); } return new PIXI.CanvasRenderer(width, height, view, transparent); }; /** * @author Mat Groves http://matgroves.com/ @Doormat23 */ PIXI.shaderFragmentSrc = [ "precision mediump float;", "varying vec2 vTextureCoord;", "varying float vColor;", "uniform sampler2D uSampler;", "void main(void) {", "gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y));", "gl_FragColor = gl_FragColor * vColor;", "}"]; PIXI.shaderVertexSrc = [ "attribute vec2 aVertexPosition;", "attribute vec2 aTextureCoord;", "attribute float aColor;", "uniform mat4 uMVMatrix;", "varying vec2 vTextureCoord;", "varying float vColor;", "void main(void) {", "gl_Position = uMVMatrix * vec4(aVertexPosition, 1.0, 1.0);", "vTextureCoord = aTextureCoord;", "vColor = aColor;", "}"] PIXI.CompileVertexShader = function(gl, shaderSrc) { var src = ""; for (var i=0; i < shaderSrc.length; i++) { src += shaderSrc[i]; }; var shader; shader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { alert(gl.getShaderInfoLog(shader)); return null; } return shader; } PIXI.CompileFragmentShader = function(gl, shaderSrc) { var src = ""; for (var i=0; i < shaderSrc.length; i++) { src += shaderSrc[i]; }; var shader; shader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { alert(gl.getShaderInfoLog(shader)); return null; } return shader; } /** * @author Mat Groves http://matgroves.com/ @Doormat23 */ PIXI._defaultFrame = new PIXI.Rectangle(0,0,1,1); /** * the WebGLRenderer is draws the stage and all its content onto a webGL enabled canvas. This renderer should be used for browsers support webGL. This Render works by automatically managing webGLBatchs. So no need for Sprite Batch's or Sprite Cloud's * Dont forget to add the view to your DOM or you will not see anything :) * @class WebGLRenderer * @constructor * @param width {Number} the width of the canvas view * @default 0 * @param height {Number} the height of the canvas view * @default 0 * @param view {Canvas} the canvas to use as a view, optional * @param transparent {Boolean} the transparency of the render view, default false * @default false * */ PIXI.WebGLRenderer = function(width, height, view, transparent) { //console.log(transparent) this.transparent = !!transparent; this.width = width || 800; this.height = height || 600; this.view = view || document.createElement( 'canvas' ); this.view.width = this.width; this.view.height = this.height; // deal with losing context.. var scope = this; this.view.addEventListener('webglcontextlost', function(event) { scope.handleContextLost(event); }, false) this.view.addEventListener('webglcontextrestored', function(event) { scope.handleContextRestored(event); }, false) this.batchs = []; try { this.gl = this.view.getContext("experimental-webgl", { alpha: this.transparent, antialias:false, // SPEED UP?? premultipliedAlpha:true }); } catch (e) { throw new Error(" This browser does not support webGL. Try using the canvas renderer" + this); } this.initShaders(); var gl = this.gl; this.batch = new PIXI.WebGLBatch(gl); gl.disable(gl.DEPTH_TEST); gl.enable(gl.BLEND); gl.colorMask(true, true, true, this.transparent); this.projectionMatrix = PIXI.mat4.create(); this.resize(this.width, this.height) this.contextLost = false; } // constructor PIXI.WebGLRenderer.constructor = PIXI.WebGLRenderer; /** * @private */ PIXI.WebGLRenderer.prototype.initShaders = function() { var gl = this.gl; var fragmentShader = PIXI.CompileFragmentShader(gl, PIXI.shaderFragmentSrc); var vertexShader = PIXI.CompileVertexShader(gl, PIXI.shaderVertexSrc); this.shaderProgram = gl.createProgram(); var shaderProgram = this.shaderProgram; gl.attachShader(shaderProgram, vertexShader); gl.attachShader(shaderProgram, fragmentShader); gl.linkProgram(shaderProgram); if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { alert("Could not initialise shaders"); } gl.useProgram(shaderProgram); shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition"); gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute); shaderProgram.textureCoordAttribute = gl.getAttribLocation(shaderProgram, "aTextureCoord"); gl.enableVertexAttribArray(shaderProgram.textureCoordAttribute); shaderProgram.colorAttribute = gl.getAttribLocation(shaderProgram, "aColor"); gl.enableVertexAttribArray(shaderProgram.colorAttribute); shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix"); shaderProgram.samplerUniform = gl.getUniformLocation(shaderProgram, "uSampler"); PIXI.shaderProgram = this.shaderProgram; } /** * @private */ PIXI.WebGLRenderer.prototype.checkVisibility = function(displayObject, globalVisible) { var children = displayObject.children; for (var i=0; i < children.length; i++) { var child = children[i]; // TODO optimize... shouldt need to loop through everything all the time var actualVisibility = child.visible && globalVisible; // everything should have a batch! // time to see whats new! if(child.textureChange) { child.textureChange = false; if(actualVisibility) { this.removeDisplayObject(child) this.addDisplayObject(child) } // update texture!! } if(child.cacheVisible != actualVisibility) { child.cacheVisible = actualVisibility; if(child.cacheVisible) { this.addDisplayObject(child); } else { this.removeDisplayObject(child); } } if(child.children.length > 0) { this.checkVisibility(child, actualVisibility); } }; } /** * Renders the stage to its webGL view * @method render * @param stage {Stage} the PIXI.Stage element to be rendered */ PIXI.WebGLRenderer.prototype.render = function(stage) { if(this.contextLost)return; // update children if need be // best to remove first! for (var i=0; i < stage.__childrenRemoved.length; i++) { this.removeDisplayObject(stage.__childrenRemoved[i]); } // update any textures for (var i=0; i < PIXI.texturesToUpdate.length; i++) this.updateTexture(PIXI.texturesToUpdate[i]); // empty out the arrays stage.__childrenRemoved = []; stage.__childrenAdded = []; PIXI.texturesToUpdate = []; // recursivly loop through all items! this.checkVisibility(stage, true); // update the scene graph stage.updateTransform(); var gl = this.gl; gl.clear(gl.COLOR_BUFFER_BIT) gl.clearColor(stage.backgroundColorSplit[0], stage.backgroundColorSplit[1], stage.backgroundColorSplit[2], 0); // set the correct blend mode! gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.uniformMatrix4fv(this.shaderProgram.mvMatrixUniform, false, this.projectionMatrix); // render all the batchs! var renderable; for (var i=0; i < this.batchs.length; i++) { renderable = this.batchs[i]; if(renderable instanceof PIXI.WebGLBatch) { this.batchs[i].render(); } else if(renderable instanceof PIXI.Strip) { if(renderable.visible)this.renderStrip(renderable); } } // interaction // run interaction! if(stage.interactive) { //need to add some events! if(!stage._interactiveEventsAdded) { stage._interactiveEventsAdded = true; stage.interactionManager.setTarget(this); } } } /** * @private */ PIXI.WebGLRenderer.prototype.updateTexture = function(texture) { var gl = this.gl; if(!texture._glTexture) { texture._glTexture = gl.createTexture(); } if(texture.hasLoaded) { gl.bindTexture(gl.TEXTURE_2D, texture._glTexture); gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.source); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); // gl.generateMipmap(gl.TEXTURE_2D); gl.bindTexture(gl.TEXTURE_2D, null); } this.refreshBatchs = true; } /** * @private */ PIXI.WebGLRenderer.prototype.addDisplayObject = function(displayObject) { if(!displayObject.stage)return; // means it was removed if(displayObject.__inWebGL)return; //means it is already in webgL //displayObject.cacheVisible = displayObject.visible; // TODO if objects parent is not visible then dont add to stage!!!! //if(!displayObject.visible)return; displayObject.batch = null; //displayObject.cacheVisible = true; if(!displayObject.renderable)return; // while looping below THE OBJECT MAY NOT HAVE BEEN ADDED displayObject.__inWebGL = true; /* * LOOK FOR THE PREVIOUS SPRITE * This part looks for the closest previous sprite that can go into a batch * It keeps going back until it finds a sprite or the stage */ var previousSprite = displayObject; do { if(previousSprite.childIndex == 0) { previousSprite = previousSprite.parent; } else { previousSprite = previousSprite.parent.children[previousSprite.childIndex-1]; // what if the bloop has children??? while(previousSprite.children.length != 0) { // keep diggin till we get to the last child previousSprite = previousSprite.children[previousSprite.children.length-1]; } } if(previousSprite == displayObject.stage)break; } while(!previousSprite.renderable || !previousSprite.__inWebGL) //while(!(previousSprite instanceof PIXI.Sprite)) /* * LOOK FOR THE NEXT SPRITE * This part looks for the closest next sprite that can go into a batch * it keeps looking until it finds a sprite or gets to the end of the display * scene graph * * These look a lot scarier than the actually are... */ var nextSprite = displayObject; do { // moving forward! // if it has no children.. if(nextSprite.children.length == 0) { // go along to the parent.. while(nextSprite.childIndex == nextSprite.parent.children.length-1) { nextSprite = nextSprite.parent; if(nextSprite == displayObject.stage) { nextSprite = null break; } } if(nextSprite)nextSprite = nextSprite.parent.children[nextSprite.childIndex+1]; } else { nextSprite = nextSprite.children[0]; } if(!nextSprite)break; } while(!nextSprite.renderable || !nextSprite.__inWebGL) /* * so now we have the next renderable and the previous renderable * */ if(displayObject instanceof PIXI.Sprite) { var previousBatch var nextBatch if(previousSprite instanceof PIXI.Sprite) { previousBatch = previousSprite.batch; if(previousBatch) { if(previousBatch.texture == displayObject.texture.baseTexture && previousBatch.blendMode == displayObject.blendMode) { previousBatch.insertAfter(displayObject, previousSprite); return; } } } else { // TODO reword! previousBatch = previousSprite; } if(nextSprite) { if(nextSprite instanceof PIXI.Sprite) { nextBatch = nextSprite.batch; //batch may not exist if item was added to the display list but not to the webGL if(nextBatch) { if(nextBatch.texture == displayObject.texture.baseTexture && nextBatch.blendMode == displayObject.blendMode) { nextBatch.insertBefore(displayObject, nextSprite); return; } else { if(nextBatch == previousBatch) { // THERE IS A SPLIT IN THIS BATCH! // var splitBatch = previousBatch.split(nextSprite); // COOL! // add it back into the array /* * OOPS! * seems the new sprite is in the middle of a batch * lets split it.. */ var batch = PIXI._getBatch(this.gl); var index = this.batchs.indexOf( previousBatch ); batch.init(displayObject); this.batchs.splice(index+1, 0, batch, splitBatch); return; } } } } else { // TODO re-word! nextBatch = nextSprite; } } /* * looks like it does not belong to any batch! * but is also not intersecting one.. * time to create anew one! */ var batch = PIXI._getBatch(this.gl); batch.init(displayObject); if(previousBatch) // if this is invalid it means { var index = this.batchs.indexOf( previousBatch ); this.batchs.splice(index+1, 0, batch); } else { this.batchs.push(batch); } } else if(displayObject instanceof PIXI.Strip) { // add to a batch!! this.initStrip(displayObject); this.batchs.push(displayObject); } // if its somthing else... then custom codes! this.batchUpdate = true; } /** * @private */ PIXI.WebGLRenderer.prototype.removeDisplayObject = function(displayObject) { //if(displayObject.stage)return; displayObject.cacheVisible = false;//displayObject.visible; if(!displayObject.renderable)return; displayObject.__inWebGL = false; /* * removing is a lot quicker.. * */ var batchToRemove; if(displayObject instanceof PIXI.Sprite) { // should always have a batch! var batch = displayObject.batch; if(!batch)return; // this means the display list has been altered befre rendering batch.remove(displayObject); if(batch.size==0) { batchToRemove = batch } } else { batchToRemove = displayObject; } /* * Looks like there is somthing that needs removing! */ if(batchToRemove) { var index = this.batchs.indexOf( batchToRemove ); if(index == -1)return;// this means it was added then removed before rendered // ok so.. check to see if you adjacent batchs should be joined. // TODO may optimise? if(index == 0 || index == this.batchs.length-1) { // wha - eva! just get of the empty batch! this.batchs.splice(index, 1); if(batchToRemove instanceof PIXI.WebGLBatch)PIXI._returnBatch(batchToRemove); return; } if(this.batchs[index-1] instanceof PIXI.WebGLBatch && this.batchs[index+1] instanceof PIXI.WebGLBatch) { if(this.batchs[index-1].texture == this.batchs[index+1].texture && this.batchs[index-1].blendMode == this.batchs[index+1].blendMode) { //console.log("MERGE") this.batchs[index-1].merge(this.batchs[index+1]); if(batchToRemove instanceof PIXI.WebGLBatch)PIXI._returnBatch(batchToRemove); PIXI._returnBatch(this.batchs[index+1]); this.batchs.splice(index, 2); return; } } this.batchs.splice(index, 1); if(batchToRemove instanceof PIXI.WebGLBatch)PIXI._returnBatch(batchToRemove); } } /** * resizes the webGL view to the specified width and height * @method resize * @param width {Number} the new width of the webGL view * @param height {Number} the new height of the webGL view */ PIXI.WebGLRenderer.prototype.resize = function(width, height) { this.width = width; this.height = height; this.view.width = width; this.view.height = height; this.gl.viewport(0, 0, this.width, this.height); var projectionMatrix = this.projectionMatrix; projectionMatrix[0] = 2/this.width; projectionMatrix[5] = -2/this.height; projectionMatrix[12] = -1; projectionMatrix[13] = 1; } /** * @private */ PIXI.WebGLRenderer.prototype.initStrip = function(strip) { // build the strip! var gl = this.gl; var shaderProgram = this.shaderProgram; strip._vertexBuffer = gl.createBuffer(); strip._indexBuffer = gl.createBuffer(); strip._uvBuffer = gl.createBuffer(); strip._colorBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, strip._vertexBuffer); gl.bufferData(gl.ARRAY_BUFFER, strip.verticies, gl.DYNAMIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, strip._uvBuffer); gl.bufferData(gl.ARRAY_BUFFER, strip.uvs, gl.STATIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, strip._colorBuffer); gl.bufferData(gl.ARRAY_BUFFER, strip.colors, gl.STATIC_DRAW); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, strip._indexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, strip.indices, gl.STATIC_DRAW); } /** * @private */ PIXI.WebGLRenderer.prototype.renderStrip = function(strip) { var gl = this.gl; var shaderProgram = this.shaderProgram; // mat var mat4Real = PIXI.mat3.toMat4(strip.worldTransform); PIXI.mat4.transpose(mat4Real); PIXI.mat4.multiply(this.projectionMatrix, mat4Real, mat4Real ) gl.uniformMatrix4fv(this.shaderProgram.mvMatrixUniform, false, mat4Real); if(strip.blendMode == PIXI.blendModes.NORMAL) { gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); } else { gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_COLOR); } if(!strip.dirty) { gl.bindBuffer(gl.ARRAY_BUFFER, strip._vertexBuffer); gl.bufferSubData(gl.ARRAY_BUFFER, 0, strip.verticies) gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, 2, gl.FLOAT, false, 0, 0); // update the uvs gl.bindBuffer(gl.ARRAY_BUFFER, strip._uvBuffer); gl.vertexAttribPointer(shaderProgram.textureCoordAttribute, 2, gl.FLOAT, false, 0, 0); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, strip.texture.baseTexture._glTexture); gl.bindBuffer(gl.ARRAY_BUFFER, strip._colorBuffer); gl.vertexAttribPointer(shaderProgram.colorAttribute, 1, gl.FLOAT, false, 0, 0); // dont need to upload! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, strip._indexBuffer); } else { strip.dirty = false; gl.bindBuffer(gl.ARRAY_BUFFER, strip._vertexBuffer); gl.bufferData(gl.ARRAY_BUFFER, strip.verticies, gl.STATIC_DRAW) gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, 2, gl.FLOAT, false, 0, 0); // update the uvs gl.bindBuffer(gl.ARRAY_BUFFER, strip._uvBuffer); gl.bufferData(gl.ARRAY_BUFFER, strip.uvs, gl.STATIC_DRAW) gl.vertexAttribPointer(shaderProgram.textureCoordAttribute, 2, gl.FLOAT, false, 0, 0); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, strip.texture.baseTexture._glTexture); gl.bindBuffer(gl.ARRAY_BUFFER, strip._colorBuffer); gl.bufferData(gl.ARRAY_BUFFER, strip.colors, gl.STATIC_DRAW) gl.vertexAttribPointer(shaderProgram.colorAttribute, 1, gl.FLOAT, false, 0, 0); // dont need to upload! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, strip._indexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, strip.indices, gl.STATIC_DRAW); } gl.drawElements(gl.TRIANGLE_STRIP, strip.indices.length, gl.UNSIGNED_SHORT, 0); gl.uniformMatrix4fv(this.shaderProgram.mvMatrixUniform, false, this.projectionMatrix); // console.log("!!!") } /** * @private */ PIXI.WebGLRenderer.prototype.handleContextLost = function(event) { event.preventDefault(); this.contextLost = true; } /** * @private */ PIXI.WebGLRenderer.prototype.handleContextRestored = function(event) { this.gl = this.view.getContext("experimental-webgl", { alpha: true }); this.initShaders(); for (var i=0; i < PIXI.TextureCache.length; i++) { this.updateTexture(PIXI.TextureCache[i]); }; for (var i=0; i < this.batchs.length; i++) { this.batchs[i].restoreLostContext(this.gl)// this.batchs[i].dirty = true; }; PIXI._restoreBatchs(this.gl); this.contextLost = false; } /** * @author Mat Groves http://matgroves.com/ @Doormat23 */ PIXI._batchs = []; /** * @private */ PIXI._getBatch = function(gl) { if(PIXI._batchs.length == 0) { return new PIXI.WebGLBatch(gl); } else { return PIXI._batchs.pop(); } } /** * @private */ PIXI._returnBatch = function(batch) { batch.clean(); PIXI._batchs.push(batch); } /** * @private */ PIXI._restoreBatchs = function(gl) { for (var i=0; i < PIXI._batchs.length; i++) { PIXI._batchs[i].restoreLostContext(gl); }; } /** * A WebGLBatch Enables a group of sprites to be drawn using the same settings. * if a group of sprites all have the same baseTexture and blendMode then they can be grouped into a batch. All the sprites in a batch can then be drawn in one go by the GPU which is hugely efficient. ALL sprites in the webGL renderer are added to a batch even if the batch only contains one sprite. Batching is handled automatically by the webGL renderer. A good tip is: the smaller the number of batchs there are, the faster the webGL renderer will run. * @class WebGLBatch * @param an instance of the webGL context * @return {PIXI.renderers.WebGLBatch} WebGLBatch {@link PIXI.renderers.WebGLBatch} */ PIXI.WebGLBatch = function(gl) { this.gl = gl; this.size = 0; this.vertexBuffer = gl.createBuffer(); this.indexBuffer = gl.createBuffer(); this.uvBuffer = gl.createBuffer(); this.colorBuffer = gl.createBuffer(); this.blendMode = PIXI.blendModes.NORMAL; this.dynamicSize = 1; } // constructor PIXI.WebGLBatch.constructor = PIXI.WebGLBatch; /** * Cleans the batch so that is can be returned to an object pool and reused */ PIXI.WebGLBatch.prototype.clean = function() { this.verticies = []; this.uvs = []; this.indices = []; this.colors = []; //this.sprites = []; this.dynamicSize = 1; this.texture = null; this.last = null; this.size = 0; this.head; this.tail; } /* * recreates the buffers in the event of a context loss */ PIXI.WebGLBatch.prototype.restoreLostContext = function(gl) { this.gl = gl; this.vertexBuffer = gl.createBuffer(); this.indexBuffer = gl.createBuffer(); this.uvBuffer = gl.createBuffer(); this.colorBuffer = gl.createBuffer(); } /** * inits the batch's texture and blend mode based if the supplied sprite * @method init * @param sprite {Sprite} the first sprite to be added to the batch. Only sprites with the same base texture and blend mode will be allowed to be added to this batch */ PIXI.WebGLBatch.prototype.init = function(sprite) { sprite.batch = this; this.dirty = true; this.blendMode = sprite.blendMode; this.texture = sprite.texture.baseTexture; // this.sprites.push(sprite); this.head = sprite; this.tail = sprite; this.size = 1; this.growBatch(); } /** * inserts a sprite before the specified sprite * @method insertBefore * @param sprite {Sprite} the sprite to be added * @param nextSprite {nextSprite} the first sprite will be inserted before this sprite */ PIXI.WebGLBatch.prototype.insertBefore = function(sprite, nextSprite) { this.size++; sprite.batch = this; this.dirty = true; var tempPrev = nextSprite.__prev; nextSprite.__prev = sprite; sprite.__next = nextSprite; if(tempPrev) { sprite.__prev = tempPrev; tempPrev.__next = sprite; } else { this.head = sprite; //this.head.__prev = null } } /** * inserts a sprite after the specified sprite * @method insertAfter * @param sprite {Sprite} the sprite to be added * @param previousSprite {Sprite} the first sprite will be inserted after this sprite */ PIXI.WebGLBatch.prototype.insertAfter = function(sprite, previousSprite) { this.size++; sprite.batch = this; this.dirty = true; var tempNext = previousSprite.__next; previousSprite.__next = sprite; sprite.__prev = previousSprite; if(tempNext) { sprite.__next = tempNext; tempNext.__prev = sprite; } else { this.tail = sprite } } /** * removes a sprite from the batch * @method remove * @param sprite {Sprite} the sprite to be removed */ PIXI.WebGLBatch.prototype.remove = function(sprite) { this.size--; if(this.size == 0) { sprite.batch = null; sprite.__prev = null; sprite.__next = null; return; } if(sprite.__prev) { sprite.__prev.__next = sprite.__next; } else { this.head = sprite.__next; this.head.__prev = null; } if(sprite.__next) { sprite.__next.__prev = sprite.__prev; } else { this.tail = sprite.__prev; this.tail.__next = null } sprite.batch = null; sprite.__next = null; sprite.__prev = null; this.dirty = true; } /** * Splits the batch into two with the specified sprite being the start of the new batch. * @method split * @param sprite {Sprite} the sprite that indicates where the batch should be split * @return {WebGLBatch} the new batch */ PIXI.WebGLBatch.prototype.split = function(sprite) { //console.log("Splitting batch :" + this.size) // console.log(sprite) // console.log("-------") this.dirty = true; //var val = (this.tail == this.head) //console.log(val + " SAME?"); var batch = new PIXI.WebGLBatch(this.gl)//PIXI._getBatch(this.gl); batch.init(sprite); batch.tail = this.tail; //console.log("id is " +batcheee.id) this.tail = sprite.__prev; this.tail.__next = null; sprite.__prev = null; // return a splite batch! //sprite.__prev.__next = null; //sprite.__prev = null; // TODO this size is wrong! // need to recalculate :/ problem with a linked list! // unless it gets calculated in the "clean"? // need to loop through items as there is no way to know the length on a linked list :/ var tempSize = 0; while(sprite) { tempSize++; sprite.batch = batch; sprite = sprite.__next; } batch.size = tempSize; this.size -= tempSize; return batch; } /** * Merges two batchs together * @method merge * @param batch {WebGLBatch} the batch that will be merged */ PIXI.WebGLBatch.prototype.merge = function(batch) { this.dirty = true; this.tail.__next = batch.head; batch.head.__prev = this.tail; this.size += batch.size; this.tail = batch.tail; var sprite = batch.head; while(sprite) { sprite.batch = this; sprite = sprite.__next; } } /** * Grows the size of the batch. As the elements in the batch cannot have a dynamic size this function is used to increase the size of the batch. It also creates a little extra room so that the batch does not need to be resized every time a sprite is added * @methos growBatch */ PIXI.WebGLBatch.prototype.growBatch = function() { var gl = this.gl; if( this.size == 1) { this.dynamicSize = 1; } else { this.dynamicSize = this.size * 1.5 } // grow verts this.verticies = new Float32Array(this.dynamicSize * 8); gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); gl.bufferData(gl.ARRAY_BUFFER,this.verticies , gl.DYNAMIC_DRAW); this.uvs = new Float32Array( this.dynamicSize * 8 ) gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); gl.bufferData(gl.ARRAY_BUFFER, this.uvs , gl.DYNAMIC_DRAW); this.dirtyUVS = true; this.colors = new Float32Array( this.dynamicSize * 4 ) gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); gl.bufferData(gl.ARRAY_BUFFER, this.colors , gl.DYNAMIC_DRAW); this.dirtyColors = true; this.indices = new Uint16Array(this.dynamicSize * 6); var length = this.indices.length/6; for (var i=0; i < length; i++) { var index2 = i * 6; var index3 = i * 4; this.indices[index2 + 0] = index3 + 0; this.indices[index2 + 1] = index3 + 1; this.indices[index2 + 2] = index3 + 2; this.indices[index2 + 3] = index3 + 0; this.indices[index2 + 4] = index3 + 2; this.indices[index2 + 5] = index3 + 3; }; gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); } /** * Refresh's all the data in the batch and sync's it with the webGL buffers * @method refresh */ PIXI.WebGLBatch.prototype.refresh = function() { var gl = this.gl; if (this.dynamicSize < this.size) { this.growBatch(); } var indexRun = 0; var worldTransform, width, height, aX, aY, w0, w1, h0, h1, index var a, b, c, d, tx, ty var displayObject = this.head while(displayObject) { index = indexRun * 8; var texture = displayObject.texture; var frame = texture.frame; var tw = texture.baseTexture.width; var th = texture.baseTexture.height; this.uvs[index + 0] = frame.x / tw; this.uvs[index +1] = frame.y / th; this.uvs[index +2] = (frame.x + frame.width) / tw; this.uvs[index +3] = frame.y / th; this.uvs[index +4] = (frame.x + frame.width) / tw; this.uvs[index +5] = (frame.y + frame.height) / th; this.uvs[index +6] = frame.x / tw; this.uvs[index +7] = (frame.y + frame.height) / th; displayObject.updateFrame = false; colorIndex = indexRun * 4; this.colors[colorIndex] = this.colors[colorIndex + 1] = this.colors[colorIndex + 2] = this.colors[colorIndex + 3] = displayObject.worldAlpha; displayObject = displayObject.__next; indexRun ++; } this.dirtyUVS = true; this.dirtyColors = true; } /** * Updates all the relevant geometry and uploads the data to the GPU * @method update */ PIXI.WebGLBatch.prototype.update = function() { var gl = this.gl; var worldTransform, width, height, aX, aY, w0, w1, h0, h1, index, index2, index3 var a, b, c, d, tx, ty; var indexRun = 0; var displayObject = this.head; while(displayObject) { width = displayObject.width; height = displayObject.height; aX = displayObject.anchor.x - displayObject.texture.trim.x aY = displayObject.anchor.y - displayObject.texture.trim.y w0 = width * (1-aX); w1 = width * -aX; h0 = height * (1-aY); h1 = height * -aY; index = indexRun * 8; worldTransform = displayObject.worldTransform; a = worldTransform[0]; b = worldTransform[3]; c = worldTransform[1]; d = worldTransform[4]; tx = worldTransform[2]; ty = worldTransform[5]; this.verticies[index + 0 ] = a * w1 + c * h1 + tx; this.verticies[index + 1 ] = d * h1 + b * w1 + ty; this.verticies[index + 2 ] = a * w0 + c * h1 + tx; this.verticies[index + 3 ] = d * h1 + b * w0 + ty; this.verticies[index + 4 ] = a * w0 + c * h0 + tx; this.verticies[index + 5 ] = d * h0 + b * w0 + ty; this.verticies[index + 6] = a * w1 + c * h0 + tx; this.verticies[index + 7] = d * h0 + b * w1 + ty; if(displayObject.updateFrame) { this.dirtyUVS = true; var texture = displayObject.texture; var frame = texture.frame; var tw = texture.baseTexture.width; var th = texture.baseTexture.height; this.uvs[index + 0] = frame.x / tw; this.uvs[index +1] = frame.y / th; this.uvs[index +2] = (frame.x + frame.width) / tw; this.uvs[index +3] = frame.y / th; this.uvs[index +4] = (frame.x + frame.width) / tw; this.uvs[index +5] = (frame.y + frame.height) / th; this.uvs[index +6] = frame.x / tw; this.uvs[index +7] = (frame.y + frame.height) / th; displayObject.updateFrame = false; } // TODO this probably could do with some optimisation.... if(displayObject.cacheAlpha != displayObject.worldAlpha) { displayObject.cacheAlpha = displayObject.worldAlpha; var colorIndex = indexRun * 4; this.colors[colorIndex] = this.colors[colorIndex + 1] = this.colors[colorIndex + 2] = this.colors[colorIndex + 3] = displayObject.worldAlpha; this.dirtyColors = true; } indexRun++; displayObject = displayObject.__next; } } /** * Draws the batch to the frame buffer * @method render */ PIXI.WebGLBatch.prototype.render = function() { if(this.dirty) { this.refresh(); this.dirty = false; } if (this.size == 0)return; this.update(); var gl = this.gl; //TODO optimize this! if(this.blendMode == PIXI.blendModes.NORMAL) { gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); } else { gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_COLOR); } var shaderProgram = PIXI.shaderProgram; // update the verts.. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); // ok.. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.verticies) gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, 2, gl.FLOAT, false, 0, 0); // update the uvs gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); if(this.dirtyUVS) { this.dirtyUVS = false; gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.uvs); } gl.vertexAttribPointer(shaderProgram.textureCoordAttribute, 2, gl.FLOAT, false, 0, 0); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, this.texture._glTexture); // update color! gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); if(this.dirtyColors) { this.dirtyColors = false; gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.colors); } gl.vertexAttribPointer(shaderProgram.colorAttribute, 1, gl.FLOAT, false, 0, 0); // dont need to upload! gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); // DRAW THAT this! gl.drawElements(gl.TRIANGLES, this.size * 6, gl.UNSIGNED_SHORT, 0); } /** * @author Mat Groves http://matgroves.com/ @Doormat23 */ /** * the CanvasRenderer draws the stage and all its content onto a 2d canvas. This renderer should be used for browsers that do not support webGL. * Dont forget to add the view to your DOM or you will not see anything :) * @class CanvasRenderer * @constructor * @param width {Number} the width of the canvas view * @default 0 * @param height {Number} the height of the canvas view * @default 0 * @param view {Canvas} the canvas to use as a view, optional * @param transparent {Boolean} the transparency of the render view, default false * @default false * */ PIXI.CanvasRenderer = function(width, height, view, transparent) { this.transparent = transparent; /** * The width of the canvas view * @property width * @type Number * @default 800 */ this.width = width || 800; /** * The height of the canvas view * @property height * @type Number * @default 600 */ this.height = height || 600; this.refresh = true; /** * The canvas element that the everything is drawn to * @property view * @type Canvas */ this.view = view || document.createElement( 'canvas' ); // hack to enable some hardware acceleration! //this.view.style["transform"] = "translatez(0)"; this.view.width = this.width; this.view.height = this.height; this.count = 0; /** * The canvas context that the everything is drawn to * @property context * @type Canvas 2d Context */ this.context = this.view.getContext("2d"); } // constructor PIXI.CanvasRenderer.constructor = PIXI.CanvasRenderer; /** * Renders the stage to its canvas view * @method render * @param stage {Stage} the Stage element to be rendered */ PIXI.CanvasRenderer.prototype.render = function(stage) { // update children if need be stage.__childrenAdded = []; stage.__childrenRemoved = []; // update textures if need be PIXI.texturesToUpdate = []; this.context.setTransform(1,0,0,1,0,0); stage.updateTransform(); this.context.setTransform(1,0,0,1,0,0); // update the background color if(this.view.style.backgroundColor!=stage.backgroundColorString && !this.transparent)this.view.style.backgroundColor = stage.backgroundColorString; this.context.clearRect(0, 0, this.width, this.height) this.renderDisplayObject(stage); //as // run interaction! if(stage.interactive) { //need to add some events! if(!stage._interactiveEventsAdded) { stage._interactiveEventsAdded = true; stage.interactionManager.setTarget(this); } } } /** * resizes the canvas view to the specified width and height * @param the new width of the canvas view * @param the new height of the canvas view */ PIXI.CanvasRenderer.prototype.resize = function(width, height) { this.width = width; this.height = height; this.view.width = width; this.view.height = height; } /** * @private */ PIXI.CanvasRenderer.prototype.renderDisplayObject = function(displayObject) { var transform = displayObject.worldTransform; var context = this.context; context.globalCompositeOperation = "source-over" var blit = false; if(!displayObject.visible)return; if(displayObject instanceof PIXI.Sprite) { var frame = displayObject.texture.frame; if(frame) { context.globalAlpha = displayObject.worldAlpha; // BLITZ!!! /* * if the rotation is 0 then we can blitz it * meaning we dont need to do a transform and also we * can round to the nearest round number for a little extra speed! */ /*if(displayObject.rotation == 0) { if(!blit)this.context.setTransform(1,0,0,1,0,0); blit = true; context.drawImage(displayObject.texture.baseTexture.image, frame.x, frame.y, frame.width, frame.height, (transform[2]+ ((displayObject.anchor.x - displayObject.texture.trim.x) * -frame.width) * transform[0]), (transform[5]+ ((displayObject.anchor.y - displayObject.texture.trim.y) * -frame.height)* transform[4]), (displayObject.width * transform[0]), (displayObject.height * transform[4])); } else {*/ blit = false; context.setTransform(transform[0], transform[3], transform[1], transform[4], transform[2], transform[5]) context.drawImage(displayObject.texture.baseTexture.source, frame.x, frame.y, frame.width, frame.height, (displayObject.anchor.x - displayObject.texture.trim.x) * -frame.width, (displayObject.anchor.y - displayObject.texture.trim.y) * -frame.height, displayObject.width, displayObject.height); //} } } else if(displayObject instanceof PIXI.Strip) { context.setTransform(transform[0], transform[3], transform[1], transform[4], transform[2], transform[5]) this.renderStrip(displayObject); } // render! for (var i=0; i < displayObject.children.length; i++) { this.renderDisplayObject(displayObject.children[i]); } } /** * @private */ PIXI.CanvasRenderer.prototype.renderStripFlat = function(strip) { var context = this.context; var verticies = strip.verticies; var uvs = strip.uvs; var length = verticies.length/2; this.count++; context.beginPath(); for (var i=1; i < length-2; i++) { // draw some triangles! var index = i*2; var x0 = verticies[index], x1 = verticies[index+2], x2 = verticies[index+4]; var y0 = verticies[index+1], y1 = verticies[index+3], y2 = verticies[index+5]; context.moveTo(x0, y0); context.lineTo(x1, y1); context.lineTo(x2, y2); }; // context.globalCompositeOperation = 'lighter'; context.fillStyle = "#FF0000"; context.fill(); context.closePath(); //context.globalCompositeOperation = 'source-over'; } /** * @private */ PIXI.CanvasRenderer.prototype.renderStrip = function(strip) { var context = this.context; //context.globalCompositeOperation = 'lighter'; // draw triangles!! var verticies = strip.verticies; var uvs = strip.uvs; var length = verticies.length/2; this.count++; for (var i=1; i < length-2; i++) { // draw some triangles! var index = i*2; var x0 = verticies[index], x1 = verticies[index+2], x2 = verticies[index+4]; var y0 = verticies[index+1], y1 = verticies[index+3], y2 = verticies[index+5]; var u0 = uvs[index] * strip.texture.width, u1 = uvs[index+2]* strip.texture.width, u2 = uvs[index+4]* strip.texture.width; var v0 = uvs[index+1]* strip.texture.height, v1 = uvs[index+3]* strip.texture.height, v2 = uvs[index+5]* strip.texture.height; context.save(); context.beginPath(); context.moveTo(x0, y0); context.lineTo(x1, y1); context.lineTo(x2, y2); context.closePath(); // context.fillStyle = "white"//rgb(1, 1, 1,1)); // context.fill(); context.clip(); // Compute matrix transform var delta = u0*v1 + v0*u2 + u1*v2 - v1*u2 - v0*u1 - u0*v2; var delta_a = x0*v1 + v0*x2 + x1*v2 - v1*x2 - v0*x1 - x0*v2; var delta_b = u0*x1 + x0*u2 + u1*x2 - x1*u2 - x0*u1 - u0*x2; var delta_c = u0*v1*x2 + v0*x1*u2 + x0*u1*v2 - x0*v1*u2 - v0*u1*x2 - u0*x1*v2; var delta_d = y0*v1 + v0*y2 + y1*v2 - v1*y2 - v0*y1 - y0*v2; var delta_e = u0*y1 + y0*u2 + u1*y2 - y1*u2 - y0*u1 - u0*y2; var delta_f = u0*v1*y2 + v0*y1*u2 + y0*u1*v2 - y0*v1*u2 - v0*u1*y2 - u0*y1*v2; context.transform(delta_a/delta, delta_d/delta, delta_b/delta, delta_e/delta, delta_c/delta, delta_f/delta); context.drawImage(strip.texture.baseTexture.source, 0, 0); context.restore(); }; // context.globalCompositeOperation = 'source-over'; } /** * @author Mat Groves http://matgroves.com/ */ PIXI.Strip = function(texture, width, height) { PIXI.DisplayObjectContainer.call( this ); this.texture = texture; this.blendMode = PIXI.blendModes.NORMAL; try { this.uvs = new Float32Array([0, 1, 1, 1, 1, 0, 0,1]); this.verticies = new Float32Array([0, 0, 0,0, 0,0, 0, 0, 0]); this.colors = new Float32Array([1, 1, 1, 1]); this.indices = new Uint16Array([0, 1, 2, 3]); } catch(error) { this.uvs = [0, 1, 1, 1, 1, 0, 0,1]; this.verticies = [0, 0, 0,0, 0,0, 0, 0, 0]; this.colors = [1, 1, 1, 1]; this.indices = [0, 1, 2, 3]; } /* this.uvs = new Float32Array() this.verticies = new Float32Array() this.colors = new Float32Array() this.indices = new Uint16Array() */ this.width = width; this.height = height; // load the texture! if(texture.baseTexture.hasLoaded) { this.width = this.texture.frame.width; this.height = this.texture.frame.height; this.updateFrame = true; } else { this.onTextureUpdateBind = this.onTextureUpdate.bind(this); this.texture.addEventListener( 'update', this.onTextureUpdateBind ); } this.renderable = true; } // constructor PIXI.Strip.constructor = PIXI.Strip; PIXI.Strip.prototype = Object.create( PIXI.DisplayObjectContainer.prototype ); PIXI.Strip.prototype.setTexture = function(texture) { //TODO SET THE TEXTURES //TODO VISIBILITY // stop current texture this.texture = texture; this.width = texture.frame.width; this.height = texture.frame.height; this.updateFrame = true; } PIXI.Strip.prototype.onTextureUpdate = function(event) { this.updateFrame = true; } // some helper functions.. /** * @author Mat Groves http://matgroves.com/ */ PIXI.Rope = function(texture, points) { PIXI.Strip.call( this, texture ); this.points = points; try { this.verticies = new Float32Array( points.length * 4); this.uvs = new Float32Array( points.length * 4); this.colors = new Float32Array( points.length * 2); this.indices = new Uint16Array( points.length * 2); } catch(error) { this.verticies = verticies this.uvs = uvs this.colors = colors this.indices = indices } this.refresh(); } // constructor PIXI.Rope.constructor = PIXI.Rope; PIXI.Rope.prototype = Object.create( PIXI.Strip.prototype ); PIXI.Rope.prototype.refresh = function() { var points = this.points; if(points.length < 1)return; var uvs = this.uvs var indices = this.indices; var colors = this.colors; var lastPoint = points[0]; var nextPoint; var perp = {x:0, y:0}; var point = points[0]; this.count-=0.2; uvs[0] = 0 uvs[1] = 1 uvs[2] = 0 uvs[3] = 1 colors[0] = 1; colors[1] = 1; indices[0] = 0; indices[1] = 1; var total = points.length; for (var i = 1; i < total; i++) { var point = points[i]; var index = i * 4; // time to do some smart drawing! var amount = i/(total-1) if(i%2) { uvs[index] = amount; uvs[index+1] = 0; uvs[index+2] = amount uvs[index+3] = 1 } else { uvs[index] = amount uvs[index+1] = 0 uvs[index+2] = amount uvs[index+3] = 1 } index = i * 2; colors[index] = 1; colors[index+1] = 1; index = i * 2; indices[index] = index; indices[index + 1] = index + 1; lastPoint = point; } } PIXI.Rope.prototype.updateTransform = function() { var points = this.points; if(points.length < 1)return; var verticies = this.verticies var lastPoint = points[0]; var nextPoint; var perp = {x:0, y:0}; var point = points[0]; this.count-=0.2; verticies[0] = point.x + perp.x verticies[1] = point.y + perp.y //+ 200 verticies[2] = point.x - perp.x verticies[3] = point.y - perp.y//+200 // time to do some smart drawing! var total = points.length; for (var i = 1; i < total; i++) { var point = points[i]; var index = i * 4; if(i < points.length-1) { nextPoint = points[i+1]; } else { nextPoint = point } perp.y = -(nextPoint.x - lastPoint.x); perp.x = nextPoint.y - lastPoint.y; var ratio = (1 - (i / (total-1))) * 10; if(ratio > 1)ratio = 1; var perpLength = Math.sqrt(perp.x * perp.x + perp.y * perp.y); var num = this.texture.height/2//(20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio; perp.x /= perpLength; perp.y /= perpLength; perp.x *= num; perp.y *= num; verticies[index] = point.x + perp.x verticies[index+1] = point.y + perp.y verticies[index+2] = point.x - perp.x verticies[index+3] = point.y - perp.y lastPoint = point; } PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); } PIXI.Rope.prototype.setTexture = function(texture) { // stop current texture this.texture = texture; this.updateFrame = true; } /** * @author Mat Groves http://matgroves.com/ @Doormat23 */ PIXI.BaseTextureCache = {}; PIXI.texturesToUpdate = []; /** * A texture stores the information that represents an image. All textures have a base texture * @class BaseTexture * @extends EventTarget * @constructor * @param source {String} the source object (image or canvas) */ PIXI.BaseTexture = function(source) { PIXI.EventTarget.call( this ); /* * The url of the texture * @property imageUrl * @type String */ //this.imageUrl = source.src; /** * [read only] The width of the base texture set when the image has loaded * @property width * @type Number */ this.width = 100; /** * [read only] The height of the base texture set when the image has loaded * @property height * @type Number */ this.height = 100; /** * The source that is loaded to create the texture * @property source * @type Image */ this.source = source//new Image(); if(this.source instanceof Image) { if(this.source.complete) { this.hasLoaded = true; this.width = this.source.width; this.height = this.source.height; PIXI.texturesToUpdate.push(this); } else { var scope = this; this.source.onload = function(){ scope.hasLoaded = true; scope.width = scope.source.width; scope.height = scope.source.height; // add it to somewhere... PIXI.texturesToUpdate.push(scope); scope.dispatchEvent( { type: 'loaded', content: scope } ); } // this.image.src = imageUrl; } } else { this.hasLoaded = true; this.width = this.source.width; this.height = this.source.height; //console.log(">!!",this.width) PIXI.texturesToUpdate.push(this); } } PIXI.BaseTexture.constructor = PIXI.BaseTexture; PIXI.BaseTexture.prototype.fromImage = function(imageUrl) { } /** * @author Mat Groves http://matgroves.com/ @Doormat23 */ PIXI.TextureCache = {}; PIXI.FrameCache = {}; /** * A texture stores the information that represents an image or part of an image. It cannot be added to the display list directly. To do this use PIXI.Sprite. If no frame is provided then the whole image is used * @class Texture * @extends EventTarget * @constructor * @param baseTexture {BaseTexture} * @param frmae {Rectangle} */ PIXI.Texture = function(baseTexture, frame) { PIXI.EventTarget.call( this ); if(!frame) { this.noFrame = true; frame = new PIXI.Rectangle(0,0,1,1); } this.trim = new PIXI.Point(); /** * The base texture of this texture * @property baseTexture * @type BaseTexture */ this.baseTexture = baseTexture; /** * The frame specifies the region of the base texture that this texture uses * @property frame * @type #Rectangle */ this.frame = frame; this.scope = this; if(baseTexture.hasLoaded) { if(this.noFrame)frame = new PIXI.Rectangle(0,0, baseTexture.width, baseTexture.height); //console.log(frame) this.setFrame(frame); } else { var scope = this; baseTexture.addEventListener( 'loaded', function(){ scope.onBaseTextureLoaded()} ); } } PIXI.Texture.constructor = PIXI.Texture; PIXI.Texture.prototype.onBaseTextureLoaded = function(event) { var baseTexture = this.baseTexture; baseTexture.removeEventListener( 'loaded', this.onLoaded ); if(this.noFrame)this.frame = new PIXI.Rectangle(0,0, baseTexture.width, baseTexture.height); this.noFrame = false; this.width = this.frame.width; this.height = this.frame.height; this.scope.dispatchEvent( { type: 'update', content: this } ); } /** * Specifies the rectangle region of the baseTexture * @method setFrame * @param frame {Rectangle} */ PIXI.Texture.prototype.setFrame = function(frame) { this.frame = frame; this.width = frame.width; this.height = frame.height; if(frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height) { throw new Error("Texture Error: frame does not fit inside the base Texture dimensions " + this); } //this.updateFrame = true; } /** * * Helper function that returns a texture based on an image url * If the image is not in the texture cache it will be created and loaded * @static * @method fromImage * @param imageUrl {String} The image url of the texture * @return Texture */ PIXI.Texture.fromImage = function(imageUrl, crossorigin) { var texture = PIXI.TextureCache[imageUrl]; if(!texture) { var baseTexture = PIXI.BaseTextureCache[imageUrl]; if(!baseTexture) { var image = new Image();//new Image(); if (crossorigin) { image.crossOrigin = ''; } image.src = imageUrl; baseTexture = new PIXI.BaseTexture(image); PIXI.BaseTextureCache[imageUrl] = baseTexture; } texture = new PIXI.Texture(baseTexture); PIXI.TextureCache[imageUrl] = texture; } return texture; } /** * * Helper function that returns a texture based on a frame id * If the frame id is not in the texture cache an error will be thrown * @method fromFrame * @param frameId {String} The frame id of the texture * @return Texture */ PIXI.Texture.fromFrame = function(frameId) { var texture = PIXI.TextureCache[frameId]; if(!texture)throw new Error("The frameId '"+ frameId +"' does not exist in the texture cache " + this); return texture; } /** * * Helper function that returns a texture based on a canvas element * If the canvas is not in the texture cache it will be created and loaded * @static * @method fromCanvas * @param canvas {Canvas} The canvas element source of the texture * @return Texture */ PIXI.Texture.fromCanvas = function(canvas) { // create a canvas id?? var texture = PIXI.TextureCache[canvas]; if(!texture) { var baseTexture = PIXI.BaseTextureCache[canvas]; if(!baseTexture) { baseTexture = new PIXI.BaseTexture(canvas); PIXI.BaseTextureCache[canvas] = baseTexture; } texture = new PIXI.Texture(baseTexture); PIXI.TextureCache[canvas] = texture; } return texture; } /** * * Adds a texture to the textureCache. * @method addTextureToCache * @param texture {Texture} * @param id {String} the id that the texture will be stored against. */ PIXI.Texture.addTextureToCache = function(texture, id) { PIXI.TextureCache[id] = texture; } /** * * Remove a texture from the textureCache. * @method removeTextureFromCache * @param id {String} the id of the texture to be removed * @return {Texture} the texture that was removed */ PIXI.Texture.removeTextureFromCache = function(id) { var texture = PIXI.TextureCache[id] PIXI.TextureCache[id] = null; return texture; } /** * @author Mat Groves http://matgroves.com/ @Doormat23 */ /** * The sprite sheet loader is used to load in JSON sprite sheet data * To generate the data you can use http://www.codeandweb.com/texturepacker and publish the "JSON" format * There is a free version so thats nice, although the paid version is great value for money. * It is highly recommended to use Sprite sheets (also know as texture atlas') as it means sprite's can be batched and drawn together for highly increased rendering speed. * Once the data has been loaded the frames are stored in the PIXI texture cache and can be accessed though PIXI.Texture.fromFrameId() and PIXI.Sprite.fromFromeId() * This loader will also load the image file that the Spritesheet points to as well as the data. * When loaded this class will dispatch a 'loaded' event * @class SpriteSheetLoader * @extends EventTarget * @constructor * @param url {String} the url of the sprite sheet JSON file */ PIXI.SpriteSheetLoader = function(url) { /* * i use texture packer to load the assets.. * http://www.codeandweb.com/texturepacker * make sure to set the format as "JSON" */ PIXI.EventTarget.call( this ); this.url = url; this.baseUrl = url.replace(/[^\/]*$/, ''); this.texture; this.frames = {}; this.crossorigin = false; } // constructor PIXI.SpriteSheetLoader.constructor = PIXI.SpriteSheetLoader; /** * This will begin loading the JSON file */ PIXI.SpriteSheetLoader.prototype.load = function() { this.ajaxRequest = new AjaxRequest(); var scope = this; this.ajaxRequest.onreadystatechange=function() { scope.onLoaded(); } this.ajaxRequest.open("GET", this.url, true) if (this.ajaxRequest.overrideMimeType) this.ajaxRequest.overrideMimeType("application/json"); this.ajaxRequest.send(null) } PIXI.SpriteSheetLoader.prototype.onLoaded = function() { if (this.ajaxRequest.readyState==4) { if (this.ajaxRequest.status==200 || window.location.href.indexOf("http")==-1) { var jsondata = eval("("+this.ajaxRequest.responseText+")"); var textureUrl = this.baseUrl + jsondata.meta.image; this.texture = PIXI.Texture.fromImage(textureUrl, this.crossorigin).baseTexture; // if(!this.texture)this.texture = new PIXI.Texture(textureUrl); var frameData = jsondata.frames; for (var i in frameData) { var rect = frameData[i].frame; PIXI.TextureCache[i] = new PIXI.Texture(this.texture, {x:rect.x, y:rect.y, width:rect.w, height:rect.h}); if(frameData[i].trimmed) { //var realSize = frameData[i].spriteSourceSize; PIXI.TextureCache[i].realSize = frameData[i].spriteSourceSize; PIXI.TextureCache[i].trim.x = 0// (realSize.x / rect.w) // calculate the offset! } // this.frames[i] = ; } if(this.texture.hasLoaded) { this.dispatchEvent( { type: 'loaded', content: this } ); } else { var scope = this; // wait for the texture to load.. this.texture.addEventListener('loaded', function(){ scope.dispatchEvent( { type: 'loaded', content: scope } ); }); } } } } /** * @author Mat Groves http://matgroves.com/ @Doormat23 */ /** * A Class that loads a bunch of images / sprite sheet files. Once the assets have been loaded they are added to the PIXI Texture cache and can be accessed easily through PIXI.Texture.fromFrame(), PIXI.Texture.fromImage() and PIXI.Sprite.fromImage(), PIXI.Sprite.fromFromeId() * When all items have been loaded this class will dispatch a 'loaded' event * As each individual item is loaded this class will dispatch a 'progress' event * @class AssetLoader * @constructor * @extends EventTarget * @param assetURLs {Array} an array of image/sprite sheet urls that you would like loaded supported. Supported image formats include "jpeg", "jpg", "png", "gif". Supported sprite sheet data formats only include "JSON" at this time */ PIXI.AssetLoader = function(assetURLs) { PIXI.EventTarget.call( this ); /** * The array of asset URLs that are going to be loaded * @property assetURLs * @type Array */ this.assetURLs = assetURLs; this.assets = []; this.crossorigin = false; } /** Fired when an item has loaded @event onProgress **/ /** Fired when all the assets have loaded @event onComplete **/ // constructor PIXI.AssetLoader.constructor = PIXI.AssetLoader; /** * This will begin loading the assets sequentially */ PIXI.AssetLoader.prototype.load = function() { this.loadCount = this.assetURLs.length; var imageTypes = ["jpeg", "jpg", "png", "gif"]; var spriteSheetTypes = ["json"]; for (var i=0; i < this.assetURLs.length; i++) { var filename = this.assetURLs[i]; var fileType = filename.split('.').pop().toLowerCase(); // what are we loading? var type = null; for (var j=0; j < imageTypes.length; j++) { if(fileType == imageTypes[j]) { type = "img"; break; } } if(type != "img") { for (var j=0; j < spriteSheetTypes.length; j++) { if(fileType == spriteSheetTypes[j]) { type = "atlas"; break; } } } if(type == "img") { var texture = PIXI.Texture.fromImage(filename, this.crossorigin); if(!texture.baseTexture.hasLoaded) { var scope = this; texture.baseTexture.addEventListener( 'loaded', function ( event ) { scope.onAssetLoaded(); }); this.assets.push(texture); } else { // already loaded! this.loadCount--; // if this hits zero here.. then everything was cached! if(this.loadCount == 0) { this.dispatchEvent( { type: 'onComplete', content: this } ); if(this.onComplete)this.onComplete(); } } } else if(type == "atlas") { var spriteSheetLoader = new PIXI.SpriteSheetLoader(filename); spriteSheetLoader.crossorigin = this.crossorigin; this.assets.push(spriteSheetLoader); var scope = this; spriteSheetLoader.addEventListener( 'loaded', function ( event ) { scope.onAssetLoaded(); }); spriteSheetLoader.load(); } else { // dont know what the file is! :/ //this.loadCount--; throw new Error(filename + " is an unsupported file type " + this); } //this.assets[i].load(); }; } PIXI.AssetLoader.prototype.onAssetLoaded = function() { this.loadCount--; this.dispatchEvent( { type: 'onProgress', content: this } ); if(this.onProgress)this.onProgress(); if(this.loadCount == 0) { this.dispatchEvent( { type: 'onComplete', content: this } ); if(this.onComplete)this.onComplete(); } }
webpackJsonp([8],{61:function(e,o,t){var n,s;t(62),n=t(63),s=t(64),e.exports=n||{},e.exports.__esModule&&(e.exports=e.exports.default),s&&(("function"==typeof e.exports?e.exports.options:e.exports).template=s)},62:function(e,o){},63:function(e,o){"use strict";Object.defineProperty(o,"__esModule",{value:!0}),o.default={data:function(){return{mustLearn:""}},components:{}}},64:function(e,o){e.exports=' <div _v-0708e8b4=""> <label _v-0708e8b4="">้€‰ๆ‹ฉๅญฆ้™ข</label> <select class=from-control v-model=mustLearn _v-0708e8b4=""> <option value=1 _v-0708e8b4="">ๅฟ…ไฟฎ</option> <option value=0 _v-0708e8b4="">้€‰ไฟฎ</option> </select> <select class=from-control v-model=mustLearn _v-0708e8b4=""> <option value=1 _v-0708e8b4="">ๅฟ…ไฟฎ</option> <option value=0 _v-0708e8b4="">้€‰ไฟฎ</option> </select> </div> '}});
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path fillOpacity=".3" d="M15.5 14.5c0-2.8 2.2-5 5-5 .36 0 .71.04 1.05.11L23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7L12 21.5l3.5-4.36V14.5z" /><path d="M15.5 14.5c0-1.34.51-2.53 1.34-3.42C15.62 10.51 13.98 10 12 10c-4.1 0-6.8 2.2-7.2 2.5l7.2 9 3.5-4.38V14.5zM23 16v-1.5c0-1.4-1.1-2.5-2.5-2.5S18 13.1 18 14.5V16c-.5 0-1 .5-1 1v4c0 .5.5 1 1 1h5c.5 0 1-.5 1-1v-4c0-.5-.5-1-1-1zm-1 0h-3v-1.5c0-.8.7-1.5 1.5-1.5s1.5.7 1.5 1.5V16z" /></g></React.Fragment> , 'SignalWifi2BarLockTwoTone');
/* mustache.js โ€” Logic-less templates in JavaScript See http://mustache.github.com/ for more info. */ var Mustache = function () { var _toString = Object.prototype.toString; Array.isArray = Array.isArray || function (obj) { return _toString.call(obj) == "[object Array]"; } var _trim = String.prototype.trim, trim; if (_trim) { trim = function (text) { return text == null ? "" : _trim.call(text); } } else { var trimLeft, trimRight; // IE doesn't match non-breaking spaces with \s. if ((/\S/).test("\xA0")) { trimLeft = /^[\s\xA0]+/; trimRight = /[\s\xA0]+$/; } else { trimLeft = /^\s+/; trimRight = /\s+$/; } trim = function (text) { return text == null ? "" : text.toString().replace(trimLeft, "").replace(trimRight, ""); } } function escapeHTML(string) { return String(string) .replace(/&(?!\w+;)/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/"/g, "&quot;") .replace(/'/g, "&#39;"); } var regexCache = {}; var Renderer = function () {}; Renderer.prototype = { otag: "{{", ctag: "}}", pragmas: {}, buffer: [], pragmas_implemented: { "IMPLICIT-ITERATOR": true }, context: {}, render: function (template, context, partials, in_recursion) { // reset buffer & set context if (!in_recursion) { this.context = context; this.buffer = []; // TODO: make this non-lazy } // fail fast if (!this.includes("", template)) { if (in_recursion) { return template; } else { this.send(template); return; } } // get the pragmas together template = this.render_pragmas(template); // render the template var html = this.render_section(template, context, partials); // render_section did not find any sections, we still need to render the tags if (html === false) { html = this.render_tags(template, context, partials, in_recursion); } if (in_recursion) { return html; } else { this.sendLines(html); } }, /* Sends parsed lines */ send: function (line) { if (line !== "") { this.buffer.push(line); } }, sendLines: function (text) { if (text) { var lines = text.split("\n"); for (var i = 0; i < lines.length; i++) { this.send(lines[i]); } } }, /* Looks for %PRAGMAS */ render_pragmas: function (template) { // no pragmas if (!this.includes("%", template)) { return template; } var that = this; var regex = this.getCachedRegex("render_pragmas", function (otag, ctag) { return new RegExp(otag + "%([\\w-]+) ?([\\w]+=[\\w]+)?" + ctag, "g"); }); return template.replace(regex, function (match, pragma, options) { if (!that.pragmas_implemented[pragma]) { throw({message: "This implementation of mustache doesn't understand the '" + pragma + "' pragma"}); } that.pragmas[pragma] = {}; if (options) { var opts = options.split("="); that.pragmas[pragma][opts[0]] = opts[1]; } return ""; // ignore unknown pragmas silently }); }, /* Tries to find a partial in the curent scope and render it */ render_partial: function (name, context, partials) { name = trim(name); if (!partials || partials[name] === undefined) { throw({message: "unknown_partial '" + name + "'"}); } if (!context || typeof context[name] != "object") { return this.render(partials[name], context, partials, true); } return this.render(partials[name], context[name], partials, true); }, /* Renders inverted (^) and normal (#) sections */ render_section: function (template, context, partials) { if (!this.includes("#", template) && !this.includes("^", template)) { // did not render anything, there were no sections return false; } var that = this; var regex = this.getCachedRegex("render_section", function (otag, ctag) { // This regex matches _the first_ section ({{#foo}}{{/foo}}), and captures the remainder return new RegExp( "^([\\s\\S]*?)" + // all the crap at the beginning that is not {{*}} ($1) otag + // {{ "(\\^|\\#)\\s*(.+)\\s*" + // #foo (# == $2, foo == $3) ctag + // }} "\n*([\\s\\S]*?)" + // between the tag ($2). leading newlines are dropped otag + // {{ "\\/\\s*\\3\\s*" + // /foo (backreference to the opening tag). ctag + // }} "\\s*([\\s\\S]*)$", // everything else in the string ($4). leading whitespace is dropped. "g"); }); // for each {{#foo}}{{/foo}} section do... return template.replace(regex, function (match, before, type, name, content, after) { // before contains only tags, no sections var renderedBefore = before ? that.render_tags(before, context, partials, true) : "", // after may contain both sections and tags, so use full rendering function renderedAfter = after ? that.render(after, context, partials, true) : "", // will be computed below renderedContent, value = that.find(name, context); if (type === "^") { // inverted section if (!value || Array.isArray(value) && value.length === 0) { // false or empty list, render it renderedContent = that.render(content, context, partials, true); } else { renderedContent = ""; } } else if (type === "#") { // normal section if (Array.isArray(value)) { // Enumerable, Let's loop! renderedContent = that.map(value, function (row) { return that.render(content, that.create_context(row), partials, true); }).join(""); } else if (that.is_object(value)) { // Object, Use it as subcontext! renderedContent = that.render(content, that.create_context(value), partials, true); } else if (typeof value == "function") { // higher order section renderedContent = value.call(context, content, function (text) { return that.render(text, context, partials, true); }); } else if (value) { // boolean section renderedContent = that.render(content, context, partials, true); } else { renderedContent = ""; } } return renderedBefore + renderedContent + renderedAfter; }); }, /* Replace {{foo}} and friends with values from our view */ render_tags: function (template, context, partials, in_recursion) { // tit for tat var that = this; var new_regex = function () { return that.getCachedRegex("render_tags", function (otag, ctag) { return new RegExp(otag + "(=|!|>|\\{|%)?([^\\/#\\^]+?)\\1?" + ctag + "+", "g"); }); }; var regex = new_regex(); var tag_replace_callback = function (match, operator, name) { switch(operator) { case "!": // ignore comments return ""; case "=": // set new delimiters, rebuild the replace regexp that.set_delimiters(name); regex = new_regex(); return ""; case ">": // render partial return that.render_partial(name, context, partials); case "{": // the triple mustache is unescaped return that.find(name, context); default: // escape the value return escapeHTML(that.find(name, context)); } }; var lines = template.split("\n"); for(var i = 0; i < lines.length; i++) { lines[i] = lines[i].replace(regex, tag_replace_callback, this); if (!in_recursion) { this.send(lines[i]); } } if (in_recursion) { return lines.join("\n"); } }, set_delimiters: function (delimiters) { var dels = delimiters.split(" "); this.otag = this.escape_regex(dels[0]); this.ctag = this.escape_regex(dels[1]); }, escape_regex: function (text) { // thank you Simon Willison if (!arguments.callee.sRE) { var specials = [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\' ]; arguments.callee.sRE = new RegExp( '(\\' + specials.join('|\\') + ')', 'g' ); } return text.replace(arguments.callee.sRE, '\\$1'); }, /* find `name` in current `context`. That is find me a value from the view object */ find: function (name, context) { name = trim(name); // Checks whether a value is thruthy or false or 0 function is_kinda_truthy(bool) { return bool === false || bool === 0 || bool; } var value; // check for dot notation eg. foo.bar if (name.match(/([a-z_]+)\./ig)) { var childValue = this.walk_context(name, context); if (is_kinda_truthy(childValue)) { value = childValue; } } else { if (is_kinda_truthy(context[name])) { value = context[name]; } else if (is_kinda_truthy(this.context[name])) { value = this.context[name]; } } if (typeof value == "function") { return value.apply(context); } if (value !== undefined) { return value; } // silently ignore unkown variables return ""; }, walk_context: function (name, context) { var path = name.split('.'); // if the var doesn't exist in current context, check the top level context var value_context = (context[path[0]] != undefined) ? context : this.context; var value = value_context[path.shift()]; while (value != undefined && path.length > 0) { value_context = value; value = value[path.shift()]; } // if the value is a function, call it, binding the correct context if (typeof value == "function") { return value.apply(value_context); } return value; }, // Utility methods /* includes tag */ includes: function (needle, haystack) { return haystack.indexOf(this.otag + needle) != -1; }, // by @langalex, support for arrays of strings create_context: function (_context) { if (this.is_object(_context)) { return _context; } else { var iterator = "."; if (this.pragmas["IMPLICIT-ITERATOR"]) { iterator = this.pragmas["IMPLICIT-ITERATOR"].iterator; } var ctx = {}; ctx[iterator] = _context; return ctx; } }, is_object: function (a) { return a && typeof a == "object"; }, /* Why, why, why? Because IE. Cry, cry cry. */ map: function (array, fn) { if (typeof array.map == "function") { return array.map(fn); } else { var r = []; var l = array.length; for(var i = 0; i < l; i++) { r.push(fn(array[i])); } return r; } }, getCachedRegex: function (name, generator) { var byOtag = regexCache[this.otag]; if (!byOtag) { byOtag = regexCache[this.otag] = {}; } var byCtag = byOtag[this.ctag]; if (!byCtag) { byCtag = byOtag[this.ctag] = {}; } var regex = byCtag[name]; if (!regex) { regex = byCtag[name] = generator(this.otag, this.ctag); } return regex; } }; return({ name: "mustache.js", version: "0.4.0-dev", /* Turns a template and view into HTML */ to_html: function (template, view, partials, send_fun) { var renderer = new Renderer(); if (send_fun) { renderer.send = send_fun; } renderer.render(template, view || {}, partials); if (!send_fun) { return renderer.buffer.join("\n"); } } }); }();
/** * Copyright <%= year %> Telerik AD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function(f, define){ define([], f); })(function(){ /* * Kendo UI Web v2012.1.322 (http://kendoui.com) * Copyright 2012 Telerik AD. All rights reserved. * * Kendo UI Web commercial licenses may be obtained at http://kendoui.com/web-license * If you do not own a commercial license, this file shall be governed by the * GNU General Public License (GPL) version 3. * For GPL requirements, please review: http://www.gnu.org/copyleft/gpl.html */ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["ru-UA"] = { name: "ru-UA", numberFormat: { pattern: ["-n"], decimals: 2, ",": "ย ", ".": ",", groupSize: [3], percent: { pattern: ["-n%","n%"], decimals: 2, ",": "ย ", ".": ",", groupSize: [3], symbol: "%" }, currency: { pattern: ["-n$","n$"], decimals: 2, ",": "ย ", ".": ",", groupSize: [3], symbol: "โ‚ด" } }, calendars: { standard: { days: { names: ["ะฒะพัะบั€ะตัะตะฝัŒะต","ะฟะพะฝะตะดะตะปัŒะฝะธะบ","ะฒั‚ะพั€ะฝะธะบ","ัั€ะตะดะฐ","ั‡ะตั‚ะฒะตั€ะณ","ะฟัั‚ะฝะธั†ะฐ","ััƒะฑะฑะพั‚ะฐ"], namesAbbr: ["ะ’ั","ะŸะฝ","ะ’ั‚","ะกั€","ะงั‚","ะŸั‚","ะกะฑ"], namesShort: ["ะ’ั","ะŸะฝ","ะ’ั‚","ะกั€","ะงั‚","ะŸั‚","ะกะฑ"] }, months: { names: ["ะฏะฝะฒะฐั€ัŒ","ะคะตะฒั€ะฐะปัŒ","ะœะฐั€ั‚","ะะฟั€ะตะปัŒ","ะœะฐะน","ะ˜ัŽะฝัŒ","ะ˜ัŽะปัŒ","ะะฒะณัƒัั‚","ะกะตะฝั‚ัะฑั€ัŒ","ะžะบั‚ัะฑั€ัŒ","ะะพัะฑั€ัŒ","ะ”ะตะบะฐะฑั€ัŒ",""], namesAbbr: ["ัะฝะฒ","ั„ะตะฒ","ะผะฐั€","ะฐะฟั€","ะผะฐะน","ะธัŽะฝ","ะธัŽะป","ะฐะฒะณ","ัะตะฝ","ะพะบั‚","ะฝะพั","ะดะตะบ",""] }, AM: [""], PM: [""], patterns: { d: "dd.MM.yyyy", D: "d MMMM yyyy 'ะณ.'", F: "d MMMM yyyy 'ะณ.' H:mm:ss", g: "dd.MM.yyyy H:mm", G: "dd.MM.yyyy H:mm:ss", m: "MMMM dd", M: "MMMM dd", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "H:mm", T: "H:mm:ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM yyyy", Y: "MMMM yyyy" }, "/": ".", ":": ":", firstDay: 1 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
var gulp = require('gulp'); var config = require('../config'); var gutil = require('gulp-util'); var jsdoc = require("gulp-jsdoc"); var plumber = require('gulp-plumber'); gulp.task('docs', function() { return gulp.src( config.js.src + '/**/*.js' ) .pipe( plumber() ) .pipe( jsdoc( config.docs ) ); });
/* */ var isObject = require('../lang/isObject'); function isStrictComparable(value) { return value === value && !isObject(value); } module.exports = isStrictComparable;
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M13 3H6v18h4v-6h3c3.31 0 6-2.69 6-6s-2.69-6-6-6zm.2 8H10V7h3.2c1.1 0 2 .9 2 2s-.9 2-2 2z" /> , 'LocalParkingTwoTone');
import React, {PropTypes} from 'react'; var {RouteHandler} = require('react-router'); var App = React.createClass({ propTypes: { flux: PropTypes.object.isRequired }, render() { return <RouteHandler flux={this.props.flux}/>; } }); module.exports = App;
๏ปฟ/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'adv_link', 'he', { acccessKey: 'ืžืงืฉ ื’ื™ืฉื”', advanced: 'ืืคืฉืจื•ื™ื•ืช ืžืชืงื“ืžื•ืช', advisoryContentType: 'Content Type ืžื•ืฆืข', advisoryTitle: 'ื›ื•ืชืจืช ืžื•ืฆืขืช', anchor: { toolbar: 'ื”ื•ืกืคืช/ืขืจื™ื›ืช ื ืงื•ื“ืช ืขื™ื’ื•ืŸ', menu: 'ืžืืคื™ื™ื ื™ ื ืงื•ื“ืช ืขื™ื’ื•ืŸ', title: 'ืžืืคื™ื™ื ื™ ื ืงื•ื“ืช ืขื™ื’ื•ืŸ', name: 'ืฉื ืœื ืงื•ื“ืช ืขื™ื’ื•ืŸ', errorName: 'ื™ืฉ ืœื”ืงืœื™ื“ ืฉื ืœื ืงื•ื“ืช ืขื™ื’ื•ืŸ', remove: 'ืžื—ื™ืงืช ื ืงื•ื“ืช ืขื™ื’ื•ืŸ' }, anchorId: 'ืขืค"ื™ ื–ื™ื”ื•ื™ (ID) ื”ืืœืžื ื˜', anchorName: 'ืขืค"ื™ ืฉื ื”ืขื•ื’ืŸ', charset: 'ืงื™ื“ื•ื“ ื”ืžืฉืื‘ ื”ืžืงื•ืฉืจ', cssClasses: 'ื’ื™ืœื™ื•ื ื•ืช ืขื™ืฆื•ื‘ ืงื‘ื•ืฆื•ืช', emailAddress: 'ื›ืชื•ื‘ืช ื”ื“ื•ื"ืœ', emailBody: 'ื’ื•ืฃ ื”ื”ื•ื“ืขื”', emailSubject: 'ื ื•ืฉื ื”ื”ื•ื“ืขื”', id: 'ื–ื™ื”ื•ื™ (ID)', info: 'ืžื™ื“ืข ืขืœ ื”ืงื™ืฉื•ืจ', langCode: 'ืงื•ื“ ืฉืคื”', langDir: 'ื›ื™ื•ื•ืŸ ืฉืคื”', langDirLTR: 'ืฉืžืืœ ืœื™ืžื™ืŸ (LTR)', langDirRTL: 'ื™ืžื™ืŸ ืœืฉืžืืœ (RTL)', menu: 'ืžืืคื™ื™ื ื™ ืงื™ืฉื•ืจ', name: 'ืฉื', noAnchors: '(ืื™ืŸ ืขื•ื’ื ื™ื ื–ืžื™ื ื™ื ื‘ื“ืฃ)', noEmail: 'ื™ืฉ ืœื”ืงืœื™ื“ ืืช ื›ืชื•ื‘ืช ื”ื“ื•ื"ืœ', noUrl: 'ื™ืฉ ืœื”ืงืœื™ื“ ืืช ื›ืชื•ื‘ืช ื”ืงื™ืฉื•ืจ (URL)', other: '<ืื—ืจ>', popupDependent: 'ืชืœื•ื™ (Netscape)', popupFeatures: 'ืชื›ื•ื ื•ืช ื”ื—ืœื•ืŸ ื”ืงื•ืคืฅ', popupFullScreen: 'ืžืกืš ืžืœื (IE)', popupLeft: 'ืžื™ืงื•ื ืฆื“ ืฉืžืืœ', popupLocationBar: 'ืกืจื’ืœ ื›ืชื•ื‘ืช', popupMenuBar: 'ืกืจื’ืœ ืชืคืจื™ื˜', popupResizable: 'ืฉื™ื ื•ื™ ื’ื•ื“ืœ', popupScrollBars: 'ื ื™ืชืŸ ืœื’ืœื™ืœื”', popupStatusBar: 'ืกืจื’ืœ ื—ื™ื•ื•ื™', popupToolbar: 'ืกืจื’ืœ ื”ื›ืœื™ื', popupTop: 'ืžื™ืงื•ื ืฆื“ ืขืœื™ื•ืŸ', rel: 'ืงืฉืจ ื’ื•ืžืœื™ืŸ', selectAnchor: 'ื‘ื—ื™ืจืช ืขื•ื’ืŸ', styles: 'ืกื’ื ื•ืŸ', tabIndex: 'ืžืกืคืจ ื˜ืื‘', target: 'ืžื˜ืจื”', targetFrame: '<ืžืกื’ืจืช>', targetFrameName: 'ืฉื ืžืกื’ืจืช ื”ื™ืขื“', targetPopup: '<ื—ืœื•ืŸ ืงื•ืคืฅ>', targetPopupName: 'ืฉื ื”ื—ืœื•ืŸ ื”ืงื•ืคืฅ', title: 'ืงื™ืฉื•ืจ', toAnchor: 'ืขื•ื’ืŸ ื‘ืขืžื•ื“ ื–ื”', toEmail: 'ื“ื•ื"ืœ', toUrl: 'ื›ืชื•ื‘ืช (URL)', toolbar: 'ื”ื•ืกืคืช/ืขืจื™ื›ืช ืงื™ืฉื•ืจ', type: 'ืกื•ื’ ืงื™ืฉื•ืจ', unlink: 'ื”ืกืจืช ื”ืงื™ืฉื•ืจ', upload: 'ื”ืขืœืื”' } );
/*! * Bootstrap-select v1.13.12 (https://developer.snapappointments.com/bootstrap-select) * * Copyright 2012-2019 SnapAppointments, LLC * Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE) */ !function(e,t){void 0===e&&void 0!==window&&(e=window),"function"==typeof define&&define.amd?define(["jquery"],function(e){return t(e)}):"object"==typeof module&&module.exports?module.exports=t(require("jquery")):t(e.jQuery)}(this,function(e){e.fn.selectpicker.defaults={noneSelectedText:"Tidak ada yang dipilih",noneResultsText:"Tidak ada yang cocok {0}",countSelectedText:"{0} terpilih",maxOptionsText:["Mencapai batas (maksimum {n})","Mencapai batas grup (maksimum {n})"],selectAllText:"Pilih Semua",deselectAllText:"Hapus Semua",multipleSeparator:", "}});
var lastTime = null; function updateAnimation() { // Your code here. } function frame(time) { if (lastTime !== null) { updateAnimation(Math.min(100, time - lastTime) / 1000); } lastTime = time; requestAnimationFrame(frame); } requestAnimationFrame(frame);
module.exports = function(grunt) { grunt.loadNpmTasks('grunt-sass'); grunt.loadNpmTasks('grunt-includes'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.initConfig({ sass: { options: { sourceMap: true, outputStyle: 'compressed' }, portal: { files: { 'resources/css/glasscityhacks.min.css' : 'src/scss/init.scss' } } }, clean: { css: [ 'resources/css' ], js: [ 'resources/js' ] }, uglify: { options: { sourceMap: true, mangle: { except: ['jQuery'] }, compress: true }, js: { files: { 'resources/js/glasscityhacks.min.js': [ 'src/lib/jquery/jquery-2.1.4.min.js', 'src/lib/scrollspy/jquery.scrollspy.js', 'src/lib/scrollto/jquery.scrollTo.min.js', 'src/js/**/*.js' ] } } }, includes: { views: { cwd: 'src/views', src: ['**/*.html', '!global/*.html' ], dest: '', flatten: true } } }); grunt.registerTask('build-views', ['includes:views']); grunt.registerTask('build-css', ['clean:css','sass:portal']); grunt.registerTask('build-javascript', ['clean:js', 'uglify:js']); };
/* */ var $def = require("./$.def"), toIndex = require("./$").toIndex, fromCharCode = String.fromCharCode; $def($def.S, 'String', {fromCodePoint: function fromCodePoint(x) { var res = [], len = arguments.length, i = 0, code; while (len > i) { code = +arguments[i++]; if (toIndex(code, 0x10ffff) !== code) throw RangeError(code + ' is not a valid code point'); res.push(code < 0x10000 ? fromCharCode(code) : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00)); } return res.join(''); }});
import React from 'react'; class ComponentName extends React.Component { render() { return <div data-qa="custom-attribute"> <h1>Hello world</h1> </div>; } } export default ComponentName;
// read dbus adress from window selection const x11 = require('x11'); const fs = require('fs'); const os = require('os'); function getDbusAddress(callback) { // read machine uuid fs.readFile('/var/lib/dbus/machine-id', 'ascii', function(err, uuid) { if (err) return callback(err); var hostname = os.hostname().split('-')[0]; x11.createClient(function(err, display) { var X = display.client; var selectionName = `_DBUS_SESSION_BUS_SELECTION_${ hostname }_${uuid.trim()}`; X.InternAtom(false, selectionName, function(err, id) { if (err) return callback(err); X.GetSelectionOwner(id, function(err, win) { if (err) return callback(err); X.InternAtom(false, '_DBUS_SESSION_BUS_ADDRESS', function( err, propId ) { if (err) return callback(err); win = display.screen[0].root; X.GetProperty(0, win, propId, 0, 0, 10000000, function(err, val) { if (err) return callback(err); callback(null, val.data.toString()); }); }); }); }); }); }); } module.exports = getDbusAddress;
describe('Hand of the King', function () { integration({ isMelee: true }, function () { describe('initiating additional power challenge', function () { beforeEach(function () { const deck = this.buildDeck('stark', [ 'A Noble Cause', 'Bastard in Hiding', 'Shireen Baratheon (Core)' ]); this.player1.selectDeck(deck); this.player2.selectDeck(deck); this.player3.selectDeck(deck); this.startGame(); this.keepStartingHands(); this.player1.clickCard('Bastard in Hiding', 'hand'); this.player1.clickCard('Shireen Baratheon (Core)', 'hand'); this.completeSetup(); this.selectFirstPlayer(this.player1); this.player1.selectTitle('Hand of the King'); this.player2.selectTitle('Master of Coin'); this.player3.selectTitle('Master of Ships'); this.completeMarshalPhase(); // Power challenge vs player2 this.player1.clickPrompt('Power'); this.player1.clickPrompt('player2'); this.player1.clickCard('Bastard in Hiding'); this.player1.clickPrompt('Done'); this.skipActionWindow(); this.player2.clickPrompt('Done'); this.skipActionWindow(); this.player1.clickPrompt('Apply Claim'); // Additional power challenge this.player1.clickPrompt('Power'); }); it('should allow an additional challenge against the other player', function () { expect(this.player1).toHaveDisabledPromptButton('player2'); expect(this.player1).toHavePromptButton('player3'); }); }); describe('when the player already has an additional power challenge', function () { beforeEach(function () { const deck = this.buildDeck('stark', [ 'Sailing the Summer Sea', 'Bastard in Hiding', 'Shireen Baratheon (Core)' ]); this.player1.selectDeck(deck); this.player2.selectDeck(deck); this.player3.selectDeck(deck); this.startGame(); this.keepStartingHands(); this.player1.clickCard('Bastard in Hiding', 'hand'); this.player1.clickCard('Shireen Baratheon (Core)', 'hand'); this.completeSetup(); this.selectFirstPlayer(this.player1); this.player1.selectTitle('Hand of the King'); this.player2.selectTitle('Master of Coin'); this.player3.selectTitle('Master of Ships'); this.completeMarshalPhase(); // Power challenge vs player2 this.player1.clickPrompt('Power'); this.player1.clickPrompt('player2'); this.player1.clickCard('Bastard in Hiding'); this.player1.clickPrompt('Done'); this.skipActionWindow(); this.player2.clickPrompt('Done'); this.skipActionWindow(); this.player1.clickPrompt('Apply Claim'); // Additional power challenge this.player1.clickPrompt('Power'); }); it('should not limit the opponent for the second challenge', function () { expect(this.player1).toHavePromptButton('player2'); }); it('should limit the opponent for the third challenge', function () { // Power challenge #2 vs player 2 this.player1.clickPrompt('player2'); this.player1.clickCard('Shireen Baratheon (Core)'); this.player1.clickPrompt('Done'); this.skipActionWindow(); this.player2.clickPrompt('Done'); this.skipActionWindow(); this.player1.clickPrompt('Apply Claim'); // Power challenge #3 this.player1.clickPrompt('Power'); expect(this.player1).toHaveDisabledPromptButton('player2'); }); it('should not limit the opponent for the third challenge if second challenge opponent was different', function () { // Power challenge vs player 3 this.player1.clickPrompt('player3'); this.player1.clickCard('Shireen Baratheon (Core)'); this.player1.clickPrompt('Done'); this.skipActionWindow(); this.player3.clickPrompt('Done'); this.skipActionWindow(); this.player1.clickPrompt('Apply Claim'); // Power challenge #3 this.player1.clickPrompt('Power'); expect(this.player1).toHavePromptButton('player2'); }); }); }); });
/* MD5 Message-Digest Algorithm - JavaScript ' MODIFICATION HISTORY: ' 1.0 16-Feb-2001 - Phil Fresle (sales@frez.co.uk) - Initial Version (VB/ASP code) ' 1.0 21-Feb-2001 - Enrico Mosanghini (erik504@yahoo.com) - JavaScript porting */ function MD5(sMessage) { function RotateLeft(lValue, iShiftBits) { return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits)); } function AddUnsigned(lX,lY) { var lX4,lY4,lX8,lY8,lResult; lX8 = (lX & 0x80000000); lY8 = (lY & 0x80000000); lX4 = (lX & 0x40000000); lY4 = (lY & 0x40000000); lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF); if (lX4 & lY4) { return (lResult ^ 0x80000000 ^ lX8 ^ lY8); } if (lX4 | lY4) { if (lResult & 0x40000000) { return (lResult ^ 0xC0000000 ^ lX8 ^ lY8); } else { return (lResult ^ 0x40000000 ^ lX8 ^ lY8); } } else { return (lResult ^ lX8 ^ lY8); } } function F(x,y,z) { return (x & y) | ((~x) & z); } function G(x,y,z) { return (x & z) | (y & (~z)); } function H(x,y,z) { return (x ^ y ^ z); } function I(x,y,z) { return (y ^ (x | (~z))); } function FF(a,b,c,d,x,s,ac) { a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac)); return AddUnsigned(RotateLeft(a, s), b); } function GG(a,b,c,d,x,s,ac) { a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac)); return AddUnsigned(RotateLeft(a, s), b); } function HH(a,b,c,d,x,s,ac) { a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac)); return AddUnsigned(RotateLeft(a, s), b); } function II(a,b,c,d,x,s,ac) { a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac)); return AddUnsigned(RotateLeft(a, s), b); } function ConvertToWordArray(sMessage) { var lWordCount; var lMessageLength = sMessage.length; var lNumberOfWords_temp1=lMessageLength + 8; var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64; var lNumberOfWords = (lNumberOfWords_temp2+1)*16; var lWordArray=Array(lNumberOfWords-1); var lBytePosition = 0; var lByteCount = 0; while ( lByteCount < lMessageLength ) { lWordCount = (lByteCount-(lByteCount % 4))/4; lBytePosition = (lByteCount % 4)*8; lWordArray[lWordCount] = (lWordArray[lWordCount] | (sMessage.charCodeAt(lByteCount)<<lBytePosition)); lByteCount++; } lWordCount = (lByteCount-(lByteCount % 4))/4; lBytePosition = (lByteCount % 4)*8; lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition); lWordArray[lNumberOfWords-2] = lMessageLength<<3; lWordArray[lNumberOfWords-1] = lMessageLength>>>29; return lWordArray; } function WordToHex(lValue) { var WordToHexValue="",WordToHexValue_temp="",lByte,lCount; for (lCount = 0; lCount<=3; lCount++) { lByte = (lValue>>>(lCount*8)) & 255; WordToHexValue_temp = "0" + lByte.toString(16); WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2); } return WordToHexValue; } var x=Array(); var k,AA,BB,CC,DD,a,b,c,d var S11=7, S12=12, S13=17, S14=22; var S21=5, S22=9 , S23=14, S24=20; var S31=4, S32=11, S33=16, S34=23; var S41=6, S42=10, S43=15, S44=21; // Steps 1 and 2. Append padding bits and length and convert to words x = ConvertToWordArray(sMessage); // Step 3. Initialise a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476; // Step 4. Process the message in 16-word blocks for (k=0; k<x.length; k+=16) { AA=a; BB=b; CC=c; DD=d; a=FF(a,b,c,d,x[k+0], S11,0xD76AA478); d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756); c=FF(c,d,a,b,x[k+2], S13,0x242070DB); b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE); a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF); d=FF(d,a,b,c,x[k+5], S12,0x4787C62A); c=FF(c,d,a,b,x[k+6], S13,0xA8304613); b=FF(b,c,d,a,x[k+7], S14,0xFD469501); a=FF(a,b,c,d,x[k+8], S11,0x698098D8); d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF); c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1); b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE); a=FF(a,b,c,d,x[k+12],S11,0x6B901122); d=FF(d,a,b,c,x[k+13],S12,0xFD987193); c=FF(c,d,a,b,x[k+14],S13,0xA679438E); b=FF(b,c,d,a,x[k+15],S14,0x49B40821); a=GG(a,b,c,d,x[k+1], S21,0xF61E2562); d=GG(d,a,b,c,x[k+6], S22,0xC040B340); c=GG(c,d,a,b,x[k+11],S23,0x265E5A51); b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA); a=GG(a,b,c,d,x[k+5], S21,0xD62F105D); d=GG(d,a,b,c,x[k+10],S22,0x2441453); c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681); b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8); a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6); d=GG(d,a,b,c,x[k+14],S22,0xC33707D6); c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87); b=GG(b,c,d,a,x[k+8], S24,0x455A14ED); a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905); d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8); c=GG(c,d,a,b,x[k+7], S23,0x676F02D9); b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A); a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942); d=HH(d,a,b,c,x[k+8], S32,0x8771F681); c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122); b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C); a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44); d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9); c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60); b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70); a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6); d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA); c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085); b=HH(b,c,d,a,x[k+6], S34,0x4881D05); a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039); d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5); c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8); b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665); a=II(a,b,c,d,x[k+0], S41,0xF4292244); d=II(d,a,b,c,x[k+7], S42,0x432AFF97); c=II(c,d,a,b,x[k+14],S43,0xAB9423A7); b=II(b,c,d,a,x[k+5], S44,0xFC93A039); a=II(a,b,c,d,x[k+12],S41,0x655B59C3); d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92); c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D); b=II(b,c,d,a,x[k+1], S44,0x85845DD1); a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F); d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0); c=II(c,d,a,b,x[k+6], S43,0xA3014314); b=II(b,c,d,a,x[k+13],S44,0x4E0811A1); a=II(a,b,c,d,x[k+4], S41,0xF7537E82); d=II(d,a,b,c,x[k+11],S42,0xBD3AF235); c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB); b=II(b,c,d,a,x[k+9], S44,0xEB86D391); a=AddUnsigned(a,AA); b=AddUnsigned(b,BB); c=AddUnsigned(c,CC); d=AddUnsigned(d,DD); } // Step 5. Output the 128 bit digest var temp= WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d); return temp.toLowerCase(); }
/** * Checkbox renderer * * @private * @renderer CheckboxRenderer * @param {Object} instance Handsontable instance * @param {Element} TD Table cell where to render * @param {Number} row * @param {Number} col * @param {String|Number} prop Row object property name * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!) * @param {Object} cellProperties Cell properties (shared by cell renderer and editor) */ import * as dom from './../dom.js'; import * as helper from './../helpers.js'; import {EventManager} from './../eventManager.js'; import {getRenderer, registerRenderer} from './../renderers.js'; let clonableINPUT = document.createElement('INPUT'); clonableINPUT.className = 'htCheckboxRendererInput'; clonableINPUT.type = 'checkbox'; clonableINPUT.setAttribute('autocomplete', 'off'); const isListeningKeyDownEvent = new WeakMap(); function checkboxRenderer(instance, TD, row, col, prop, value, cellProperties) { const eventManager = new EventManager(instance); // this is faster than createElement const input = clonableINPUT.cloneNode(false); if (typeof cellProperties.checkedTemplate === 'undefined') { cellProperties.checkedTemplate = true; } if (typeof cellProperties.uncheckedTemplate === 'undefined') { cellProperties.uncheckedTemplate = false; } dom.empty(TD); // TODO identify under what circumstances this line can be removed if (value === cellProperties.checkedTemplate || helper.equalsIgnoreCase(value, cellProperties.checkedTemplate)) { input.checked = true; TD.appendChild(input); } else if (value === cellProperties.uncheckedTemplate || helper.equalsIgnoreCase(value, cellProperties.uncheckedTemplate)) { TD.appendChild(input); } else if (value === null) { // default value dom.addClass(input, 'noValue'); TD.appendChild(input); } else { dom.fastInnerText(TD, '#bad value#'); } if (cellProperties.readOnly) { eventManager.addEventListener(input, 'click', preventDefault); } else { eventManager.addEventListener(input, 'mousedown', stopPropagation); eventManager.addEventListener(input, 'mouseup', stopPropagation); eventManager.addEventListener(input, 'change', (event) => { instance.setDataAtRowProp(row, prop, event.target.checked ? cellProperties.checkedTemplate : cellProperties.uncheckedTemplate); }); } if (!isListeningKeyDownEvent.has(instance)) { isListeningKeyDownEvent.set(instance, true); instance.addHook('beforeKeyDown', onBeforeKeyDown); } /** * On before key down DOM listener. * * @private * @param {Event} event */ function onBeforeKeyDown(event) { const allowedKeys = [ helper.keyCode.SPACE, helper.keyCode.ENTER, helper.keyCode.DELETE, helper.keyCode.BACKSPACE ]; dom.enableImmediatePropagation(event); if (allowedKeys.indexOf(event.keyCode) !== -1 && !event.isImmediatePropagationStopped()) { eachSelectedCheckboxCell(function() { event.stopImmediatePropagation(); event.preventDefault(); }); } if (event.keyCode == helper.keyCode.SPACE || event.keyCode == helper.keyCode.ENTER) { toggleSelected(); } if (event.keyCode == helper.keyCode.DELETE || event.keyCode == helper.keyCode.BACKSPACE) { toggleSelected(false); } } /** * Toggle checkbox checked property * * @private * @param {Boolean} [checked=null] */ function toggleSelected(checked = null) { eachSelectedCheckboxCell(function(checkboxes) { for (var i = 0, len = checkboxes.length; i < len; i++) { toggleCheckbox(checkboxes[i], checked); } }); } /** * Toggle checkbox element. * * @private * @param {HTMLInputElement} checkbox * @param {Boolean} [checked=null] */ function toggleCheckbox(checkbox, checked = null) { if (checked === null) { checkbox.checked = !checkbox.checked; } else { checkbox.checked = checked; } eventManager.fireEvent(checkbox, 'change'); } /** * Call callback for each found selected cell with checkbox type. * * @private * @param {Function} callback */ function eachSelectedCheckboxCell(callback) { const selRange = instance.getSelectedRange(); const topLeft = selRange.getTopLeftCorner(); const bottomRight = selRange.getBottomRightCorner(); for (let row = topLeft.row; row <= bottomRight.row; row++) { for (let col = topLeft.col; col <= bottomRight.col; col++) { let cell = instance.getCell(row, col); let cellProperties = instance.getCellMeta(row, col); let checkboxes = cell.querySelectorAll('input[type=checkbox]'); if (checkboxes.length > 0 && !cellProperties.readOnly) { callback(checkboxes); } } } } function preventDefault(event) { event.preventDefault(); } function stopPropagation(event) { helper.stopPropagation(event); } } export {checkboxRenderer}; registerRenderer('checkbox', checkboxRenderer);
/** * @license * Copyright 2014 David Wolverton * Available under MIT license <https://raw.githubusercontent.com/dwolverton/my/master/LICENSE.txt> */ define([ "dojo/store/Memory", "mytime/persistence/LocalStorage", "mytime/model/TimeEntry" ], function( Memory, LocalStorage, TimeEntry ) { describe("mytime/persistence/LocalStorage", function() { it("stores and retrieves an array of objects", function() { LocalStorage.persistStoreData("theKey", [ {id: "A", value: 1}, {id: "B", value: 2} ]); var retrieved = LocalStorage.retrieveStoreData("theKey"); expect(retrieved).to.deep.equal([ {id: "A", value: 1}, {id: "B", value: 2} ]); }); it("stores and retrieves an array of TimeEntries", function() { LocalStorage.persistStoreData("theKey", [ new TimeEntry({id: "A", startHour: 8}), new TimeEntry({id: "B", startHour: 10.5}) ]); var retrieved = LocalStorage.retrieveStoreData("theKey", TimeEntry); expect(retrieved).not.to.deep.equal([ {id: "A", startHour: 8}, {id: "B", startHour: 10.5} ]); expect(retrieved).to.deep.equal([ new TimeEntry({id: "A", startHour: 8}), new TimeEntry({id: "B", startHour: 10.5}) ]); expect(retrieved[0] instanceof TimeEntry).to.be.true; expect(retrieved[0]).to.have.property("id", "A"); expect(retrieved[0]).to.have.property("startHour", 8); expect(retrieved[0]).to.have.property("endHour", null); }); it("stores and retrieves a store", function() { var store = new Memory(); store.add({id: "A", value: 1}); store.add({id: "B", value: 2}); LocalStorage.persistStore("theKey", store); var retrieved = LocalStorage.loadStore("theKey", new Memory()); expect(retrieved.query()).to.have.property("total", 2); expect(retrieved.get("A")).to.deep.equal({id: "A", value: 1}); expect(retrieved.get("B")).to.deep.equal({id: "B", value: 2}); }); it("stores and retrieves a store or TimeEntries", function() { var store = new Memory(); store.add(new TimeEntry({id: "A", startHour: 8})); store.add(new TimeEntry({id: "B", startHour: 10.5})); LocalStorage.persistStore("theKey", store); var retrieved = LocalStorage.loadStore("theKey", new Memory(), TimeEntry); expect(retrieved.query()).to.have.property("total", 2); expect(retrieved.get("A") instanceof TimeEntry).to.be.true; }); }); });
/** * @class Keyboard * @classdesc Mixin which manages the keydown handling for a component * * TODO: Document collective behavior. * TODO: Provide baseline behavior outside of a collective. */ export default (base) => class Keyboard extends base { // Default keydown handler. This will typically be handled by other mixins. keydown(event) { if (super.keydown) { return super.keydown(event); } } /* * If we're now the outermost element of the collective, set up to receive * keyboard events. If we're no longer the outermost element, stop listening. */ collectiveChanged() { if (super.collectiveChanged) { super.collectiveChanged(); } if (this.collective.outermostElement !== this) { // We're no longer the outermost element; stop listening. if (isListeningToKeydown(this)) { stopListeningToKeydown(this); } return; } if (!this.getAttribute('aria-label')) { // Since we're going to handle the keyboard, see if we can adopt an ARIA // label from an inner element of the collective. let label = getCollectiveAriaLabel(this.collective); if (label) { this.setAttribute('aria-label', label); } } if (!isListeningToKeydown(this)) { startListeningToKeydown(this); } } }; function keydown(event) { // Give collective elements a shot at the event, working from innermost to // outermost (this element). let handled; let elements = this.collective.elements; for (let i = elements.length - 1; i >= 0; i--) { let element = elements[i]; handled = element.keydown && element.keydown(event); if (handled) { break; } } if (handled) { event.preventDefault(); event.stopPropagation(); } } // Return the first ARIA label defined by the collective. function getCollectiveAriaLabel(collective) { let labels = collective.elements.map(element => element.getAttribute('aria-label')); // Would prefer to use Array.prototype.find here, but IE 11 doesn't have it. let nonNullLabels = labels.filter(label => label != null); return nonNullLabels[0]; } function isListeningToKeydown(element) { return element._keydownListener != null; } function startListeningToKeydown(element) { element._keydownListener = keydown.bind(element); element.addEventListener('keydown', element._keydownListener); // Set a default tab index of 0 (document order) if no tab index exists. // MS Edge requires we explicitly check for presence of tabindex attribute. if (element.getAttribute('tabindex') == null || element.tabIndex < 0) { element.setAttribute('tabindex', '0'); } } function stopListeningToKeydown(element) { element.removeEventListener('keydown', element._keydownListener); element._keydownListener = null; element.removeAttribute('tabindex'); }
const amino = require('../main.js'); const gfx = new amino.AminoGfx(); gfx.start(function (err) { if (err) { console.log('Start failed: ' + err.message); return; } //size (100x100) this.w(100); this.h(100); //see opacity.js //root const root = this.createGroup(); this.setRoot(root); //rect const rect = this.createRect().fill('#00ff00').opacity(1.0); root.add(rect); rect.opacity.anim().from(1.0).to(0.0).dur(1000).loop(-1).start(); //text const text = this.createText().fill('#ff0000').opacity(1.0).x(100).y(200); text.text('Sample Text'); text.opacity.anim().from(0.0).to(1.0).dur(1000).loop(-1).start(); root.add(text); //circle const circle = this.createCircle().radius(50) .fill('#0000ff').filled(true) .opacity(0.5) .x(200).y(50); root.add(circle); });
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import { Provider } from 'react-redux'; import store from './store' ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') );
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = global || self, factory(global.au = {})); }(this, function (exports) { 'use strict'; function AggregateError(message, innerError, skipIfAlreadyAggregate) { if (innerError) { if (innerError.innerError && skipIfAlreadyAggregate) { return innerError; } const separator = '\n------------------------------------------------\n'; message += `${separator}Inner Error:\n`; if (typeof innerError === 'string') { message += `Message: ${innerError}`; } else { if (innerError.message) { message += `Message: ${innerError.message}`; } else { message += `Unknown Inner Error Type. Displaying Inner Error as JSON:\n ${JSON.stringify(innerError, null, ' ')}`; } if (innerError.stack) { message += `\nInner Error Stack:\n${innerError.stack}`; message += '\nEnd Inner Error Stack'; } } message += separator; } let e = new Error(message); if (innerError) { e.innerError = innerError; } return e; } const FEATURE = {}; const PLATFORM = { noop() {}, eachModule() {}, moduleName(moduleName) { return moduleName; } }; PLATFORM.global = function () { if (typeof self !== 'undefined') { return self; } if (typeof global !== 'undefined') { return global; } return new Function('return this')(); }(); const DOM = {}; exports.isInitialized = false; function initializePAL(callback) { if (exports.isInitialized) { return; } exports.isInitialized = true; if (typeof Object.getPropertyDescriptor !== 'function') { Object.getPropertyDescriptor = function (subject, name) { let pd = Object.getOwnPropertyDescriptor(subject, name); let proto = Object.getPrototypeOf(subject); while (typeof pd === 'undefined' && proto !== null) { pd = Object.getOwnPropertyDescriptor(proto, name); proto = Object.getPrototypeOf(proto); } return pd; }; } callback(PLATFORM, FEATURE, DOM); } function reset() { exports.isInitialized = false; } if (!String.prototype.endsWith || function () { try { return !"ab".endsWith("a", 1); } catch (e) { return true; } }()) { String.prototype.endsWith = function (searchString, position) { var subjectString = this.toString(); if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) { position = subjectString.length; } position -= searchString.length; var lastIndex = subjectString.indexOf(searchString, position); return lastIndex !== -1 && lastIndex === position; }; } if (!String.prototype.startsWith || function () { try { return !"ab".startsWith("b", 1); } catch (e) { return true; } }()) { String.prototype.startsWith = function (searchString, position) { position = position || 0; return this.substr(position, searchString.length) === searchString; }; } { var emptyMetadata = Object.freeze({}); var metadataContainerKey = '__metadata__'; if (typeof Reflect.getOwnMetadata !== 'function') { Reflect.getOwnMetadata = function (metadataKey, target, targetKey) { if (target.hasOwnProperty(metadataContainerKey)) { return (target[metadataContainerKey][targetKey] || emptyMetadata)[metadataKey]; } }; } if (typeof Reflect.defineMetadata !== 'function') { Reflect.defineMetadata = function (metadataKey, metadataValue, target, targetKey) { var metadataContainer = target.hasOwnProperty(metadataContainerKey) ? target[metadataContainerKey] : target[metadataContainerKey] = {}; var targetContainer = metadataContainer[targetKey] || (metadataContainer[targetKey] = {}); targetContainer[metadataKey] = metadataValue; }; } if (typeof Reflect.metadata !== 'function') { Reflect.metadata = function (metadataKey, metadataValue) { return function (target, targetKey) { Reflect.defineMetadata(metadataKey, metadataValue, target, targetKey); }; }; } } const _PLATFORM = { location: window.location, history: window.history, addEventListener(eventName, callback, capture) { this.global.addEventListener(eventName, callback, capture); }, removeEventListener(eventName, callback, capture) { this.global.removeEventListener(eventName, callback, capture); }, performance: window.performance, requestAnimationFrame(callback) { return this.global.requestAnimationFrame(callback); } }; if (Element && !Element.prototype.matches) { let proto = Element.prototype; proto.matches = proto.matchesSelector || proto.mozMatchesSelector || proto.msMatchesSelector || proto.oMatchesSelector || proto.webkitMatchesSelector; } const _FEATURE = { shadowDOM: !!HTMLElement.prototype.attachShadow, scopedCSS: 'scoped' in document.createElement('style'), htmlTemplateElement: function () { let d = document.createElement('div'); d.innerHTML = '<template></template>'; return 'content' in d.children[0]; }(), mutationObserver: !!(window.MutationObserver || window.WebKitMutationObserver), ensureHTMLTemplateElement: t => t }; let shadowPoly = window.ShadowDOMPolyfill || null; const _DOM = { Element: Element, NodeList: NodeList, SVGElement: SVGElement, boundary: 'aurelia-dom-boundary', addEventListener(eventName, callback, capture) { document.addEventListener(eventName, callback, capture); }, removeEventListener(eventName, callback, capture) { document.removeEventListener(eventName, callback, capture); }, adoptNode(node) { return document.adoptNode(node); }, createAttribute(name) { return document.createAttribute(name); }, createElement(tagName) { return document.createElement(tagName); }, createTextNode(text) { return document.createTextNode(text); }, createComment(text) { return document.createComment(text); }, createDocumentFragment() { return document.createDocumentFragment(); }, createTemplateElement() { let template = document.createElement('template'); return _FEATURE.ensureHTMLTemplateElement(template); }, createMutationObserver(callback) { return new (window.MutationObserver || window.WebKitMutationObserver)(callback); }, createCustomEvent(eventType, options) { return new window.CustomEvent(eventType, options); }, dispatchEvent(evt) { document.dispatchEvent(evt); }, getComputedStyle(element) { return window.getComputedStyle(element); }, getElementById(id) { return document.getElementById(id); }, querySelector(query) { return document.querySelector(query); }, querySelectorAll(query) { return document.querySelectorAll(query); }, nextElementSibling(element) { if (element.nextElementSibling) { return element.nextElementSibling; } do { element = element.nextSibling; } while (element && element.nodeType !== 1); return element; }, createTemplateFromMarkup(markup) { let parser = document.createElement('div'); parser.innerHTML = markup; let temp = parser.firstElementChild; if (!temp || temp.nodeName !== 'TEMPLATE') { throw new Error('Template markup must be wrapped in a <template> element e.g. <template> <!-- markup here --> </template>'); } return _FEATURE.ensureHTMLTemplateElement(temp); }, appendNode(newNode, parentNode) { (parentNode || document.body).appendChild(newNode); }, replaceNode(newNode, node, parentNode) { if (node.parentNode) { node.parentNode.replaceChild(newNode, node); } else if (shadowPoly !== null) { shadowPoly.unwrap(parentNode).replaceChild(shadowPoly.unwrap(newNode), shadowPoly.unwrap(node)); } else { parentNode.replaceChild(newNode, node); } }, removeNode(node, parentNode) { if (node.parentNode) { node.parentNode.removeChild(node); } else if (parentNode) { if (shadowPoly !== null) { shadowPoly.unwrap(parentNode).removeChild(shadowPoly.unwrap(node)); } else { parentNode.removeChild(node); } } }, injectStyles(styles, destination, prepend, id) { if (id) { let oldStyle = document.getElementById(id); if (oldStyle) { let isStyleTag = oldStyle.tagName.toLowerCase() === 'style'; if (isStyleTag) { oldStyle.innerHTML = styles; return; } throw new Error('The provided id does not indicate a style tag.'); } } let node = document.createElement('style'); node.innerHTML = styles; node.type = 'text/css'; if (id) { node.id = id; } destination = destination || document.head; if (prepend && destination.childNodes.length > 0) { destination.insertBefore(node, destination.childNodes[0]); } else { destination.appendChild(node); } return node; } }; function initialize() { if (exports.isInitialized) { return; } initializePAL((platform, feature, dom) => { Object.assign(platform, _PLATFORM); Object.assign(feature, _FEATURE); Object.assign(dom, _DOM); Object.defineProperty(dom, 'title', { get: () => document.title, set: value => { document.title = value; } }); Object.defineProperty(dom, 'activeElement', { get: () => document.activeElement }); Object.defineProperty(platform, 'XMLHttpRequest', { get: () => platform.global.XMLHttpRequest }); }); } var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function isObject(val) { return val && (typeof val === 'function' || typeof val === 'object'); } const metadata = { resource: 'aurelia:resource', paramTypes: 'design:paramtypes', propertyType: 'design:type', properties: 'design:properties', get(metadataKey, target, targetKey) { if (!isObject(target)) { return undefined; } let result = metadata.getOwn(metadataKey, target, targetKey); return result === undefined ? metadata.get(metadataKey, Object.getPrototypeOf(target), targetKey) : result; }, getOwn(metadataKey, target, targetKey) { if (!isObject(target)) { return undefined; } return Reflect.getOwnMetadata(metadataKey, target, targetKey); }, define(metadataKey, metadataValue, target, targetKey) { Reflect.defineMetadata(metadataKey, metadataValue, target, targetKey); }, getOrCreateOwn(metadataKey, Type, target, targetKey) { let result = metadata.getOwn(metadataKey, target, targetKey); if (result === undefined) { result = new Type(); Reflect.defineMetadata(metadataKey, result, target, targetKey); } return result; } }; const originStorage = new Map(); const unknownOrigin = Object.freeze({ moduleId: undefined, moduleMember: undefined }); let Origin = class Origin { constructor(moduleId, moduleMember) { this.moduleId = moduleId; this.moduleMember = moduleMember; } static get(fn) { let origin = originStorage.get(fn); if (origin === undefined) { PLATFORM.eachModule((key, value) => { if (typeof value === 'object') { for (let name in value) { try { let exp = value[name]; if (exp === fn) { originStorage.set(fn, origin = new Origin(key, name)); return true; } } catch (e) {} } } if (value === fn) { originStorage.set(fn, origin = new Origin(key, 'default')); return true; } return false; }); } return origin || unknownOrigin; } static set(fn, origin) { originStorage.set(fn, origin); } }; function decorators(...rest) { let applicator = function (target, key, descriptor) { let i = rest.length; if (key) { descriptor = descriptor || { value: target[key], writable: true, configurable: true, enumerable: true }; while (i--) { descriptor = rest[i](target, key, descriptor) || descriptor; } Object.defineProperty(target, key, descriptor); } else { while (i--) { target = rest[i](target) || target; } } return target; }; applicator.on = applicator; return applicator; } function deprecated(optionsOrTarget, maybeKey, maybeDescriptor) { function decorator(target, key, descriptor) { const methodSignature = `${target.constructor.name}#${key}`; let options = maybeKey ? {} : optionsOrTarget || {}; let message = `DEPRECATION - ${methodSignature}`; if (typeof descriptor.value !== 'function') { throw new SyntaxError('Only methods can be marked as deprecated.'); } if (options.message) { message += ` - ${options.message}`; } return _extends({}, descriptor, { value: function deprecationWrapper() { if (options.error) { throw new Error(message); } else { console.warn(message); } return descriptor.value.apply(this, arguments); } }); } return maybeKey ? decorator(optionsOrTarget, maybeKey, maybeDescriptor) : decorator; } function mixin(behavior) { const instanceKeys = Object.keys(behavior); function _mixin(possible) { let decorator = function (target) { let resolvedTarget = typeof target === 'function' ? target.prototype : target; let i = instanceKeys.length; while (i--) { let property = instanceKeys[i]; Object.defineProperty(resolvedTarget, property, { value: behavior[property], writable: true }); } }; return possible ? decorator(possible) : decorator; } return _mixin; } function alwaysValid() { return true; } function noCompose() {} function ensureProtocolOptions(options) { if (options === undefined) { options = {}; } else if (typeof options === 'function') { options = { validate: options }; } if (!options.validate) { options.validate = alwaysValid; } if (!options.compose) { options.compose = noCompose; } return options; } function createProtocolValidator(validate) { return function (target) { let result = validate(target); return result === true; }; } function createProtocolAsserter(name, validate) { return function (target) { let result = validate(target); if (result !== true) { throw new Error(result || `${name} was not correctly implemented.`); } }; } function protocol(name, options) { options = ensureProtocolOptions(options); let result = function (target) { let resolvedTarget = typeof target === 'function' ? target.prototype : target; options.compose(resolvedTarget); result.assert(resolvedTarget); Object.defineProperty(resolvedTarget, 'protocol:' + name, { enumerable: false, configurable: false, writable: false, value: true }); }; result.validate = createProtocolValidator(options.validate); result.assert = createProtocolAsserter(name, options.validate); return result; } protocol.create = function (name, options) { options = ensureProtocolOptions(options); let hidden = 'protocol:' + name; let result = function (target) { let decorator = protocol(name, options); return target ? decorator(target) : decorator; }; result.decorates = function (obj) { return obj[hidden] === true; }; result.validate = createProtocolValidator(options.validate); result.assert = createProtocolAsserter(name, options.validate); return result; }; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; function trimDots(ary) { for (var i = 0; i < ary.length; ++i) { var part = ary[i]; if (part === '.') { ary.splice(i, 1); i -= 1; } else if (part === '..') { if (i === 0 || i === 1 && ary[2] === '..' || ary[i - 1] === '..') { continue; } else if (i > 0) { ary.splice(i - 1, 2); i -= 2; } } } } function relativeToFile(name, file) { var fileParts = file && file.split('/'); var nameParts = name.trim().split('/'); if (nameParts[0].charAt(0) === '.' && fileParts) { var normalizedBaseParts = fileParts.slice(0, fileParts.length - 1); nameParts.unshift.apply(nameParts, normalizedBaseParts); } trimDots(nameParts); return nameParts.join('/'); } function join(path1, path2) { if (!path1) { return path2; } if (!path2) { return path1; } var schemeMatch = path1.match(/^([^/]*?:)\//); var scheme = schemeMatch && schemeMatch.length > 0 ? schemeMatch[1] : ''; path1 = path1.substr(scheme.length); var urlPrefix = void 0; if (path1.indexOf('///') === 0 && scheme === 'file:') { urlPrefix = '///'; } else if (path1.indexOf('//') === 0) { urlPrefix = '//'; } else if (path1.indexOf('/') === 0) { urlPrefix = '/'; } else { urlPrefix = ''; } var trailingSlash = path2.slice(-1) === '/' ? '/' : ''; var url1 = path1.split('/'); var url2 = path2.split('/'); var url3 = []; for (var i = 0, ii = url1.length; i < ii; ++i) { if (url1[i] === '..') { url3.pop(); } else if (url1[i] === '.' || url1[i] === '') { continue; } else { url3.push(url1[i]); } } for (var _i = 0, _ii = url2.length; _i < _ii; ++_i) { if (url2[_i] === '..') { url3.pop(); } else if (url2[_i] === '.' || url2[_i] === '') { continue; } else { url3.push(url2[_i]); } } return scheme + urlPrefix + url3.join('/') + trailingSlash; } var encode = encodeURIComponent; var encodeKey = function encodeKey(k) { return encode(k).replace('%24', '$'); }; function buildParam(key, value, traditional) { var result = []; if (value === null || value === undefined) { return result; } if (Array.isArray(value)) { for (var i = 0, l = value.length; i < l; i++) { if (traditional) { result.push(encodeKey(key) + '=' + encode(value[i])); } else { var arrayKey = key + '[' + (_typeof(value[i]) === 'object' && value[i] !== null ? i : '') + ']'; result = result.concat(buildParam(arrayKey, value[i])); } } } else if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && !traditional) { for (var propertyName in value) { result = result.concat(buildParam(key + '[' + propertyName + ']', value[propertyName])); } } else { result.push(encodeKey(key) + '=' + encode(value)); } return result; } function buildQueryString(params, traditional) { var pairs = []; var keys = Object.keys(params || {}).sort(); for (var i = 0, len = keys.length; i < len; i++) { var key = keys[i]; pairs = pairs.concat(buildParam(key, params[key], traditional)); } if (pairs.length === 0) { return ''; } return pairs.join('&'); } function processScalarParam(existedParam, value) { if (Array.isArray(existedParam)) { existedParam.push(value); return existedParam; } if (existedParam !== undefined) { return [existedParam, value]; } return value; } function parseComplexParam(queryParams, keys, value) { var currentParams = queryParams; var keysLastIndex = keys.length - 1; for (var j = 0; j <= keysLastIndex; j++) { var key = keys[j] === '' ? currentParams.length : keys[j]; if (j < keysLastIndex) { var prevValue = !currentParams[key] || _typeof(currentParams[key]) === 'object' ? currentParams[key] : [currentParams[key]]; currentParams = currentParams[key] = prevValue || (isNaN(keys[j + 1]) ? {} : []); } else { currentParams = currentParams[key] = value; } } } function parseQueryString(queryString) { var queryParams = {}; if (!queryString || typeof queryString !== 'string') { return queryParams; } var query = queryString; if (query.charAt(0) === '?') { query = query.substr(1); } var pairs = query.replace(/\+/g, ' ').split('&'); for (var i = 0; i < pairs.length; i++) { var pair = pairs[i].split('='); var key = decodeURIComponent(pair[0]); if (!key) { continue; } var keys = key.split(']['); var keysLastIndex = keys.length - 1; if (/\[/.test(keys[0]) && /\]$/.test(keys[keysLastIndex])) { keys[keysLastIndex] = keys[keysLastIndex].replace(/\]$/, ''); keys = keys.shift().split('[').concat(keys); keysLastIndex = keys.length - 1; } else { keysLastIndex = 0; } if (pair.length >= 2) { var value = pair[1] ? decodeURIComponent(pair[1]) : ''; if (keysLastIndex) { parseComplexParam(queryParams, keys, value); } else { queryParams[key] = processScalarParam(queryParams[key], value); } } else { queryParams[key] = true; } } return queryParams; } let TemplateDependency = class TemplateDependency { constructor(src, name) { this.src = src; this.name = name; } }; let TemplateRegistryEntry = class TemplateRegistryEntry { constructor(address) { this.templateIsLoaded = false; this.factoryIsReady = false; this.resources = null; this.dependencies = null; this.address = address; this.onReady = null; this._template = null; this._factory = null; } get template() { return this._template; } set template(value) { let address = this.address; let requires; let current; let src; let dependencies; this._template = value; this.templateIsLoaded = true; requires = value.content.querySelectorAll('require'); dependencies = this.dependencies = new Array(requires.length); for (let i = 0, ii = requires.length; i < ii; ++i) { current = requires[i]; src = current.getAttribute('from'); if (!src) { throw new Error(`<require> element in ${address} has no "from" attribute.`); } dependencies[i] = new TemplateDependency(relativeToFile(src, address), current.getAttribute('as')); if (current.parentNode) { current.parentNode.removeChild(current); } } } get factory() { return this._factory; } set factory(value) { this._factory = value; this.factoryIsReady = true; } addDependency(src, name) { let finalSrc = typeof src === 'string' ? relativeToFile(src, this.address) : Origin.get(src).moduleId; this.dependencies.push(new TemplateDependency(finalSrc, name)); } }; let Loader = class Loader { constructor() { this.templateRegistry = {}; } map(id, source) { throw new Error('Loaders must implement map(id, source).'); } normalizeSync(moduleId, relativeTo) { throw new Error('Loaders must implement normalizeSync(moduleId, relativeTo).'); } normalize(moduleId, relativeTo) { throw new Error('Loaders must implement normalize(moduleId: string, relativeTo: string): Promise<string>.'); } loadModule(id) { throw new Error('Loaders must implement loadModule(id).'); } loadAllModules(ids) { throw new Error('Loader must implement loadAllModules(ids).'); } loadTemplate(url) { throw new Error('Loader must implement loadTemplate(url).'); } loadText(url) { throw new Error('Loader must implement loadText(url).'); } applyPluginToUrl(url, pluginName) { throw new Error('Loader must implement applyPluginToUrl(url, pluginName).'); } addPlugin(pluginName, implementation) { throw new Error('Loader must implement addPlugin(pluginName, implementation).'); } getOrCreateTemplateRegistryEntry(address) { return this.templateRegistry[address] || (this.templateRegistry[address] = new TemplateRegistryEntry(address)); } }; /** * An implementation of the TemplateLoader interface implemented with text-based loading. */ class TextTemplateLoader { /** * Loads a template. * @param loader The loader that is requesting the template load. * @param entry The TemplateRegistryEntry to load and populate with a template. * @return A promise which resolves when the TemplateRegistryEntry is loaded with a template. */ async loadTemplate(loader, entry) { const text = await loader.loadText(entry.address); entry.template = DOM.createTemplateFromMarkup(text); } } function ensureOriginOnExports(moduleExports, moduleId) { let target = moduleExports; let key; let exportedValue; // Mark the module with Origin // for view mapping from loader Origin.set(target, new Origin(moduleId, '')); if (typeof target === 'object') { for (key in target) { exportedValue = target[key]; if (typeof exportedValue === 'function') { Origin.set(exportedValue, new Origin(moduleId, key)); } } } return moduleExports; } /** * A default implementation of the Loader abstraction which works with webpack (extended common-js style). */ class EsmLoader extends Loader { constructor() { super(); this.moduleRegistry = Object.create(null); this.loaderPlugins = Object.create(null); this.modulesBeingLoaded = new Map(); this.baseUrl = location.origin || `${location.protocol}//${location.hostname}${location.port ? `:${location.port}` : ''}`; this.useTemplateLoader(new TextTemplateLoader()); this.addPlugin('template-registry-entry', { fetch: async (moduleId) => { const entry = this.getOrCreateTemplateRegistryEntry(moduleId); if (!entry.templateIsLoaded) { await this.templateLoader.loadTemplate(this, entry); } return entry; } }); PLATFORM.eachModule = callback => { const registry = this.moduleRegistry; const cachedModuleIds = Object.getOwnPropertyNames(registry); cachedModuleIds // Note: we use .some here like a .forEach that can be "break"ed out of. // It will stop iterating only when a truthy value is returned. // Even though the docs say "true" explicitly, loader-default also goes by truthy // and this is to keep it consistent with that. .some(moduleId => { const moduleExports = registry[moduleId].exports; if (typeof moduleExports === 'object') { return callback(moduleId, moduleExports); } return false; }); }; } /** * @internal */ async _import(address) { const addressParts = address.split('!'); const moduleId = addressParts.splice(addressParts.length - 1, 1)[0]; const loaderPlugin = addressParts.length === 1 ? addressParts[0] : null; if (loaderPlugin) { const plugin = this.loaderPlugins[loaderPlugin]; if (!plugin) { throw new Error(`Plugin ${loaderPlugin} is not registered in the loader.`); } return await plugin.fetch(moduleId); } return import(join(this.baseUrl, moduleId)).then(m => { this.moduleRegistry[moduleId] = m; return m; }); } /** * Maps a module id to a source. * @param id The module id. * @param source The source to map the module to. */ map(id, source) { } /** * Normalizes a module id. * @param moduleId The module id to normalize. * @param relativeTo What the module id should be normalized relative to. * @return The normalized module id. */ normalizeSync(moduleId, relativeTo) { return moduleId; } /** * Normalizes a module id. * @param moduleId The module id to normalize. * @param relativeTo What the module id should be normalized relative to. * @return The normalized module id. */ normalize(moduleId, relativeTo) { return Promise.resolve(moduleId); } /** * Instructs the loader to use a specific TemplateLoader instance for loading templates * @param templateLoader The instance of TemplateLoader to use for loading templates. */ useTemplateLoader(templateLoader) { this.templateLoader = templateLoader; } /** * Loads a collection of modules. * @param ids The set of module ids to load. * @return A Promise for an array of loaded modules. */ loadAllModules(ids) { return Promise.all(ids.map(id => this.loadModule(id))); } /** * Loads a module. * @param moduleId The module ID to load. * @return A Promise for the loaded module. */ async loadModule(moduleId) { let existing = this.moduleRegistry[moduleId]; if (existing) { return existing; } let beingLoaded = this.modulesBeingLoaded.get(moduleId); if (beingLoaded) { return beingLoaded; } beingLoaded = this._import(moduleId); this.modulesBeingLoaded.set(moduleId, beingLoaded); const moduleExports = await beingLoaded; this.moduleRegistry[moduleId] = ensureOriginOnExports(moduleExports, moduleId); this.modulesBeingLoaded.delete(moduleId); return moduleExports; } /** * Loads a template. * @param url The url of the template to load. * @return A Promise for a TemplateRegistryEntry containing the template. */ loadTemplate(url) { return this.loadModule(this.applyPluginToUrl(url, 'template-registry-entry')); } /** * Loads a text-based resource. * @param url The url of the text file to load. * @return A Promise for text content. */ async loadText(url) { return fetch(url).then(res => res.text()); } /** * Alters a module id so that it includes a plugin loader. * @param url The url of the module to load. * @param pluginName The plugin to apply to the module id. * @return The plugin-based module id. */ applyPluginToUrl(url, pluginName) { return `${pluginName}!${url}`; } /** * Registers a plugin with the loader. * @param pluginName The name of the plugin. * @param implementation The plugin implementation. */ addPlugin(pluginName, implementation) { this.loaderPlugins[pluginName] = implementation; } } PLATFORM.Loader = EsmLoader; const logLevel = { none: 0, error: 10, warn: 20, info: 30, debug: 40 }; let loggers = {}; let appenders = []; let globalDefaultLevel = logLevel.none; const standardLevels = ['none', 'error', 'warn', 'info', 'debug']; function isStandardLevel(level) { return standardLevels.filter(l => l === level).length > 0; } function appendArgs() { return [this, ...arguments]; } function logFactory(level) { const threshold = logLevel[level]; return function () { if (this.level < threshold) { return; } const args = appendArgs.apply(this, arguments); let i = appenders.length; while (i--) { appenders[i][level](...args); } }; } function logFactoryCustom(level) { const threshold = logLevel[level]; return function () { if (this.level < threshold) { return; } const args = appendArgs.apply(this, arguments); let i = appenders.length; while (i--) { const appender = appenders[i]; if (appender[level] !== undefined) { appender[level](...args); } } }; } function connectLoggers() { let proto = Logger.prototype; for (let level in logLevel) { if (isStandardLevel(level)) { if (level !== 'none') { proto[level] = logFactory(level); } } else { proto[level] = logFactoryCustom(level); } } } function disconnectLoggers() { let proto = Logger.prototype; for (let level in logLevel) { if (level !== 'none') { proto[level] = function () {}; } } } function getLogger(id) { return loggers[id] || new Logger(id); } function addAppender(appender) { if (appenders.push(appender) === 1) { connectLoggers(); } } function removeAppender(appender) { appenders = appenders.filter(a => a !== appender); } function getAppenders() { return [...appenders]; } function clearAppenders() { appenders = []; disconnectLoggers(); } function addCustomLevel(name, value) { if (logLevel[name] !== undefined) { throw Error(`Log level "${name}" already exists.`); } if (isNaN(value)) { throw Error('Value must be a number.'); } logLevel[name] = value; if (appenders.length > 0) { connectLoggers(); } else { Logger.prototype[name] = function () {}; } } function removeCustomLevel(name) { if (logLevel[name] === undefined) { return; } if (isStandardLevel(name)) { throw Error(`Built-in log level "${name}" cannot be removed.`); } delete logLevel[name]; delete Logger.prototype[name]; } function setLevel(level) { globalDefaultLevel = level; for (let key in loggers) { loggers[key].setLevel(level); } } function getLevel() { return globalDefaultLevel; } let Logger = class Logger { constructor(id) { let cached = loggers[id]; if (cached) { return cached; } loggers[id] = this; this.id = id; this.level = globalDefaultLevel; } debug(message, ...rest) {} info(message, ...rest) {} warn(message, ...rest) {} error(message, ...rest) {} setLevel(level) { this.level = level; } isDebugEnabled() { return this.level === logLevel.debug; } }; var TheLogManager = /*#__PURE__*/Object.freeze({ logLevel: logLevel, getLogger: getLogger, addAppender: addAppender, removeAppender: removeAppender, getAppenders: getAppenders, clearAppenders: clearAppenders, addCustomLevel: addCustomLevel, removeCustomLevel: removeCustomLevel, setLevel: setLevel, getLevel: getLevel, Logger: Logger }); var _dec, _class, _dec2, _class2, _dec3, _class3, _dec4, _class4, _dec5, _class5, _dec6, _class6, _dec7, _class7; const resolver = protocol.create('aurelia:resolver', function (target) { if (!(typeof target.get === 'function')) { return 'Resolvers must implement: get(container: Container, key: any): any'; } return true; }); let StrategyResolver = (_dec = resolver(), _dec(_class = class StrategyResolver { constructor(strategy, state) { this.strategy = strategy; this.state = state; } get(container, key) { switch (this.strategy) { case 0: return this.state; case 1: let singleton = container.invoke(this.state); this.state = singleton; this.strategy = 0; return singleton; case 2: return container.invoke(this.state); case 3: return this.state(container, key, this); case 4: return this.state[0].get(container, key); case 5: return container.get(this.state); default: throw new Error('Invalid strategy: ' + this.strategy); } } }) || _class); let Lazy = (_dec2 = resolver(), _dec2(_class2 = class Lazy { constructor(key) { this._key = key; } get(container) { return () => container.get(this._key); } static of(key) { return new Lazy(key); } }) || _class2); let All = (_dec3 = resolver(), _dec3(_class3 = class All { constructor(key) { this._key = key; } get(container) { return container.getAll(this._key); } static of(key) { return new All(key); } }) || _class3); let Optional = (_dec4 = resolver(), _dec4(_class4 = class Optional { constructor(key, checkParent = true) { this._key = key; this._checkParent = checkParent; } get(container) { if (container.hasResolver(this._key, this._checkParent)) { return container.get(this._key); } return null; } static of(key, checkParent = true) { return new Optional(key, checkParent); } }) || _class4); let Parent = (_dec5 = resolver(), _dec5(_class5 = class Parent { constructor(key) { this._key = key; } get(container) { return container.parent ? container.parent.get(this._key) : null; } static of(key) { return new Parent(key); } }) || _class5); let Factory = (_dec6 = resolver(), _dec6(_class6 = class Factory { constructor(key) { this._key = key; } get(container) { let fn = this._key; let resolver = container.getResolver(fn); if (resolver && resolver.strategy === 3) { fn = resolver.state; } return (...rest) => container.invoke(fn, rest); } static of(key) { return new Factory(key); } }) || _class6); let NewInstance = (_dec7 = resolver(), _dec7(_class7 = class NewInstance { constructor(key, ...dynamicDependencies) { this.key = key; this.asKey = key; this.dynamicDependencies = dynamicDependencies; } get(container) { let dynamicDependencies = this.dynamicDependencies.length > 0 ? this.dynamicDependencies.map(dependency => dependency['protocol:aurelia:resolver'] ? dependency.get(container) : container.get(dependency)) : undefined; let fn = this.key; let resolver = container.getResolver(fn); if (resolver && resolver.strategy === 3) { fn = resolver.state; } const instance = container.invoke(fn, dynamicDependencies); container.registerInstance(this.asKey, instance); return instance; } as(key) { this.asKey = key; return this; } static of(key, ...dynamicDependencies) { return new NewInstance(key, ...dynamicDependencies); } }) || _class7); function getDecoratorDependencies(target) { autoinject(target); return target.inject; } function lazy(keyValue) { return function (target, key, index) { let inject = getDecoratorDependencies(target); inject[index] = Lazy.of(keyValue); }; } function all(keyValue) { return function (target, key, index) { let inject = getDecoratorDependencies(target); inject[index] = All.of(keyValue); }; } function optional(checkParentOrTarget = true) { let deco = function (checkParent) { return function (target, key, index) { let inject = getDecoratorDependencies(target); inject[index] = Optional.of(inject[index], checkParent); }; }; if (typeof checkParentOrTarget === 'boolean') { return deco(checkParentOrTarget); } return deco(true); } function parent(target, key, index) { let inject = getDecoratorDependencies(target); inject[index] = Parent.of(inject[index]); } function factory(keyValue) { return function (target, key, index) { let inject = getDecoratorDependencies(target); inject[index] = Factory.of(keyValue); }; } function newInstance(asKeyOrTarget, ...dynamicDependencies) { let deco = function (asKey) { return function (target, key, index) { let inject = getDecoratorDependencies(target); inject[index] = NewInstance.of(inject[index], ...dynamicDependencies); if (!!asKey) { inject[index].as(asKey); } }; }; if (arguments.length >= 1) { return deco(asKeyOrTarget); } return deco(); } function invoker(value) { return function (target) { metadata.define(metadata.invoker, value, target); }; } function invokeAsFactory(potentialTarget) { let deco = function (target) { metadata.define(metadata.invoker, FactoryInvoker.instance, target); }; return potentialTarget ? deco(potentialTarget) : deco; } let FactoryInvoker = class FactoryInvoker { invoke(container, fn, dependencies) { let i = dependencies.length; let args = new Array(i); while (i--) { args[i] = container.get(dependencies[i]); } return fn.apply(undefined, args); } invokeWithDynamicDependencies(container, fn, staticDependencies, dynamicDependencies) { let i = staticDependencies.length; let args = new Array(i); while (i--) { args[i] = container.get(staticDependencies[i]); } if (dynamicDependencies !== undefined) { args = args.concat(dynamicDependencies); } return fn.apply(undefined, args); } }; FactoryInvoker.instance = new FactoryInvoker(); function registration(value) { return function (target) { metadata.define(metadata.registration, value, target); }; } function transient(key) { return registration(new TransientRegistration(key)); } function singleton(keyOrRegisterInChild, registerInChild = false) { return registration(new SingletonRegistration(keyOrRegisterInChild, registerInChild)); } let TransientRegistration = class TransientRegistration { constructor(key) { this._key = key; } registerResolver(container, key, fn) { let existingResolver = container.getResolver(this._key || key); return existingResolver === undefined ? container.registerTransient(this._key || key, fn) : existingResolver; } }; let SingletonRegistration = class SingletonRegistration { constructor(keyOrRegisterInChild, registerInChild = false) { if (typeof keyOrRegisterInChild === 'boolean') { this._registerInChild = keyOrRegisterInChild; } else { this._key = keyOrRegisterInChild; this._registerInChild = registerInChild; } } registerResolver(container, key, fn) { let targetContainer = this._registerInChild ? container : container.root; let existingResolver = targetContainer.getResolver(this._key || key); return existingResolver === undefined ? targetContainer.registerSingleton(this._key || key, fn) : existingResolver; } }; function validateKey(key) { if (key === null || key === undefined) { throw new Error('key/value cannot be null or undefined. Are you trying to inject/register something that doesn\'t exist with DI?'); } } const _emptyParameters = Object.freeze([]); metadata.registration = 'aurelia:registration'; metadata.invoker = 'aurelia:invoker'; let resolverDecorates = resolver.decorates; let InvocationHandler = class InvocationHandler { constructor(fn, invoker, dependencies) { this.fn = fn; this.invoker = invoker; this.dependencies = dependencies; } invoke(container, dynamicDependencies) { return dynamicDependencies !== undefined ? this.invoker.invokeWithDynamicDependencies(container, this.fn, this.dependencies, dynamicDependencies) : this.invoker.invoke(container, this.fn, this.dependencies); } }; function invokeWithDynamicDependencies(container, fn, staticDependencies, dynamicDependencies) { let i = staticDependencies.length; let args = new Array(i); let lookup; while (i--) { lookup = staticDependencies[i]; if (lookup === null || lookup === undefined) { throw new Error('Constructor Parameter with index ' + i + ' cannot be null or undefined. Are you trying to inject/register something that doesn\'t exist with DI?'); } else { args[i] = container.get(lookup); } } if (dynamicDependencies !== undefined) { args = args.concat(dynamicDependencies); } return Reflect.construct(fn, args); } let classInvokers = { [0]: { invoke(container, Type) { return new Type(); }, invokeWithDynamicDependencies: invokeWithDynamicDependencies }, [1]: { invoke(container, Type, deps) { return new Type(container.get(deps[0])); }, invokeWithDynamicDependencies: invokeWithDynamicDependencies }, [2]: { invoke(container, Type, deps) { return new Type(container.get(deps[0]), container.get(deps[1])); }, invokeWithDynamicDependencies: invokeWithDynamicDependencies }, [3]: { invoke(container, Type, deps) { return new Type(container.get(deps[0]), container.get(deps[1]), container.get(deps[2])); }, invokeWithDynamicDependencies: invokeWithDynamicDependencies }, [4]: { invoke(container, Type, deps) { return new Type(container.get(deps[0]), container.get(deps[1]), container.get(deps[2]), container.get(deps[3])); }, invokeWithDynamicDependencies: invokeWithDynamicDependencies }, [5]: { invoke(container, Type, deps) { return new Type(container.get(deps[0]), container.get(deps[1]), container.get(deps[2]), container.get(deps[3]), container.get(deps[4])); }, invokeWithDynamicDependencies: invokeWithDynamicDependencies }, fallback: { invoke: invokeWithDynamicDependencies, invokeWithDynamicDependencies: invokeWithDynamicDependencies } }; function getDependencies(f) { if (!f.hasOwnProperty('inject')) { return []; } if (typeof f.inject === 'function') { return f.inject(); } return f.inject; } let Container = class Container { constructor(configuration) { if (configuration === undefined) { configuration = {}; } this._configuration = configuration; this._onHandlerCreated = configuration.onHandlerCreated; this._handlers = configuration.handlers || (configuration.handlers = new Map()); this._resolvers = new Map(); this.root = this; this.parent = null; } makeGlobal() { Container.instance = this; return this; } setHandlerCreatedCallback(onHandlerCreated) { this._onHandlerCreated = onHandlerCreated; this._configuration.onHandlerCreated = onHandlerCreated; } registerInstance(key, instance) { return this.registerResolver(key, new StrategyResolver(0, instance === undefined ? key : instance)); } registerSingleton(key, fn) { return this.registerResolver(key, new StrategyResolver(1, fn === undefined ? key : fn)); } registerTransient(key, fn) { return this.registerResolver(key, new StrategyResolver(2, fn === undefined ? key : fn)); } registerHandler(key, handler) { return this.registerResolver(key, new StrategyResolver(3, handler)); } registerAlias(originalKey, aliasKey) { return this.registerResolver(aliasKey, new StrategyResolver(5, originalKey)); } registerResolver(key, resolver) { validateKey(key); let allResolvers = this._resolvers; let result = allResolvers.get(key); if (result === undefined) { allResolvers.set(key, resolver); } else if (result.strategy === 4) { result.state.push(resolver); } else { allResolvers.set(key, new StrategyResolver(4, [result, resolver])); } return resolver; } autoRegister(key, fn) { fn = fn === undefined ? key : fn; if (typeof fn === 'function') { let registration = metadata.get(metadata.registration, fn); if (registration === undefined) { return this.registerResolver(key, new StrategyResolver(1, fn)); } return registration.registerResolver(this, key, fn); } return this.registerResolver(key, new StrategyResolver(0, fn)); } autoRegisterAll(fns) { let i = fns.length; while (i--) { this.autoRegister(fns[i]); } } unregister(key) { this._resolvers.delete(key); } hasResolver(key, checkParent = false) { validateKey(key); return this._resolvers.has(key) || checkParent && this.parent !== null && this.parent.hasResolver(key, checkParent); } getResolver(key) { return this._resolvers.get(key); } get(key) { validateKey(key); if (key === Container) { return this; } if (resolverDecorates(key)) { return key.get(this, key); } let resolver = this._resolvers.get(key); if (resolver === undefined) { if (this.parent === null) { return this.autoRegister(key).get(this, key); } let registration = metadata.get(metadata.registration, key); if (registration === undefined) { return this.parent._get(key); } return registration.registerResolver(this, key, key).get(this, key); } return resolver.get(this, key); } _get(key) { let resolver = this._resolvers.get(key); if (resolver === undefined) { if (this.parent === null) { return this.autoRegister(key).get(this, key); } return this.parent._get(key); } return resolver.get(this, key); } getAll(key) { validateKey(key); let resolver = this._resolvers.get(key); if (resolver === undefined) { if (this.parent === null) { return _emptyParameters; } return this.parent.getAll(key); } if (resolver.strategy === 4) { let state = resolver.state; let i = state.length; let results = new Array(i); while (i--) { results[i] = state[i].get(this, key); } return results; } return [resolver.get(this, key)]; } createChild() { let child = new Container(this._configuration); child.root = this.root; child.parent = this; return child; } invoke(fn, dynamicDependencies) { try { let handler = this._handlers.get(fn); if (handler === undefined) { handler = this._createInvocationHandler(fn); this._handlers.set(fn, handler); } return handler.invoke(this, dynamicDependencies); } catch (e) { throw new AggregateError(`Error invoking ${fn.name}. Check the inner error for details.`, e, true); } } _createInvocationHandler(fn) { let dependencies; if (fn.inject === undefined) { dependencies = metadata.getOwn(metadata.paramTypes, fn) || _emptyParameters; } else { dependencies = []; let ctor = fn; while (typeof ctor === 'function') { dependencies.push(...getDependencies(ctor)); ctor = Object.getPrototypeOf(ctor); } } let invoker = metadata.getOwn(metadata.invoker, fn) || classInvokers[dependencies.length] || classInvokers.fallback; let handler = new InvocationHandler(fn, invoker, dependencies); return this._onHandlerCreated !== undefined ? this._onHandlerCreated(handler) : handler; } }; function autoinject(potentialTarget) { let deco = function (target) { if (!target.hasOwnProperty('inject')) { target.inject = (metadata.getOwn(metadata.paramTypes, target) || _emptyParameters).slice(); if (target.inject.length > 0 && target.inject[target.inject.length - 1] === Object) { target.inject.pop(); } } }; return potentialTarget ? deco(potentialTarget) : deco; } function inject(...rest) { return function (target, key, descriptor) { if (typeof descriptor === 'number') { autoinject(target); if (rest.length === 1) { target.inject[descriptor] = rest[0]; } return; } if (descriptor) { const fn = descriptor.value; fn.inject = rest; } else { target.inject = rest; } }; } const stackSeparator = '\nEnqueued in TaskQueue by:\n'; const microStackSeparator = '\nEnqueued in MicroTaskQueue by:\n'; function makeRequestFlushFromMutationObserver(flush) { let observer = DOM.createMutationObserver(flush); let val = 'a'; let node = DOM.createTextNode('a'); let values = Object.create(null); values.a = 'b'; values.b = 'a'; observer.observe(node, { characterData: true }); return function requestFlush() { node.data = val = values[val]; }; } function makeRequestFlushFromTimer(flush) { return function requestFlush() { let timeoutHandle = setTimeout(handleFlushTimer, 0); let intervalHandle = setInterval(handleFlushTimer, 50); function handleFlushTimer() { clearTimeout(timeoutHandle); clearInterval(intervalHandle); flush(); } }; } function onError(error, task, longStacks) { if (longStacks && task.stack && typeof error === 'object' && error !== null) { error.stack = filterFlushStack(error.stack) + task.stack; } if ('onError' in task) { task.onError(error); } else { setTimeout(() => { throw error; }, 0); } } let TaskQueue = class TaskQueue { constructor() { this.flushing = false; this.longStacks = false; this.microTaskQueue = []; this.microTaskQueueCapacity = 1024; this.taskQueue = []; if (FEATURE.mutationObserver) { this.requestFlushMicroTaskQueue = makeRequestFlushFromMutationObserver(() => this.flushMicroTaskQueue()); } else { this.requestFlushMicroTaskQueue = makeRequestFlushFromTimer(() => this.flushMicroTaskQueue()); } this.requestFlushTaskQueue = makeRequestFlushFromTimer(() => this.flushTaskQueue()); } _flushQueue(queue, capacity) { let index = 0; let task; try { this.flushing = true; while (index < queue.length) { task = queue[index]; if (this.longStacks) { this.stack = typeof task.stack === 'string' ? task.stack : undefined; } task.call(); index++; if (index > capacity) { for (let scan = 0, newLength = queue.length - index; scan < newLength; scan++) { queue[scan] = queue[scan + index]; } queue.length -= index; index = 0; } } } catch (error) { onError(error, task, this.longStacks); } finally { this.flushing = false; } } queueMicroTask(task) { if (this.microTaskQueue.length < 1) { this.requestFlushMicroTaskQueue(); } if (this.longStacks) { task.stack = this.prepareQueueStack(microStackSeparator); } this.microTaskQueue.push(task); } queueTask(task) { if (this.taskQueue.length < 1) { this.requestFlushTaskQueue(); } if (this.longStacks) { task.stack = this.prepareQueueStack(stackSeparator); } this.taskQueue.push(task); } flushTaskQueue() { let queue = this.taskQueue; this.taskQueue = []; this._flushQueue(queue, Number.MAX_VALUE); } flushMicroTaskQueue() { let queue = this.microTaskQueue; this._flushQueue(queue, this.microTaskQueueCapacity); queue.length = 0; } prepareQueueStack(separator) { let stack = separator + filterQueueStack(captureStack()); if (typeof this.stack === 'string') { stack = filterFlushStack(stack) + this.stack; } return stack; } }; function captureStack() { let error = new Error(); if (error.stack) { return error.stack; } try { throw error; } catch (e) { return e.stack; } } function filterQueueStack(stack) { return stack.replace(/^[\s\S]*?\bqueue(Micro)?Task\b[^\n]*\n/, ''); } function filterFlushStack(stack) { let index = stack.lastIndexOf('flushMicroTaskQueue'); if (index < 0) { index = stack.lastIndexOf('flushTaskQueue'); if (index < 0) { return stack; } } index = stack.lastIndexOf('\n', index); return index < 0 ? stack : stack.substr(0, index); } var _dec$1, _dec2$1, _class$1, _dec3$1, _class2$1, _dec4$1, _class3$1, _dec5$1, _class5$1, _dec6$1, _class7$1, _dec7$1, _class8, _dec8, _class9, _dec9, _class10, _class11, _temp, _dec10, _class12, _class13, _temp2; const targetContext = 'Binding:target'; const sourceContext = 'Binding:source'; const map = Object.create(null); function camelCase(name) { if (name in map) { return map[name]; } const result = name.charAt(0).toLowerCase() + name.slice(1).replace(/[_.-](\w|$)/g, (_, x) => x.toUpperCase()); map[name] = result; return result; } function createOverrideContext(bindingContext, parentOverrideContext) { return { bindingContext: bindingContext, parentOverrideContext: parentOverrideContext || null }; } function getContextFor(name, scope, ancestor) { let oc = scope.overrideContext; if (ancestor) { while (ancestor && oc) { ancestor--; oc = oc.parentOverrideContext; } if (ancestor || !oc) { return undefined; } return name in oc ? oc : oc.bindingContext; } while (oc && !(name in oc) && !(oc.bindingContext && name in oc.bindingContext)) { oc = oc.parentOverrideContext; } if (oc) { return name in oc ? oc : oc.bindingContext; } return scope.bindingContext || scope.overrideContext; } function createScopeForTest(bindingContext, parentBindingContext) { if (parentBindingContext) { return { bindingContext, overrideContext: createOverrideContext(bindingContext, createOverrideContext(parentBindingContext)) }; } return { bindingContext, overrideContext: createOverrideContext(bindingContext) }; } const slotNames = []; const versionSlotNames = []; for (let i = 0; i < 100; i++) { slotNames.push(`_observer${i}`); versionSlotNames.push(`_observerVersion${i}`); } function addObserver(observer) { let observerSlots = this._observerSlots === undefined ? 0 : this._observerSlots; let i = observerSlots; while (i-- && this[slotNames[i]] !== observer) {} if (i === -1) { i = 0; while (this[slotNames[i]]) { i++; } this[slotNames[i]] = observer; observer.subscribe(sourceContext, this); if (i === observerSlots) { this._observerSlots = i + 1; } } if (this._version === undefined) { this._version = 0; } this[versionSlotNames[i]] = this._version; } function observeProperty(obj, propertyName) { let observer = this.observerLocator.getObserver(obj, propertyName); addObserver.call(this, observer); } function observeArray(array) { let observer = this.observerLocator.getArrayObserver(array); addObserver.call(this, observer); } function unobserve(all) { let i = this._observerSlots; while (i--) { if (all || this[versionSlotNames[i]] !== this._version) { let observer = this[slotNames[i]]; this[slotNames[i]] = null; if (observer) { observer.unsubscribe(sourceContext, this); } } } } function connectable() { return function (target) { target.prototype.observeProperty = observeProperty; target.prototype.observeArray = observeArray; target.prototype.unobserve = unobserve; target.prototype.addObserver = addObserver; }; } const queue = []; const queued = {}; let nextId = 0; let minimumImmediate = 100; const frameBudget = 15; let isFlushRequested = false; let immediate = 0; function flush(animationFrameStart) { const length = queue.length; let i = 0; while (i < length) { const binding = queue[i]; queued[binding.__connectQueueId] = false; binding.connect(true); i++; if (i % 100 === 0 && PLATFORM.performance.now() - animationFrameStart > frameBudget) { break; } } queue.splice(0, i); if (queue.length) { PLATFORM.requestAnimationFrame(flush); } else { isFlushRequested = false; immediate = 0; } } function enqueueBindingConnect(binding) { if (immediate < minimumImmediate) { immediate++; binding.connect(false); } else { let id = binding.__connectQueueId; if (id === undefined) { id = nextId; nextId++; binding.__connectQueueId = id; } if (!queued[id]) { queue.push(binding); queued[id] = true; } } if (!isFlushRequested) { isFlushRequested = true; PLATFORM.requestAnimationFrame(flush); } } function setConnectQueueThreshold(value) { minimumImmediate = value; } function enableConnectQueue() { setConnectQueueThreshold(100); } function disableConnectQueue() { setConnectQueueThreshold(Number.MAX_SAFE_INTEGER); } function getConnectQueueSize() { return queue.length; } function addSubscriber(context, callable) { if (this.hasSubscriber(context, callable)) { return false; } if (!this._context0) { this._context0 = context; this._callable0 = callable; return true; } if (!this._context1) { this._context1 = context; this._callable1 = callable; return true; } if (!this._context2) { this._context2 = context; this._callable2 = callable; return true; } if (!this._contextsRest) { this._contextsRest = [context]; this._callablesRest = [callable]; return true; } this._contextsRest.push(context); this._callablesRest.push(callable); return true; } function removeSubscriber(context, callable) { if (this._context0 === context && this._callable0 === callable) { this._context0 = null; this._callable0 = null; return true; } if (this._context1 === context && this._callable1 === callable) { this._context1 = null; this._callable1 = null; return true; } if (this._context2 === context && this._callable2 === callable) { this._context2 = null; this._callable2 = null; return true; } const callables = this._callablesRest; if (callables === undefined || callables.length === 0) { return false; } const contexts = this._contextsRest; let i = 0; while (!(callables[i] === callable && contexts[i] === context) && callables.length > i) { i++; } if (i >= callables.length) { return false; } contexts.splice(i, 1); callables.splice(i, 1); return true; } let arrayPool1 = []; let arrayPool2 = []; let poolUtilization = []; function callSubscribers(newValue, oldValue) { let context0 = this._context0; let callable0 = this._callable0; let context1 = this._context1; let callable1 = this._callable1; let context2 = this._context2; let callable2 = this._callable2; let length = this._contextsRest ? this._contextsRest.length : 0; let contextsRest; let callablesRest; let poolIndex; let i; if (length) { poolIndex = poolUtilization.length; while (poolIndex-- && poolUtilization[poolIndex]) {} if (poolIndex < 0) { poolIndex = poolUtilization.length; contextsRest = []; callablesRest = []; poolUtilization.push(true); arrayPool1.push(contextsRest); arrayPool2.push(callablesRest); } else { poolUtilization[poolIndex] = true; contextsRest = arrayPool1[poolIndex]; callablesRest = arrayPool2[poolIndex]; } i = length; while (i--) { contextsRest[i] = this._contextsRest[i]; callablesRest[i] = this._callablesRest[i]; } } if (context0) { if (callable0) { callable0.call(context0, newValue, oldValue); } else { context0(newValue, oldValue); } } if (context1) { if (callable1) { callable1.call(context1, newValue, oldValue); } else { context1(newValue, oldValue); } } if (context2) { if (callable2) { callable2.call(context2, newValue, oldValue); } else { context2(newValue, oldValue); } } if (length) { for (i = 0; i < length; i++) { let callable = callablesRest[i]; let context = contextsRest[i]; if (callable) { callable.call(context, newValue, oldValue); } else { context(newValue, oldValue); } contextsRest[i] = null; callablesRest[i] = null; } poolUtilization[poolIndex] = false; } } function hasSubscribers() { return !!(this._context0 || this._context1 || this._context2 || this._contextsRest && this._contextsRest.length); } function hasSubscriber(context, callable) { let has = this._context0 === context && this._callable0 === callable || this._context1 === context && this._callable1 === callable || this._context2 === context && this._callable2 === callable; if (has) { return true; } let index; let contexts = this._contextsRest; if (!contexts || (index = contexts.length) === 0) { return false; } let callables = this._callablesRest; while (index--) { if (contexts[index] === context && callables[index] === callable) { return true; } } return false; } function subscriberCollection() { return function (target) { target.prototype.addSubscriber = addSubscriber; target.prototype.removeSubscriber = removeSubscriber; target.prototype.callSubscribers = callSubscribers; target.prototype.hasSubscribers = hasSubscribers; target.prototype.hasSubscriber = hasSubscriber; }; } let ExpressionObserver = (_dec$1 = connectable(), _dec2$1 = subscriberCollection(), _dec$1(_class$1 = _dec2$1(_class$1 = class ExpressionObserver { constructor(scope, expression, observerLocator, lookupFunctions) { this.scope = scope; this.expression = expression; this.observerLocator = observerLocator; this.lookupFunctions = lookupFunctions; } getValue() { return this.expression.evaluate(this.scope, this.lookupFunctions); } setValue(newValue) { this.expression.assign(this.scope, newValue); } subscribe(context, callable) { if (!this.hasSubscribers()) { this.oldValue = this.expression.evaluate(this.scope, this.lookupFunctions); this.expression.connect(this, this.scope); } this.addSubscriber(context, callable); if (arguments.length === 1 && context instanceof Function) { return { dispose: () => { this.unsubscribe(context, callable); } }; } } unsubscribe(context, callable) { if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) { this.unobserve(true); this.oldValue = undefined; } } call() { let newValue = this.expression.evaluate(this.scope, this.lookupFunctions); let oldValue = this.oldValue; if (newValue !== oldValue) { this.oldValue = newValue; this.callSubscribers(newValue, oldValue); } this._version++; this.expression.connect(this, this.scope); this.unobserve(false); } }) || _class$1) || _class$1); function isIndex(s) { return +s === s >>> 0; } function toNumber(s) { return +s; } function newSplice(index, removed, addedCount) { return { index: index, removed: removed, addedCount: addedCount }; } const EDIT_LEAVE = 0; const EDIT_UPDATE = 1; const EDIT_ADD = 2; const EDIT_DELETE = 3; function ArraySplice() {} ArraySplice.prototype = { calcEditDistances: function (current, currentStart, currentEnd, old, oldStart, oldEnd) { let rowCount = oldEnd - oldStart + 1; let columnCount = currentEnd - currentStart + 1; let distances = new Array(rowCount); let north; let west; for (let i = 0; i < rowCount; ++i) { distances[i] = new Array(columnCount); distances[i][0] = i; } for (let j = 0; j < columnCount; ++j) { distances[0][j] = j; } for (let i = 1; i < rowCount; ++i) { for (let j = 1; j < columnCount; ++j) { if (this.equals(current[currentStart + j - 1], old[oldStart + i - 1])) { distances[i][j] = distances[i - 1][j - 1]; } else { north = distances[i - 1][j] + 1; west = distances[i][j - 1] + 1; distances[i][j] = north < west ? north : west; } } } return distances; }, spliceOperationsFromEditDistances: function (distances) { let i = distances.length - 1; let j = distances[0].length - 1; let current = distances[i][j]; let edits = []; while (i > 0 || j > 0) { if (i === 0) { edits.push(EDIT_ADD); j--; continue; } if (j === 0) { edits.push(EDIT_DELETE); i--; continue; } let northWest = distances[i - 1][j - 1]; let west = distances[i - 1][j]; let north = distances[i][j - 1]; let min; if (west < north) { min = west < northWest ? west : northWest; } else { min = north < northWest ? north : northWest; } if (min === northWest) { if (northWest === current) { edits.push(EDIT_LEAVE); } else { edits.push(EDIT_UPDATE); current = northWest; } i--; j--; } else if (min === west) { edits.push(EDIT_DELETE); i--; current = west; } else { edits.push(EDIT_ADD); j--; current = north; } } edits.reverse(); return edits; }, calcSplices: function (current, currentStart, currentEnd, old, oldStart, oldEnd) { let prefixCount = 0; let suffixCount = 0; let minLength = Math.min(currentEnd - currentStart, oldEnd - oldStart); if (currentStart === 0 && oldStart === 0) { prefixCount = this.sharedPrefix(current, old, minLength); } if (currentEnd === current.length && oldEnd === old.length) { suffixCount = this.sharedSuffix(current, old, minLength - prefixCount); } currentStart += prefixCount; oldStart += prefixCount; currentEnd -= suffixCount; oldEnd -= suffixCount; if (currentEnd - currentStart === 0 && oldEnd - oldStart === 0) { return []; } if (currentStart === currentEnd) { let splice = newSplice(currentStart, [], 0); while (oldStart < oldEnd) { splice.removed.push(old[oldStart++]); } return [splice]; } else if (oldStart === oldEnd) { return [newSplice(currentStart, [], currentEnd - currentStart)]; } let ops = this.spliceOperationsFromEditDistances(this.calcEditDistances(current, currentStart, currentEnd, old, oldStart, oldEnd)); let splice = undefined; let splices = []; let index = currentStart; let oldIndex = oldStart; for (let i = 0; i < ops.length; ++i) { switch (ops[i]) { case EDIT_LEAVE: if (splice) { splices.push(splice); splice = undefined; } index++; oldIndex++; break; case EDIT_UPDATE: if (!splice) { splice = newSplice(index, [], 0); } splice.addedCount++; index++; splice.removed.push(old[oldIndex]); oldIndex++; break; case EDIT_ADD: if (!splice) { splice = newSplice(index, [], 0); } splice.addedCount++; index++; break; case EDIT_DELETE: if (!splice) { splice = newSplice(index, [], 0); } splice.removed.push(old[oldIndex]); oldIndex++; break; } } if (splice) { splices.push(splice); } return splices; }, sharedPrefix: function (current, old, searchLength) { for (let i = 0; i < searchLength; ++i) { if (!this.equals(current[i], old[i])) { return i; } } return searchLength; }, sharedSuffix: function (current, old, searchLength) { let index1 = current.length; let index2 = old.length; let count = 0; while (count < searchLength && this.equals(current[--index1], old[--index2])) { count++; } return count; }, calculateSplices: function (current, previous) { return this.calcSplices(current, 0, current.length, previous, 0, previous.length); }, equals: function (currentValue, previousValue) { return currentValue === previousValue; } }; let arraySplice = new ArraySplice(); function calcSplices(current, currentStart, currentEnd, old, oldStart, oldEnd) { return arraySplice.calcSplices(current, currentStart, currentEnd, old, oldStart, oldEnd); } function intersect(start1, end1, start2, end2) { if (end1 < start2 || end2 < start1) { return -1; } if (end1 === start2 || end2 === start1) { return 0; } if (start1 < start2) { if (end1 < end2) { return end1 - start2; } return end2 - start2; } if (end2 < end1) { return end2 - start1; } return end1 - start1; } function mergeSplice(splices, index, removed, addedCount) { let splice = newSplice(index, removed, addedCount); let inserted = false; let insertionOffset = 0; for (let i = 0; i < splices.length; i++) { let current = splices[i]; current.index += insertionOffset; if (inserted) { continue; } let intersectCount = intersect(splice.index, splice.index + splice.removed.length, current.index, current.index + current.addedCount); if (intersectCount >= 0) { splices.splice(i, 1); i--; insertionOffset -= current.addedCount - current.removed.length; splice.addedCount += current.addedCount - intersectCount; let deleteCount = splice.removed.length + current.removed.length - intersectCount; if (!splice.addedCount && !deleteCount) { inserted = true; } else { let currentRemoved = current.removed; if (splice.index < current.index) { let prepend = splice.removed.slice(0, current.index - splice.index); Array.prototype.push.apply(prepend, currentRemoved); currentRemoved = prepend; } if (splice.index + splice.removed.length > current.index + current.addedCount) { let append = splice.removed.slice(current.index + current.addedCount - splice.index); Array.prototype.push.apply(currentRemoved, append); } splice.removed = currentRemoved; if (current.index < splice.index) { splice.index = current.index; } } } else if (splice.index < current.index) { inserted = true; splices.splice(i, 0, splice); i++; let offset = splice.addedCount - splice.removed.length; current.index += offset; insertionOffset += offset; } } if (!inserted) { splices.push(splice); } } function createInitialSplices(array, changeRecords) { let splices = []; for (let i = 0; i < changeRecords.length; i++) { let record = changeRecords[i]; switch (record.type) { case 'splice': mergeSplice(splices, record.index, record.removed.slice(), record.addedCount); break; case 'add': case 'update': case 'delete': if (!isIndex(record.name)) { continue; } let index = toNumber(record.name); if (index < 0) { continue; } mergeSplice(splices, index, [record.oldValue], record.type === 'delete' ? 0 : 1); break; default: console.error('Unexpected record type: ' + JSON.stringify(record)); break; } } return splices; } function projectArraySplices(array, changeRecords) { let splices = []; createInitialSplices(array, changeRecords).forEach(function (splice) { if (splice.addedCount === 1 && splice.removed.length === 1) { if (splice.removed[0] !== array[splice.index]) { splices.push(splice); } return; } splices = splices.concat(calcSplices(array, splice.index, splice.index + splice.addedCount, splice.removed, 0, splice.removed.length)); }); return splices; } function newRecord(type, object, key, oldValue) { return { type: type, object: object, key: key, oldValue: oldValue }; } function getChangeRecords(map) { let entries = new Array(map.size); let keys = map.keys(); let i = 0; let item; while (item = keys.next()) { if (item.done) { break; } entries[i] = newRecord('added', map, item.value); i++; } return entries; } let ModifyCollectionObserver = (_dec3$1 = subscriberCollection(), _dec3$1(_class2$1 = class ModifyCollectionObserver { constructor(taskQueue, collection) { this.taskQueue = taskQueue; this.queued = false; this.changeRecords = null; this.oldCollection = null; this.collection = collection; this.lengthPropertyName = collection instanceof Map || collection instanceof Set ? 'size' : 'length'; } subscribe(context, callable) { this.addSubscriber(context, callable); } unsubscribe(context, callable) { this.removeSubscriber(context, callable); } addChangeRecord(changeRecord) { if (!this.hasSubscribers() && !this.lengthObserver) { return; } if (changeRecord.type === 'splice') { let index = changeRecord.index; let arrayLength = changeRecord.object.length; if (index > arrayLength) { index = arrayLength - changeRecord.addedCount; } else if (index < 0) { index = arrayLength + changeRecord.removed.length + index - changeRecord.addedCount; } if (index < 0) { index = 0; } changeRecord.index = index; } if (this.changeRecords === null) { this.changeRecords = [changeRecord]; } else { this.changeRecords.push(changeRecord); } if (!this.queued) { this.queued = true; this.taskQueue.queueMicroTask(this); } } flushChangeRecords() { if (this.changeRecords && this.changeRecords.length || this.oldCollection) { this.call(); } } reset(oldCollection) { this.oldCollection = oldCollection; if (this.hasSubscribers() && !this.queued) { this.queued = true; this.taskQueue.queueMicroTask(this); } } getLengthObserver() { return this.lengthObserver || (this.lengthObserver = new CollectionLengthObserver(this.collection)); } call() { let changeRecords = this.changeRecords; let oldCollection = this.oldCollection; let records; this.queued = false; this.changeRecords = []; this.oldCollection = null; if (this.hasSubscribers()) { if (oldCollection) { if (this.collection instanceof Map || this.collection instanceof Set) { records = getChangeRecords(oldCollection); } else { records = calcSplices(this.collection, 0, this.collection.length, oldCollection, 0, oldCollection.length); } } else { if (this.collection instanceof Map || this.collection instanceof Set) { records = changeRecords; } else { records = projectArraySplices(this.collection, changeRecords); } } this.callSubscribers(records); } if (this.lengthObserver) { this.lengthObserver.call(this.collection[this.lengthPropertyName]); } } }) || _class2$1); let CollectionLengthObserver = (_dec4$1 = subscriberCollection(), _dec4$1(_class3$1 = class CollectionLengthObserver { constructor(collection) { this.collection = collection; this.lengthPropertyName = collection instanceof Map || collection instanceof Set ? 'size' : 'length'; this.currentValue = collection[this.lengthPropertyName]; } getValue() { return this.collection[this.lengthPropertyName]; } setValue(newValue) { this.collection[this.lengthPropertyName] = newValue; } subscribe(context, callable) { this.addSubscriber(context, callable); } unsubscribe(context, callable) { this.removeSubscriber(context, callable); } call(newValue) { let oldValue = this.currentValue; this.callSubscribers(newValue, oldValue); this.currentValue = newValue; } }) || _class3$1); const arrayProto = Array.prototype; const pop = arrayProto.pop; const push = arrayProto.push; const reverse = arrayProto.reverse; const shift = arrayProto.shift; const sort = arrayProto.sort; const splice = arrayProto.splice; const unshift = arrayProto.unshift; if (arrayProto.__au_patched__) { getLogger('array-observation').warn('Detected 2nd attempt of patching array from Aurelia binding.' + ' This is probably caused by dependency mismatch between core modules and a 3rd party plugin.' + ' Please see https://github.com/aurelia/cli/pull/906 if you are using webpack.'); } else { Reflect.defineProperty(arrayProto, '__au_patched__', { value: 1 }); arrayProto.pop = function () { let notEmpty = this.length > 0; let methodCallResult = pop.apply(this, arguments); if (notEmpty && this.__array_observer__ !== undefined) { this.__array_observer__.addChangeRecord({ type: 'delete', object: this, name: this.length, oldValue: methodCallResult }); } return methodCallResult; }; arrayProto.push = function () { let methodCallResult = push.apply(this, arguments); if (this.__array_observer__ !== undefined) { this.__array_observer__.addChangeRecord({ type: 'splice', object: this, index: this.length - arguments.length, removed: [], addedCount: arguments.length }); } return methodCallResult; }; arrayProto.reverse = function () { let oldArray; if (this.__array_observer__ !== undefined) { this.__array_observer__.flushChangeRecords(); oldArray = this.slice(); } let methodCallResult = reverse.apply(this, arguments); if (this.__array_observer__ !== undefined) { this.__array_observer__.reset(oldArray); } return methodCallResult; }; arrayProto.shift = function () { let notEmpty = this.length > 0; let methodCallResult = shift.apply(this, arguments); if (notEmpty && this.__array_observer__ !== undefined) { this.__array_observer__.addChangeRecord({ type: 'delete', object: this, name: 0, oldValue: methodCallResult }); } return methodCallResult; }; arrayProto.sort = function () { let oldArray; if (this.__array_observer__ !== undefined) { this.__array_observer__.flushChangeRecords(); oldArray = this.slice(); } let methodCallResult = sort.apply(this, arguments); if (this.__array_observer__ !== undefined) { this.__array_observer__.reset(oldArray); } return methodCallResult; }; arrayProto.splice = function () { let methodCallResult = splice.apply(this, arguments); if (this.__array_observer__ !== undefined) { this.__array_observer__.addChangeRecord({ type: 'splice', object: this, index: +arguments[0], removed: methodCallResult, addedCount: arguments.length > 2 ? arguments.length - 2 : 0 }); } return methodCallResult; }; arrayProto.unshift = function () { let methodCallResult = unshift.apply(this, arguments); if (this.__array_observer__ !== undefined) { this.__array_observer__.addChangeRecord({ type: 'splice', object: this, index: 0, removed: [], addedCount: arguments.length }); } return methodCallResult; }; } function getArrayObserver(taskQueue, array) { return ModifyArrayObserver.for(taskQueue, array); } let ModifyArrayObserver = class ModifyArrayObserver extends ModifyCollectionObserver { constructor(taskQueue, array) { super(taskQueue, array); } static for(taskQueue, array) { if (!('__array_observer__' in array)) { Reflect.defineProperty(array, '__array_observer__', { value: ModifyArrayObserver.create(taskQueue, array), enumerable: false, configurable: false }); } return array.__array_observer__; } static create(taskQueue, array) { return new ModifyArrayObserver(taskQueue, array); } }; let Expression = class Expression { constructor() { this.isAssignable = false; } evaluate(scope, lookupFunctions, args) { throw new Error(`Binding expression "${this}" cannot be evaluated.`); } assign(scope, value, lookupFunctions) { throw new Error(`Binding expression "${this}" cannot be assigned to.`); } toString() { return super.toString(); } }; let BindingBehavior = class BindingBehavior extends Expression { constructor(expression, name, args) { super(); this.expression = expression; this.name = name; this.args = args; } evaluate(scope, lookupFunctions) { return this.expression.evaluate(scope, lookupFunctions); } assign(scope, value, lookupFunctions) { return this.expression.assign(scope, value, lookupFunctions); } accept(visitor) { return visitor.visitBindingBehavior(this); } connect(binding, scope) { this.expression.connect(binding, scope); } bind(binding, scope, lookupFunctions) { if (this.expression.expression && this.expression.bind) { this.expression.bind(binding, scope, lookupFunctions); } let behavior = lookupFunctions.bindingBehaviors(this.name); if (!behavior) { throw new Error(`No BindingBehavior named "${this.name}" was found!`); } let behaviorKey = `behavior-${this.name}`; if (binding[behaviorKey]) { throw new Error(`A binding behavior named "${this.name}" has already been applied to "${this.expression}"`); } binding[behaviorKey] = behavior; behavior.bind.apply(behavior, [binding, scope].concat(evalList(scope, this.args, binding.lookupFunctions))); } unbind(binding, scope) { let behaviorKey = `behavior-${this.name}`; binding[behaviorKey].unbind(binding, scope); binding[behaviorKey] = null; if (this.expression.expression && this.expression.unbind) { this.expression.unbind(binding, scope); } } }; let ValueConverter = class ValueConverter extends Expression { constructor(expression, name, args) { super(); this.expression = expression; this.name = name; this.args = args; this.allArgs = [expression].concat(args); } evaluate(scope, lookupFunctions) { let converter = lookupFunctions.valueConverters(this.name); if (!converter) { throw new Error(`No ValueConverter named "${this.name}" was found!`); } if ('toView' in converter) { return converter.toView.apply(converter, evalList(scope, this.allArgs, lookupFunctions)); } return this.allArgs[0].evaluate(scope, lookupFunctions); } assign(scope, value, lookupFunctions) { let converter = lookupFunctions.valueConverters(this.name); if (!converter) { throw new Error(`No ValueConverter named "${this.name}" was found!`); } if ('fromView' in converter) { value = converter.fromView.apply(converter, [value].concat(evalList(scope, this.args, lookupFunctions))); } return this.allArgs[0].assign(scope, value, lookupFunctions); } accept(visitor) { return visitor.visitValueConverter(this); } connect(binding, scope) { let expressions = this.allArgs; let i = expressions.length; while (i--) { expressions[i].connect(binding, scope); } let converter = binding.lookupFunctions.valueConverters(this.name); if (!converter) { throw new Error(`No ValueConverter named "${this.name}" was found!`); } let signals = converter.signals; if (signals === undefined) { return; } i = signals.length; while (i--) { connectBindingToSignal(binding, signals[i]); } } }; let Assign = class Assign extends Expression { constructor(target, value) { super(); this.target = target; this.value = value; this.isAssignable = true; } evaluate(scope, lookupFunctions) { return this.target.assign(scope, this.value.evaluate(scope, lookupFunctions)); } accept(vistor) { vistor.visitAssign(this); } connect(binding, scope) {} assign(scope, value) { this.value.assign(scope, value); this.target.assign(scope, value); } }; let Conditional = class Conditional extends Expression { constructor(condition, yes, no) { super(); this.condition = condition; this.yes = yes; this.no = no; } evaluate(scope, lookupFunctions) { return !!this.condition.evaluate(scope, lookupFunctions) ? this.yes.evaluate(scope, lookupFunctions) : this.no.evaluate(scope, lookupFunctions); } accept(visitor) { return visitor.visitConditional(this); } connect(binding, scope) { this.condition.connect(binding, scope); if (this.condition.evaluate(scope)) { this.yes.connect(binding, scope); } else { this.no.connect(binding, scope); } } }; let AccessThis = class AccessThis extends Expression { constructor(ancestor) { super(); this.ancestor = ancestor; } evaluate(scope, lookupFunctions) { let oc = scope.overrideContext; let i = this.ancestor; while (i-- && oc) { oc = oc.parentOverrideContext; } return i < 1 && oc ? oc.bindingContext : undefined; } accept(visitor) { return visitor.visitAccessThis(this); } connect(binding, scope) {} }; let AccessScope = class AccessScope extends Expression { constructor(name, ancestor) { super(); this.name = name; this.ancestor = ancestor; this.isAssignable = true; } evaluate(scope, lookupFunctions) { let context = getContextFor(this.name, scope, this.ancestor); return context[this.name]; } assign(scope, value) { let context = getContextFor(this.name, scope, this.ancestor); return context ? context[this.name] = value : undefined; } accept(visitor) { return visitor.visitAccessScope(this); } connect(binding, scope) { let context = getContextFor(this.name, scope, this.ancestor); binding.observeProperty(context, this.name); } }; let AccessMember = class AccessMember extends Expression { constructor(object, name) { super(); this.object = object; this.name = name; this.isAssignable = true; } evaluate(scope, lookupFunctions) { let instance = this.object.evaluate(scope, lookupFunctions); return instance === null || instance === undefined ? instance : instance[this.name]; } assign(scope, value) { let instance = this.object.evaluate(scope); if (instance === null || instance === undefined) { instance = {}; this.object.assign(scope, instance); } instance[this.name] = value; return value; } accept(visitor) { return visitor.visitAccessMember(this); } connect(binding, scope) { this.object.connect(binding, scope); let obj = this.object.evaluate(scope); if (obj) { binding.observeProperty(obj, this.name); } } }; let AccessKeyed = class AccessKeyed extends Expression { constructor(object, key) { super(); this.object = object; this.key = key; this.isAssignable = true; } evaluate(scope, lookupFunctions) { let instance = this.object.evaluate(scope, lookupFunctions); let lookup = this.key.evaluate(scope, lookupFunctions); return getKeyed(instance, lookup); } assign(scope, value) { let instance = this.object.evaluate(scope); let lookup = this.key.evaluate(scope); return setKeyed(instance, lookup, value); } accept(visitor) { return visitor.visitAccessKeyed(this); } connect(binding, scope) { this.object.connect(binding, scope); let obj = this.object.evaluate(scope); if (obj instanceof Object) { this.key.connect(binding, scope); let key = this.key.evaluate(scope); if (key !== null && key !== undefined && !(Array.isArray(obj) && typeof key === 'number')) { binding.observeProperty(obj, key); } } } }; let CallScope = class CallScope extends Expression { constructor(name, args, ancestor) { super(); this.name = name; this.args = args; this.ancestor = ancestor; } evaluate(scope, lookupFunctions, mustEvaluate) { let args = evalList(scope, this.args, lookupFunctions); let context = getContextFor(this.name, scope, this.ancestor); let func = getFunction(context, this.name, mustEvaluate); if (func) { return func.apply(context, args); } return undefined; } accept(visitor) { return visitor.visitCallScope(this); } connect(binding, scope) { let args = this.args; let i = args.length; while (i--) { args[i].connect(binding, scope); } } }; let CallMember = class CallMember extends Expression { constructor(object, name, args) { super(); this.object = object; this.name = name; this.args = args; } evaluate(scope, lookupFunctions, mustEvaluate) { let instance = this.object.evaluate(scope, lookupFunctions); let args = evalList(scope, this.args, lookupFunctions); let func = getFunction(instance, this.name, mustEvaluate); if (func) { return func.apply(instance, args); } return undefined; } accept(visitor) { return visitor.visitCallMember(this); } connect(binding, scope) { this.object.connect(binding, scope); let obj = this.object.evaluate(scope); if (getFunction(obj, this.name, false)) { let args = this.args; let i = args.length; while (i--) { args[i].connect(binding, scope); } } } }; let CallFunction = class CallFunction extends Expression { constructor(func, args) { super(); this.func = func; this.args = args; } evaluate(scope, lookupFunctions, mustEvaluate) { let func = this.func.evaluate(scope, lookupFunctions); if (typeof func === 'function') { return func.apply(null, evalList(scope, this.args, lookupFunctions)); } if (!mustEvaluate && (func === null || func === undefined)) { return undefined; } throw new Error(`${this.func} is not a function`); } accept(visitor) { return visitor.visitCallFunction(this); } connect(binding, scope) { this.func.connect(binding, scope); let func = this.func.evaluate(scope); if (typeof func === 'function') { let args = this.args; let i = args.length; while (i--) { args[i].connect(binding, scope); } } } }; let Binary = class Binary extends Expression { constructor(operation, left, right) { super(); this.operation = operation; this.left = left; this.right = right; } evaluate(scope, lookupFunctions) { let left = this.left.evaluate(scope, lookupFunctions); switch (this.operation) { case '&&': return left && this.right.evaluate(scope, lookupFunctions); case '||': return left || this.right.evaluate(scope, lookupFunctions); } let right = this.right.evaluate(scope, lookupFunctions); switch (this.operation) { case '==': return left == right; case '===': return left === right; case '!=': return left != right; case '!==': return left !== right; case 'instanceof': return typeof right === 'function' && left instanceof right; case 'in': return typeof right === 'object' && right !== null && left in right; } if (left === null || right === null || left === undefined || right === undefined) { switch (this.operation) { case '+': if (left !== null && left !== undefined) return left; if (right !== null && right !== undefined) return right; return 0; case '-': if (left !== null && left !== undefined) return left; if (right !== null && right !== undefined) return 0 - right; return 0; } return null; } switch (this.operation) { case '+': return autoConvertAdd(left, right); case '-': return left - right; case '*': return left * right; case '/': return left / right; case '%': return left % right; case '<': return left < right; case '>': return left > right; case '<=': return left <= right; case '>=': return left >= right; case '^': return left ^ right; } throw new Error(`Internal error [${this.operation}] not handled`); } accept(visitor) { return visitor.visitBinary(this); } connect(binding, scope) { this.left.connect(binding, scope); let left = this.left.evaluate(scope); if (this.operation === '&&' && !left || this.operation === '||' && left) { return; } this.right.connect(binding, scope); } }; let Unary = class Unary extends Expression { constructor(operation, expression) { super(); this.operation = operation; this.expression = expression; } evaluate(scope, lookupFunctions) { switch (this.operation) { case '!': return !this.expression.evaluate(scope, lookupFunctions); case 'typeof': return typeof this.expression.evaluate(scope, lookupFunctions); case 'void': return void this.expression.evaluate(scope, lookupFunctions); } throw new Error(`Internal error [${this.operation}] not handled`); } accept(visitor) { return visitor.visitPrefix(this); } connect(binding, scope) { this.expression.connect(binding, scope); } }; let LiteralPrimitive = class LiteralPrimitive extends Expression { constructor(value) { super(); this.value = value; } evaluate(scope, lookupFunctions) { return this.value; } accept(visitor) { return visitor.visitLiteralPrimitive(this); } connect(binding, scope) {} }; let LiteralString = class LiteralString extends Expression { constructor(value) { super(); this.value = value; } evaluate(scope, lookupFunctions) { return this.value; } accept(visitor) { return visitor.visitLiteralString(this); } connect(binding, scope) {} }; let LiteralTemplate = class LiteralTemplate extends Expression { constructor(cooked, expressions, raw, tag) { super(); this.cooked = cooked; this.expressions = expressions || []; this.length = this.expressions.length; this.tagged = tag !== undefined; if (this.tagged) { this.cooked.raw = raw; this.tag = tag; if (tag instanceof AccessScope) { this.contextType = 'Scope'; } else if (tag instanceof AccessMember || tag instanceof AccessKeyed) { this.contextType = 'Object'; } else { throw new Error(`${this.tag} is not a valid template tag`); } } } getScopeContext(scope, lookupFunctions) { return getContextFor(this.tag.name, scope, this.tag.ancestor); } getObjectContext(scope, lookupFunctions) { return this.tag.object.evaluate(scope, lookupFunctions); } evaluate(scope, lookupFunctions, mustEvaluate) { const results = new Array(this.length); for (let i = 0; i < this.length; i++) { results[i] = this.expressions[i].evaluate(scope, lookupFunctions); } if (this.tagged) { const func = this.tag.evaluate(scope, lookupFunctions); if (typeof func === 'function') { const context = this[`get${this.contextType}Context`](scope, lookupFunctions); return func.call(context, this.cooked, ...results); } if (!mustEvaluate) { return null; } throw new Error(`${this.tag} is not a function`); } let result = this.cooked[0]; for (let i = 0; i < this.length; i++) { result = String.prototype.concat(result, results[i], this.cooked[i + 1]); } return result; } accept(visitor) { return visitor.visitLiteralTemplate(this); } connect(binding, scope) { for (let i = 0; i < this.length; i++) { this.expressions[i].connect(binding, scope); } if (this.tagged) { this.tag.connect(binding, scope); } } }; let LiteralArray = class LiteralArray extends Expression { constructor(elements) { super(); this.elements = elements; } evaluate(scope, lookupFunctions) { let elements = this.elements; let result = []; for (let i = 0, length = elements.length; i < length; ++i) { result[i] = elements[i].evaluate(scope, lookupFunctions); } return result; } accept(visitor) { return visitor.visitLiteralArray(this); } connect(binding, scope) { let length = this.elements.length; for (let i = 0; i < length; i++) { this.elements[i].connect(binding, scope); } } }; let LiteralObject = class LiteralObject extends Expression { constructor(keys, values) { super(); this.keys = keys; this.values = values; } evaluate(scope, lookupFunctions) { let instance = {}; let keys = this.keys; let values = this.values; for (let i = 0, length = keys.length; i < length; ++i) { instance[keys[i]] = values[i].evaluate(scope, lookupFunctions); } return instance; } accept(visitor) { return visitor.visitLiteralObject(this); } connect(binding, scope) { let length = this.keys.length; for (let i = 0; i < length; i++) { this.values[i].connect(binding, scope); } } }; function evalList(scope, list, lookupFunctions) { const length = list.length; const result = []; for (let i = 0; i < length; i++) { result[i] = list[i].evaluate(scope, lookupFunctions); } return result; } function autoConvertAdd(a, b) { if (a !== null && b !== null) { if (typeof a === 'string' && typeof b !== 'string') { return a + b.toString(); } if (typeof a !== 'string' && typeof b === 'string') { return a.toString() + b; } return a + b; } if (a !== null) { return a; } if (b !== null) { return b; } return 0; } function getFunction(obj, name, mustExist) { let func = obj === null || obj === undefined ? null : obj[name]; if (typeof func === 'function') { return func; } if (!mustExist && (func === null || func === undefined)) { return null; } throw new Error(`${name} is not a function`); } function getKeyed(obj, key) { if (Array.isArray(obj)) { return obj[parseInt(key, 10)]; } else if (obj) { return obj[key]; } else if (obj === null || obj === undefined) { return undefined; } return obj[key]; } function setKeyed(obj, key, value) { if (Array.isArray(obj)) { let index = parseInt(key, 10); if (obj.length <= index) { obj.length = index + 1; } obj[index] = value; } else { obj[key] = value; } return value; } exports.Unparser = null; let ExpressionCloner = class ExpressionCloner { cloneExpressionArray(array) { let clonedArray = []; let i = array.length; while (i--) { clonedArray[i] = array[i].accept(this); } return clonedArray; } visitBindingBehavior(behavior) { return new BindingBehavior(behavior.expression.accept(this), behavior.name, this.cloneExpressionArray(behavior.args)); } visitValueConverter(converter) { return new ValueConverter(converter.expression.accept(this), converter.name, this.cloneExpressionArray(converter.args)); } visitAssign(assign) { return new Assign(assign.target.accept(this), assign.value.accept(this)); } visitConditional(conditional) { return new Conditional(conditional.condition.accept(this), conditional.yes.accept(this), conditional.no.accept(this)); } visitAccessThis(access) { return new AccessThis(access.ancestor); } visitAccessScope(access) { return new AccessScope(access.name, access.ancestor); } visitAccessMember(access) { return new AccessMember(access.object.accept(this), access.name); } visitAccessKeyed(access) { return new AccessKeyed(access.object.accept(this), access.key.accept(this)); } visitCallScope(call) { return new CallScope(call.name, this.cloneExpressionArray(call.args), call.ancestor); } visitCallFunction(call) { return new CallFunction(call.func.accept(this), this.cloneExpressionArray(call.args)); } visitCallMember(call) { return new CallMember(call.object.accept(this), call.name, this.cloneExpressionArray(call.args)); } visitUnary(unary) { return new Unary(prefix.operation, prefix.expression.accept(this)); } visitBinary(binary) { return new Binary(binary.operation, binary.left.accept(this), binary.right.accept(this)); } visitLiteralPrimitive(literal) { return new LiteralPrimitive(literal); } visitLiteralArray(literal) { return new LiteralArray(this.cloneExpressionArray(literal.elements)); } visitLiteralObject(literal) { return new LiteralObject(literal.keys, this.cloneExpressionArray(literal.values)); } visitLiteralString(literal) { return new LiteralString(literal.value); } visitLiteralTemplate(literal) { return new LiteralTemplate(literal.cooked, this.cloneExpressionArray(literal.expressions), literal.raw, literal.tag && literal.tag.accept(this)); } }; function cloneExpression(expression) { let visitor = new ExpressionCloner(); return expression.accept(visitor); } const bindingMode = { oneTime: 0, toView: 1, oneWay: 1, twoWay: 2, fromView: 3 }; let Parser = class Parser { constructor() { this.cache = Object.create(null); } parse(src) { src = src || ''; return this.cache[src] || (this.cache[src] = new ParserImplementation(src).parseBindingBehavior()); } }; const fromCharCode = String.fromCharCode; let ParserImplementation = class ParserImplementation { get raw() { return this.src.slice(this.start, this.idx); } constructor(src) { this.idx = 0; this.start = 0; this.src = src; this.len = src.length; this.tkn = T$EOF; this.val = undefined; this.ch = src.charCodeAt(0); } parseBindingBehavior() { this.nextToken(); if (this.tkn & T$ExpressionTerminal) { this.err('Invalid start of expression'); } let result = this.parseValueConverter(); while (this.opt(T$Ampersand)) { result = new BindingBehavior(result, this.val, this.parseVariadicArgs()); } if (this.tkn !== T$EOF) { this.err(`Unconsumed token ${this.raw}`); } return result; } parseValueConverter() { let result = this.parseExpression(); while (this.opt(T$Bar)) { result = new ValueConverter(result, this.val, this.parseVariadicArgs()); } return result; } parseVariadicArgs() { this.nextToken(); const result = []; while (this.opt(T$Colon)) { result.push(this.parseExpression()); } return result; } parseExpression() { let exprStart = this.idx; let result = this.parseConditional(); while (this.tkn === T$Eq) { if (!result.isAssignable) { this.err(`Expression ${this.src.slice(exprStart, this.start)} is not assignable`); } this.nextToken(); exprStart = this.idx; result = new Assign(result, this.parseConditional()); } return result; } parseConditional() { let result = this.parseBinary(0); if (this.opt(T$Question)) { let yes = this.parseExpression(); this.expect(T$Colon); result = new Conditional(result, yes, this.parseExpression()); } return result; } parseBinary(minPrecedence) { let left = this.parseLeftHandSide(0); while (this.tkn & T$BinaryOp) { const opToken = this.tkn; if ((opToken & T$Precedence) <= minPrecedence) { break; } this.nextToken(); left = new Binary(TokenValues[opToken & T$TokenMask], left, this.parseBinary(opToken & T$Precedence)); } return left; } parseLeftHandSide(context) { let result; primary: switch (this.tkn) { case T$Plus: this.nextToken(); return this.parseLeftHandSide(0); case T$Minus: this.nextToken(); return new Binary('-', new LiteralPrimitive(0), this.parseLeftHandSide(0)); case T$Bang: case T$TypeofKeyword: case T$VoidKeyword: const op = TokenValues[this.tkn & T$TokenMask]; this.nextToken(); return new Unary(op, this.parseLeftHandSide(0)); case T$ParentScope: { do { this.nextToken(); context++; if (this.opt(T$Period)) { if (this.tkn === T$Period) { this.err(); } continue; } else if (this.tkn & T$AccessScopeTerminal) { result = new AccessThis(context & C$Ancestor); context = context & C$ShorthandProp | C$This; break primary; } else { this.err(); } } while (this.tkn === T$ParentScope); } case T$Identifier: { result = new AccessScope(this.val, context & C$Ancestor); this.nextToken(); context = context & C$ShorthandProp | C$Scope; break; } case T$ThisScope: this.nextToken(); result = new AccessThis(0); context = context & C$ShorthandProp | C$This; break; case T$LParen: this.nextToken(); result = this.parseExpression(); this.expect(T$RParen); context = C$Primary; break; case T$LBracket: { this.nextToken(); const elements = []; if (this.tkn !== T$RBracket) { do { elements.push(this.parseExpression()); } while (this.opt(T$Comma)); } this.expect(T$RBracket); result = new LiteralArray(elements); context = C$Primary; break; } case T$LBrace: { const keys = []; const values = []; this.nextToken(); while (this.tkn !== T$RBrace) { if (this.tkn & T$IdentifierOrKeyword) { const { ch, tkn, idx } = this; keys.push(this.val); this.nextToken(); if (this.opt(T$Colon)) { values.push(this.parseExpression()); } else { this.ch = ch; this.tkn = tkn; this.idx = idx; values.push(this.parseLeftHandSide(C$ShorthandProp)); } } else if (this.tkn & T$Literal) { keys.push(this.val); this.nextToken(); this.expect(T$Colon); values.push(this.parseExpression()); } else { this.err(); } if (this.tkn !== T$RBrace) { this.expect(T$Comma); } } this.expect(T$RBrace); result = new LiteralObject(keys, values); context = C$Primary; break; } case T$StringLiteral: result = new LiteralString(this.val); this.nextToken(); context = C$Primary; break; case T$TemplateTail: result = new LiteralTemplate([this.val]); this.nextToken(); context = C$Primary; break; case T$TemplateContinuation: result = this.parseTemplate(0); context = C$Primary; break; case T$NumericLiteral: { result = new LiteralPrimitive(this.val); this.nextToken(); break; } case T$NullKeyword: case T$UndefinedKeyword: case T$TrueKeyword: case T$FalseKeyword: result = new LiteralPrimitive(TokenValues[this.tkn & T$TokenMask]); this.nextToken(); context = C$Primary; break; default: if (this.idx >= this.len) { this.err('Unexpected end of expression'); } else { this.err(); } } if (context & C$ShorthandProp) { return result; } let name = this.val; while (this.tkn & T$MemberOrCallExpression) { switch (this.tkn) { case T$Period: this.nextToken(); if (!(this.tkn & T$IdentifierOrKeyword)) { this.err(); } name = this.val; this.nextToken(); context = context & C$Primary | (context & (C$This | C$Scope)) << 1 | context & C$Member | (context & C$Keyed) >> 1 | (context & C$Call) >> 2; if (this.tkn === T$LParen) { continue; } if (context & C$Scope) { result = new AccessScope(name, result.ancestor); } else { result = new AccessMember(result, name); } continue; case T$LBracket: this.nextToken(); context = C$Keyed; result = new AccessKeyed(result, this.parseExpression()); this.expect(T$RBracket); break; case T$LParen: this.nextToken(); const args = []; while (this.tkn !== T$RParen) { args.push(this.parseExpression()); if (!this.opt(T$Comma)) { break; } } this.expect(T$RParen); if (context & C$Scope) { result = new CallScope(name, args, result.ancestor); } else if (context & (C$Member | C$Primary)) { result = new CallMember(result, name, args); } else { result = new CallFunction(result, args); } context = C$Call; break; case T$TemplateTail: result = new LiteralTemplate([this.val], [], [this.raw], result); this.nextToken(); break; case T$TemplateContinuation: result = this.parseTemplate(context | C$Tagged, result); } } return result; } parseTemplate(context, func) { const cooked = [this.val]; const raw = context & C$Tagged ? [this.raw] : undefined; this.expect(T$TemplateContinuation); const expressions = [this.parseExpression()]; while ((this.tkn = this.scanTemplateTail()) !== T$TemplateTail) { cooked.push(this.val); if (context & C$Tagged) { raw.push(this.raw); } this.expect(T$TemplateContinuation); expressions.push(this.parseExpression()); } cooked.push(this.val); if (context & C$Tagged) { raw.push(this.raw); } this.nextToken(); return new LiteralTemplate(cooked, expressions, raw, func); } nextToken() { while (this.idx < this.len) { if (this.ch <= 0x20) { this.next(); continue; } this.start = this.idx; if (this.ch === 0x24 || this.ch >= 0x61 && this.ch <= 0x7A) { this.tkn = this.scanIdentifier(); return; } if ((this.tkn = CharScanners[this.ch](this)) !== null) { return; } } this.tkn = T$EOF; } next() { return this.ch = this.src.charCodeAt(++this.idx); } scanIdentifier() { while (AsciiIdParts.has(this.next()) || this.ch > 0x7F && IdParts[this.ch]) {} return KeywordLookup[this.val = this.raw] || T$Identifier; } scanNumber(isFloat) { if (isFloat) { this.val = 0; } else { this.val = this.ch - 0x30; while (this.next() <= 0x39 && this.ch >= 0x30) { this.val = this.val * 10 + this.ch - 0x30; } } if (isFloat || this.ch === 0x2E) { if (!isFloat) { this.next(); } const start = this.idx; let value = this.ch - 0x30; while (this.next() <= 0x39 && this.ch >= 0x30) { value = value * 10 + this.ch - 0x30; } this.val = this.val + value / Math.pow(10, this.idx - start); } if (this.ch === 0x65 || this.ch === 0x45) { const start = this.idx; this.next(); if (this.ch === 0x2D || this.ch === 0x2B) { this.next(); } if (!(this.ch >= 0x30 && this.ch <= 0x39)) { this.idx = start; this.err('Invalid exponent'); } while (this.next() <= 0x39 && this.ch >= 0x30) {} this.val = parseFloat(this.src.slice(this.start, this.idx)); } return T$NumericLiteral; } scanString() { let quote = this.ch; this.next(); let buffer; let marker = this.idx; while (this.ch !== quote) { if (this.ch === 0x5C) { if (!buffer) { buffer = []; } buffer.push(this.src.slice(marker, this.idx)); this.next(); let unescaped; if (this.ch === 0x75) { this.next(); if (this.idx + 4 < this.len) { let hex = this.src.slice(this.idx, this.idx + 4); if (!/[A-Z0-9]{4}/i.test(hex)) { this.err(`Invalid unicode escape [\\u${hex}]`); } unescaped = parseInt(hex, 16); this.idx += 4; this.ch = this.src.charCodeAt(this.idx); } else { this.err(); } } else { unescaped = unescape(this.ch); this.next(); } buffer.push(fromCharCode(unescaped)); marker = this.idx; } else if (this.ch === 0 || this.idx >= this.len) { this.err('Unterminated quote'); } else { this.next(); } } let last = this.src.slice(marker, this.idx); this.next(); let unescaped = last; if (buffer !== null && buffer !== undefined) { buffer.push(last); unescaped = buffer.join(''); } this.val = unescaped; return T$StringLiteral; } scanTemplate() { let tail = true; let result = ''; while (this.next() !== 0x60) { if (this.ch === 0x24) { if (this.idx + 1 < this.len && this.src.charCodeAt(this.idx + 1) === 0x7B) { this.idx++; tail = false; break; } else { result += '$'; } } else if (this.ch === 0x5C) { result += fromCharCode(unescape(this.next())); } else if (this.ch === 0 || this.idx >= this.len) { this.err('Unterminated template literal'); } else { result += fromCharCode(this.ch); } } this.next(); this.val = result; if (tail) { return T$TemplateTail; } return T$TemplateContinuation; } scanTemplateTail() { if (this.idx >= this.len) { this.err('Unterminated template'); } this.idx--; return this.scanTemplate(); } err(message = `Unexpected token ${this.raw}`, column = this.start) { throw new Error(`Parser Error: ${message} at column ${column} in expression [${this.src}]`); } opt(token) { if (this.tkn === token) { this.nextToken(); return true; } return false; } expect(token) { if (this.tkn === token) { this.nextToken(); } else { this.err(`Missing expected token ${TokenValues[token & T$TokenMask]}`, this.idx); } } }; function unescape(code) { switch (code) { case 0x66: return 0xC; case 0x6E: return 0xA; case 0x72: return 0xD; case 0x74: return 0x9; case 0x76: return 0xB; default: return code; } } const C$This = 1 << 10; const C$Scope = 1 << 11; const C$Member = 1 << 12; const C$Keyed = 1 << 13; const C$Call = 1 << 14; const C$Primary = 1 << 15; const C$ShorthandProp = 1 << 16; const C$Tagged = 1 << 17; const C$Ancestor = (1 << 9) - 1; const T$TokenMask = (1 << 6) - 1; const T$PrecShift = 6; const T$Precedence = 7 << T$PrecShift; const T$ExpressionTerminal = 1 << 11; const T$ClosingToken = 1 << 12; const T$OpeningToken = 1 << 13; const T$AccessScopeTerminal = 1 << 14; const T$Keyword = 1 << 15; const T$EOF = 1 << 16 | T$AccessScopeTerminal | T$ExpressionTerminal; const T$Identifier = 1 << 17; const T$IdentifierOrKeyword = T$Identifier | T$Keyword; const T$Literal = 1 << 18; const T$NumericLiteral = 1 << 19 | T$Literal; const T$StringLiteral = 1 << 20 | T$Literal; const T$BinaryOp = 1 << 21; const T$UnaryOp = 1 << 22; const T$MemberExpression = 1 << 23; const T$MemberOrCallExpression = 1 << 24; const T$TemplateTail = 1 << 25 | T$MemberOrCallExpression; const T$TemplateContinuation = 1 << 26 | T$MemberOrCallExpression; const T$FalseKeyword = 0 | T$Keyword | T$Literal; const T$TrueKeyword = 1 | T$Keyword | T$Literal; const T$NullKeyword = 2 | T$Keyword | T$Literal; const T$UndefinedKeyword = 3 | T$Keyword | T$Literal; const T$ThisScope = 4 | T$IdentifierOrKeyword; const T$ParentScope = 5 | T$IdentifierOrKeyword; const T$LParen = 6 | T$OpeningToken | T$AccessScopeTerminal | T$MemberOrCallExpression; const T$LBrace = 7 | T$OpeningToken; const T$Period = 8 | T$MemberExpression | T$MemberOrCallExpression; const T$RBrace = 9 | T$AccessScopeTerminal | T$ClosingToken | T$ExpressionTerminal; const T$RParen = 10 | T$AccessScopeTerminal | T$ClosingToken | T$ExpressionTerminal; const T$Comma = 11 | T$AccessScopeTerminal; const T$LBracket = 12 | T$OpeningToken | T$AccessScopeTerminal | T$MemberExpression | T$MemberOrCallExpression; const T$RBracket = 13 | T$ClosingToken | T$ExpressionTerminal; const T$Colon = 14 | T$AccessScopeTerminal; const T$Question = 15; const T$Ampersand = 18 | T$AccessScopeTerminal; const T$Bar = 19 | T$AccessScopeTerminal; const T$BarBar = 20 | 1 << T$PrecShift | T$BinaryOp; const T$AmpersandAmpersand = 21 | 2 << T$PrecShift | T$BinaryOp; const T$Caret = 22 | 3 << T$PrecShift | T$BinaryOp; const T$EqEq = 23 | 4 << T$PrecShift | T$BinaryOp; const T$BangEq = 24 | 4 << T$PrecShift | T$BinaryOp; const T$EqEqEq = 25 | 4 << T$PrecShift | T$BinaryOp; const T$BangEqEq = 26 | 4 << T$PrecShift | T$BinaryOp; const T$Lt = 27 | 5 << T$PrecShift | T$BinaryOp; const T$Gt = 28 | 5 << T$PrecShift | T$BinaryOp; const T$LtEq = 29 | 5 << T$PrecShift | T$BinaryOp; const T$GtEq = 30 | 5 << T$PrecShift | T$BinaryOp; const T$InKeyword = 31 | 5 << T$PrecShift | T$BinaryOp | T$Keyword; const T$InstanceOfKeyword = 32 | 5 << T$PrecShift | T$BinaryOp | T$Keyword; const T$Plus = 33 | 6 << T$PrecShift | T$BinaryOp | T$UnaryOp; const T$Minus = 34 | 6 << T$PrecShift | T$BinaryOp | T$UnaryOp; const T$TypeofKeyword = 35 | T$UnaryOp | T$Keyword; const T$VoidKeyword = 36 | T$UnaryOp | T$Keyword; const T$Star = 37 | 7 << T$PrecShift | T$BinaryOp; const T$Percent = 38 | 7 << T$PrecShift | T$BinaryOp; const T$Slash = 39 | 7 << T$PrecShift | T$BinaryOp; const T$Eq = 40; const T$Bang = 41 | T$UnaryOp; const KeywordLookup = Object.create(null); KeywordLookup.true = T$TrueKeyword; KeywordLookup.null = T$NullKeyword; KeywordLookup.false = T$FalseKeyword; KeywordLookup.undefined = T$UndefinedKeyword; KeywordLookup.$this = T$ThisScope; KeywordLookup.$parent = T$ParentScope; KeywordLookup.in = T$InKeyword; KeywordLookup.instanceof = T$InstanceOfKeyword; KeywordLookup.typeof = T$TypeofKeyword; KeywordLookup.void = T$VoidKeyword; const TokenValues = [false, true, null, undefined, '$this', '$parent', '(', '{', '.', '}', ')', ',', '[', ']', ':', '?', '\'', '"', '&', '|', '||', '&&', '^', '==', '!=', '===', '!==', '<', '>', '<=', '>=', 'in', 'instanceof', '+', '-', 'typeof', 'void', '*', '%', '/', '=', '!']; const codes = { AsciiIdPart: [0x24, 0, 0x30, 0x3A, 0x41, 0x5B, 0x5F, 0, 0x61, 0x7B], IdStart: [0x24, 0, 0x41, 0x5B, 0x5F, 0, 0x61, 0x7B, 0xAA, 0, 0xBA, 0, 0xC0, 0xD7, 0xD8, 0xF7, 0xF8, 0x2B9, 0x2E0, 0x2E5, 0x1D00, 0x1D26, 0x1D2C, 0x1D5D, 0x1D62, 0x1D66, 0x1D6B, 0x1D78, 0x1D79, 0x1DBF, 0x1E00, 0x1F00, 0x2071, 0, 0x207F, 0, 0x2090, 0x209D, 0x212A, 0x212C, 0x2132, 0, 0x214E, 0, 0x2160, 0x2189, 0x2C60, 0x2C80, 0xA722, 0xA788, 0xA78B, 0xA7AF, 0xA7B0, 0xA7B8, 0xA7F7, 0xA800, 0xAB30, 0xAB5B, 0xAB5C, 0xAB65, 0xFB00, 0xFB07, 0xFF21, 0xFF3B, 0xFF41, 0xFF5B], Digit: [0x30, 0x3A], Skip: [0, 0x21, 0x7F, 0xA1] }; function decompress(lookup, set, compressed, value) { let rangeCount = compressed.length; for (let i = 0; i < rangeCount; i += 2) { const start = compressed[i]; let end = compressed[i + 1]; end = end > 0 ? end : start + 1; if (lookup) { let j = start; while (j < end) { lookup[j] = value; j++; } } if (set) { for (let ch = start; ch < end; ch++) { set.add(ch); } } } } function returnToken(token) { return p => { p.next(); return token; }; } function unexpectedCharacter(p) { p.err(`Unexpected character [${fromCharCode(p.ch)}]`); return null; } const AsciiIdParts = new Set(); decompress(null, AsciiIdParts, codes.AsciiIdPart, true); const IdParts = new Uint8Array(0xFFFF); decompress(IdParts, null, codes.IdStart, 1); decompress(IdParts, null, codes.Digit, 1); const CharScanners = new Array(0xFFFF); let ci = 0; while (ci < 0xFFFF) { CharScanners[ci] = unexpectedCharacter; ci++; } decompress(CharScanners, null, codes.Skip, p => { p.next(); return null; }); decompress(CharScanners, null, codes.IdStart, p => p.scanIdentifier()); decompress(CharScanners, null, codes.Digit, p => p.scanNumber(false)); CharScanners[0x22] = CharScanners[0x27] = p => { return p.scanString(); }; CharScanners[0x60] = p => { return p.scanTemplate(); }; CharScanners[0x21] = p => { if (p.next() !== 0x3D) { return T$Bang; } if (p.next() !== 0x3D) { return T$BangEq; } p.next(); return T$BangEqEq; }; CharScanners[0x3D] = p => { if (p.next() !== 0x3D) { return T$Eq; } if (p.next() !== 0x3D) { return T$EqEq; } p.next(); return T$EqEqEq; }; CharScanners[0x26] = p => { if (p.next() !== 0x26) { return T$Ampersand; } p.next(); return T$AmpersandAmpersand; }; CharScanners[0x7C] = p => { if (p.next() !== 0x7C) { return T$Bar; } p.next(); return T$BarBar; }; CharScanners[0x2E] = p => { if (p.next() <= 0x39 && p.ch >= 0x30) { return p.scanNumber(true); } return T$Period; }; CharScanners[0x3C] = p => { if (p.next() !== 0x3D) { return T$Lt; } p.next(); return T$LtEq; }; CharScanners[0x3E] = p => { if (p.next() !== 0x3D) { return T$Gt; } p.next(); return T$GtEq; }; CharScanners[0x25] = returnToken(T$Percent); CharScanners[0x28] = returnToken(T$LParen); CharScanners[0x29] = returnToken(T$RParen); CharScanners[0x2A] = returnToken(T$Star); CharScanners[0x2B] = returnToken(T$Plus); CharScanners[0x2C] = returnToken(T$Comma); CharScanners[0x2D] = returnToken(T$Minus); CharScanners[0x2F] = returnToken(T$Slash); CharScanners[0x3A] = returnToken(T$Colon); CharScanners[0x3F] = returnToken(T$Question); CharScanners[0x5B] = returnToken(T$LBracket); CharScanners[0x5D] = returnToken(T$RBracket); CharScanners[0x5E] = returnToken(T$Caret); CharScanners[0x7B] = returnToken(T$LBrace); CharScanners[0x7D] = returnToken(T$RBrace); let mapProto = Map.prototype; function getMapObserver(taskQueue, map) { return ModifyMapObserver.for(taskQueue, map); } let ModifyMapObserver = class ModifyMapObserver extends ModifyCollectionObserver { constructor(taskQueue, map) { super(taskQueue, map); } static for(taskQueue, map) { if (!('__map_observer__' in map)) { Reflect.defineProperty(map, '__map_observer__', { value: ModifyMapObserver.create(taskQueue, map), enumerable: false, configurable: false }); } return map.__map_observer__; } static create(taskQueue, map) { let observer = new ModifyMapObserver(taskQueue, map); let proto = mapProto; if (proto.set !== map.set || proto.delete !== map.delete || proto.clear !== map.clear) { proto = { set: map.set, delete: map.delete, clear: map.clear }; } map.set = function () { let hasValue = map.has(arguments[0]); let type = hasValue ? 'update' : 'add'; let oldValue = map.get(arguments[0]); let methodCallResult = proto.set.apply(map, arguments); if (!hasValue || oldValue !== map.get(arguments[0])) { observer.addChangeRecord({ type: type, object: map, key: arguments[0], oldValue: oldValue }); } return methodCallResult; }; map.delete = function () { let hasValue = map.has(arguments[0]); let oldValue = map.get(arguments[0]); let methodCallResult = proto.delete.apply(map, arguments); if (hasValue) { observer.addChangeRecord({ type: 'delete', object: map, key: arguments[0], oldValue: oldValue }); } return methodCallResult; }; map.clear = function () { let methodCallResult = proto.clear.apply(map, arguments); observer.addChangeRecord({ type: 'clear', object: map }); return methodCallResult; }; return observer; } }; function findOriginalEventTarget(event) { return event.path && event.path[0] || event.deepPath && event.deepPath[0] || event.target; } function stopPropagation() { this.standardStopPropagation(); this.propagationStopped = true; } function handleCapturedEvent(event) { event.propagationStopped = false; let target = findOriginalEventTarget(event); let orderedCallbacks = []; while (target) { if (target.capturedCallbacks) { let callback = target.capturedCallbacks[event.type]; if (callback) { if (event.stopPropagation !== stopPropagation) { event.standardStopPropagation = event.stopPropagation; event.stopPropagation = stopPropagation; } orderedCallbacks.push(callback); } } target = target.parentNode; } for (let i = orderedCallbacks.length - 1; i >= 0 && !event.propagationStopped; i--) { let orderedCallback = orderedCallbacks[i]; if ('handleEvent' in orderedCallback) { orderedCallback.handleEvent(event); } else { orderedCallback(event); } } } let CapturedHandlerEntry = class CapturedHandlerEntry { constructor(eventName) { this.eventName = eventName; this.count = 0; } increment() { this.count++; if (this.count === 1) { DOM.addEventListener(this.eventName, handleCapturedEvent, true); } } decrement() { this.count--; if (this.count === 0) { DOM.removeEventListener(this.eventName, handleCapturedEvent, true); } } }; function handleDelegatedEvent(event) { event.propagationStopped = false; let target = findOriginalEventTarget(event); while (target && !event.propagationStopped) { if (target.delegatedCallbacks) { let callback = target.delegatedCallbacks[event.type]; if (callback) { if (event.stopPropagation !== stopPropagation) { event.standardStopPropagation = event.stopPropagation; event.stopPropagation = stopPropagation; } if ('handleEvent' in callback) { callback.handleEvent(event); } else { callback(event); } } } target = target.parentNode; } } let DelegateHandlerEntry = class DelegateHandlerEntry { constructor(eventName) { this.eventName = eventName; this.count = 0; } increment() { this.count++; if (this.count === 1) { DOM.addEventListener(this.eventName, handleDelegatedEvent, false); } } decrement() { this.count--; if (this.count === 0) { DOM.removeEventListener(this.eventName, handleDelegatedEvent, false); } } }; let DelegationEntryHandler = class DelegationEntryHandler { constructor(entry, lookup, targetEvent) { this.entry = entry; this.lookup = lookup; this.targetEvent = targetEvent; } dispose() { this.entry.decrement(); this.lookup[this.targetEvent] = null; } }; let EventHandler = class EventHandler { constructor(target, targetEvent, callback) { this.target = target; this.targetEvent = targetEvent; this.callback = callback; } dispose() { this.target.removeEventListener(this.targetEvent, this.callback); } }; let DefaultEventStrategy = class DefaultEventStrategy { constructor() { this.delegatedHandlers = {}; this.capturedHandlers = {}; } subscribe(target, targetEvent, callback, strategy, disposable) { let delegatedHandlers; let capturedHandlers; let handlerEntry; if (strategy === delegationStrategy.bubbling) { delegatedHandlers = this.delegatedHandlers; handlerEntry = delegatedHandlers[targetEvent] || (delegatedHandlers[targetEvent] = new DelegateHandlerEntry(targetEvent)); let delegatedCallbacks = target.delegatedCallbacks || (target.delegatedCallbacks = {}); handlerEntry.increment(); delegatedCallbacks[targetEvent] = callback; if (disposable === true) { return new DelegationEntryHandler(handlerEntry, delegatedCallbacks, targetEvent); } return function () { handlerEntry.decrement(); delegatedCallbacks[targetEvent] = null; }; } if (strategy === delegationStrategy.capturing) { capturedHandlers = this.capturedHandlers; handlerEntry = capturedHandlers[targetEvent] || (capturedHandlers[targetEvent] = new CapturedHandlerEntry(targetEvent)); let capturedCallbacks = target.capturedCallbacks || (target.capturedCallbacks = {}); handlerEntry.increment(); capturedCallbacks[targetEvent] = callback; if (disposable === true) { return new DelegationEntryHandler(handlerEntry, capturedCallbacks, targetEvent); } return function () { handlerEntry.decrement(); capturedCallbacks[targetEvent] = null; }; } target.addEventListener(targetEvent, callback); if (disposable === true) { return new EventHandler(target, targetEvent, callback); } return function () { target.removeEventListener(targetEvent, callback); }; } }; const delegationStrategy = { none: 0, capturing: 1, bubbling: 2 }; let EventManager = class EventManager { constructor() { this.elementHandlerLookup = {}; this.eventStrategyLookup = {}; this.registerElementConfig({ tagName: 'input', properties: { value: ['change', 'input'], checked: ['change', 'input'], files: ['change', 'input'] } }); this.registerElementConfig({ tagName: 'textarea', properties: { value: ['change', 'input'] } }); this.registerElementConfig({ tagName: 'select', properties: { value: ['change'] } }); this.registerElementConfig({ tagName: 'content editable', properties: { value: ['change', 'input', 'blur', 'keyup', 'paste'] } }); this.registerElementConfig({ tagName: 'scrollable element', properties: { scrollTop: ['scroll'], scrollLeft: ['scroll'] } }); this.defaultEventStrategy = new DefaultEventStrategy(); } registerElementConfig(config) { let tagName = config.tagName.toLowerCase(); let properties = config.properties; let propertyName; let lookup = this.elementHandlerLookup[tagName] = {}; for (propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { lookup[propertyName] = properties[propertyName]; } } } registerEventStrategy(eventName, strategy) { this.eventStrategyLookup[eventName] = strategy; } getElementHandler(target, propertyName) { let tagName; let lookup = this.elementHandlerLookup; if (target.tagName) { tagName = target.tagName.toLowerCase(); if (lookup[tagName] && lookup[tagName][propertyName]) { return new EventSubscriber(lookup[tagName][propertyName]); } if (propertyName === 'textContent' || propertyName === 'innerHTML') { return new EventSubscriber(lookup['content editable'].value); } if (propertyName === 'scrollTop' || propertyName === 'scrollLeft') { return new EventSubscriber(lookup['scrollable element'][propertyName]); } } return null; } addEventListener(target, targetEvent, callbackOrListener, delegate, disposable) { return (this.eventStrategyLookup[targetEvent] || this.defaultEventStrategy).subscribe(target, targetEvent, callbackOrListener, delegate, disposable); } }; let EventSubscriber = class EventSubscriber { constructor(events) { this.events = events; this.element = null; this.handler = null; } subscribe(element, callbackOrListener) { this.element = element; this.handler = callbackOrListener; let events = this.events; for (let i = 0, ii = events.length; ii > i; ++i) { element.addEventListener(events[i], callbackOrListener); } } dispose() { if (this.element === null) { return; } let element = this.element; let callbackOrListener = this.handler; let events = this.events; for (let i = 0, ii = events.length; ii > i; ++i) { element.removeEventListener(events[i], callbackOrListener); } this.element = this.handler = null; } }; let DirtyChecker = class DirtyChecker { constructor() { this.tracked = []; this.checkDelay = 120; } addProperty(property) { let tracked = this.tracked; tracked.push(property); if (tracked.length === 1) { this.scheduleDirtyCheck(); } } removeProperty(property) { let tracked = this.tracked; tracked.splice(tracked.indexOf(property), 1); } scheduleDirtyCheck() { setTimeout(() => this.check(), this.checkDelay); } check() { let tracked = this.tracked; let i = tracked.length; while (i--) { let current = tracked[i]; if (current.isDirty()) { current.call(); } } if (tracked.length) { this.scheduleDirtyCheck(); } } }; let DirtyCheckProperty = (_dec5$1 = subscriberCollection(), _dec5$1(_class5$1 = class DirtyCheckProperty { constructor(dirtyChecker, obj, propertyName) { this.dirtyChecker = dirtyChecker; this.obj = obj; this.propertyName = propertyName; } getValue() { return this.obj[this.propertyName]; } setValue(newValue) { this.obj[this.propertyName] = newValue; } call() { let oldValue = this.oldValue; let newValue = this.getValue(); this.callSubscribers(newValue, oldValue); this.oldValue = newValue; } isDirty() { return this.oldValue !== this.obj[this.propertyName]; } subscribe(context, callable) { if (!this.hasSubscribers()) { this.oldValue = this.getValue(); this.dirtyChecker.addProperty(this); } this.addSubscriber(context, callable); } unsubscribe(context, callable) { if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) { this.dirtyChecker.removeProperty(this); } } }) || _class5$1); const logger = getLogger('property-observation'); const propertyAccessor = { getValue: (obj, propertyName) => obj[propertyName], setValue: (value, obj, propertyName) => { obj[propertyName] = value; } }; let PrimitiveObserver = class PrimitiveObserver { constructor(primitive, propertyName) { this.doNotCache = true; this.primitive = primitive; this.propertyName = propertyName; } getValue() { return this.primitive[this.propertyName]; } setValue() { let type = typeof this.primitive; throw new Error(`The ${this.propertyName} property of a ${type} (${this.primitive}) cannot be assigned.`); } subscribe() {} unsubscribe() {} }; let SetterObserver = (_dec6$1 = subscriberCollection(), _dec6$1(_class7$1 = class SetterObserver { constructor(taskQueue, obj, propertyName) { this.taskQueue = taskQueue; this.obj = obj; this.propertyName = propertyName; this.queued = false; this.observing = false; } getValue() { return this.obj[this.propertyName]; } setValue(newValue) { this.obj[this.propertyName] = newValue; } getterValue() { return this.currentValue; } setterValue(newValue) { let oldValue = this.currentValue; if (oldValue !== newValue) { if (!this.queued) { this.oldValue = oldValue; this.queued = true; this.taskQueue.queueMicroTask(this); } this.currentValue = newValue; } } call() { let oldValue = this.oldValue; let newValue = this.currentValue; this.queued = false; this.callSubscribers(newValue, oldValue); } subscribe(context, callable) { if (!this.observing) { this.convertProperty(); } this.addSubscriber(context, callable); } unsubscribe(context, callable) { this.removeSubscriber(context, callable); } convertProperty() { this.observing = true; this.currentValue = this.obj[this.propertyName]; this.setValue = this.setterValue; this.getValue = this.getterValue; if (!Reflect.defineProperty(this.obj, this.propertyName, { configurable: true, enumerable: this.propertyName in this.obj ? this.obj.propertyIsEnumerable(this.propertyName) : true, get: this.getValue.bind(this), set: this.setValue.bind(this) })) { logger.warn(`Cannot observe property '${this.propertyName}' of object`, this.obj); } } }) || _class7$1); let XLinkAttributeObserver = class XLinkAttributeObserver { constructor(element, propertyName, attributeName) { this.element = element; this.propertyName = propertyName; this.attributeName = attributeName; } getValue() { return this.element.getAttributeNS('http://www.w3.org/1999/xlink', this.attributeName); } setValue(newValue) { return this.element.setAttributeNS('http://www.w3.org/1999/xlink', this.attributeName, newValue); } subscribe() { throw new Error(`Observation of a "${this.element.nodeName}" element\'s "${this.propertyName}" property is not supported.`); } }; const dataAttributeAccessor = { getValue: (obj, propertyName) => obj.getAttribute(propertyName), setValue: (value, obj, propertyName) => { if (value === null || value === undefined) { obj.removeAttribute(propertyName); } else { obj.setAttribute(propertyName, value); } } }; let DataAttributeObserver = class DataAttributeObserver { constructor(element, propertyName) { this.element = element; this.propertyName = propertyName; } getValue() { return this.element.getAttribute(this.propertyName); } setValue(newValue) { if (newValue === null || newValue === undefined) { return this.element.removeAttribute(this.propertyName); } return this.element.setAttribute(this.propertyName, newValue); } subscribe() { throw new Error(`Observation of a "${this.element.nodeName}" element\'s "${this.propertyName}" property is not supported.`); } }; let StyleObserver = class StyleObserver { constructor(element, propertyName) { this.element = element; this.propertyName = propertyName; this.styles = null; this.version = 0; } getValue() { return this.element.style.cssText; } _setProperty(style, value) { let priority = ''; if (value !== null && value !== undefined && typeof value.indexOf === 'function' && value.indexOf('!important') !== -1) { priority = 'important'; value = value.replace('!important', ''); } this.element.style.setProperty(style, value, priority); } setValue(newValue) { let styles = this.styles || {}; let style; let version = this.version; if (newValue !== null && newValue !== undefined) { if (newValue instanceof Object) { let value; for (style in newValue) { if (newValue.hasOwnProperty(style)) { value = newValue[style]; style = style.replace(/([A-Z])/g, m => '-' + m.toLowerCase()); styles[style] = version; this._setProperty(style, value); } } } else if (newValue.length) { let rx = /\s*([\w\-]+)\s*:\s*((?:(?:[\w\-]+\(\s*(?:"(?:\\"|[^"])*"|'(?:\\'|[^'])*'|[\w\-]+\(\s*(?:^"(?:\\"|[^"])*"|'(?:\\'|[^'])*'|[^\)]*)\),?|[^\)]*)\),?|"(?:\\"|[^"])*"|'(?:\\'|[^'])*'|[^;]*),?\s*)+);?/g; let pair; while ((pair = rx.exec(newValue)) !== null) { style = pair[1]; if (!style) { continue; } styles[style] = version; this._setProperty(style, pair[2]); } } } this.styles = styles; this.version += 1; if (version === 0) { return; } version -= 1; for (style in styles) { if (!styles.hasOwnProperty(style) || styles[style] !== version) { continue; } this.element.style.removeProperty(style); } } subscribe() { throw new Error(`Observation of a "${this.element.nodeName}" element\'s "${this.propertyName}" property is not supported.`); } }; let ValueAttributeObserver = (_dec7$1 = subscriberCollection(), _dec7$1(_class8 = class ValueAttributeObserver { constructor(element, propertyName, handler) { this.element = element; this.propertyName = propertyName; this.handler = handler; if (propertyName === 'files') { this.setValue = () => {}; } } getValue() { return this.element[this.propertyName]; } setValue(newValue) { newValue = newValue === undefined || newValue === null ? '' : newValue; if (this.element[this.propertyName] !== newValue) { this.element[this.propertyName] = newValue; this.notify(); } } notify() { let oldValue = this.oldValue; let newValue = this.getValue(); this.callSubscribers(newValue, oldValue); this.oldValue = newValue; } handleEvent() { this.notify(); } subscribe(context, callable) { if (!this.hasSubscribers()) { this.oldValue = this.getValue(); this.handler.subscribe(this.element, this); } this.addSubscriber(context, callable); } unsubscribe(context, callable) { if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) { this.handler.dispose(); } } }) || _class8); const checkedArrayContext = 'CheckedObserver:array'; const checkedValueContext = 'CheckedObserver:value'; let CheckedObserver = (_dec8 = subscriberCollection(), _dec8(_class9 = class CheckedObserver { constructor(element, handler, observerLocator) { this.element = element; this.handler = handler; this.observerLocator = observerLocator; } getValue() { return this.value; } setValue(newValue) { if (this.initialSync && this.value === newValue) { return; } if (this.arrayObserver) { this.arrayObserver.unsubscribe(checkedArrayContext, this); this.arrayObserver = null; } if (this.element.type === 'checkbox' && Array.isArray(newValue)) { this.arrayObserver = this.observerLocator.getArrayObserver(newValue); this.arrayObserver.subscribe(checkedArrayContext, this); } this.oldValue = this.value; this.value = newValue; this.synchronizeElement(); this.notify(); if (!this.initialSync) { this.initialSync = true; this.observerLocator.taskQueue.queueMicroTask(this); } } call(context, splices) { this.synchronizeElement(); if (!this.valueObserver) { this.valueObserver = this.element.__observers__.model || this.element.__observers__.value; if (this.valueObserver) { this.valueObserver.subscribe(checkedValueContext, this); } } } synchronizeElement() { let value = this.value; let element = this.element; let elementValue = element.hasOwnProperty('model') ? element.model : element.value; let isRadio = element.type === 'radio'; let matcher = element.matcher || ((a, b) => a === b); element.checked = isRadio && !!matcher(value, elementValue) || !isRadio && value === true || !isRadio && Array.isArray(value) && value.findIndex(item => !!matcher(item, elementValue)) !== -1; } synchronizeValue() { let value = this.value; let element = this.element; let elementValue = element.hasOwnProperty('model') ? element.model : element.value; let index; let matcher = element.matcher || ((a, b) => a === b); if (element.type === 'checkbox') { if (Array.isArray(value)) { index = value.findIndex(item => !!matcher(item, elementValue)); if (element.checked && index === -1) { value.push(elementValue); } else if (!element.checked && index !== -1) { value.splice(index, 1); } return; } value = element.checked; } else if (element.checked) { value = elementValue; } else { return; } this.oldValue = this.value; this.value = value; this.notify(); } notify() { let oldValue = this.oldValue; let newValue = this.value; if (newValue === oldValue) { return; } this.callSubscribers(newValue, oldValue); } handleEvent() { this.synchronizeValue(); } subscribe(context, callable) { if (!this.hasSubscribers()) { this.handler.subscribe(this.element, this); } this.addSubscriber(context, callable); } unsubscribe(context, callable) { if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) { this.handler.dispose(); } } unbind() { if (this.arrayObserver) { this.arrayObserver.unsubscribe(checkedArrayContext, this); this.arrayObserver = null; } if (this.valueObserver) { this.valueObserver.unsubscribe(checkedValueContext, this); } } }) || _class9); const selectArrayContext = 'SelectValueObserver:array'; let SelectValueObserver = (_dec9 = subscriberCollection(), _dec9(_class10 = class SelectValueObserver { constructor(element, handler, observerLocator) { this.element = element; this.handler = handler; this.observerLocator = observerLocator; } getValue() { return this.value; } setValue(newValue) { if (newValue !== null && newValue !== undefined && this.element.multiple && !Array.isArray(newValue)) { throw new Error('Only null or Array instances can be bound to a multi-select.'); } if (this.value === newValue) { return; } if (this.arrayObserver) { this.arrayObserver.unsubscribe(selectArrayContext, this); this.arrayObserver = null; } if (Array.isArray(newValue)) { this.arrayObserver = this.observerLocator.getArrayObserver(newValue); this.arrayObserver.subscribe(selectArrayContext, this); } this.oldValue = this.value; this.value = newValue; this.synchronizeOptions(); this.notify(); if (!this.initialSync) { this.initialSync = true; this.observerLocator.taskQueue.queueMicroTask(this); } } call(context, splices) { this.synchronizeOptions(); } synchronizeOptions() { let value = this.value; let isArray; if (Array.isArray(value)) { isArray = true; } let options = this.element.options; let i = options.length; let matcher = this.element.matcher || ((a, b) => a === b); while (i--) { let option = options.item(i); let optionValue = option.hasOwnProperty('model') ? option.model : option.value; if (isArray) { option.selected = value.findIndex(item => !!matcher(optionValue, item)) !== -1; continue; } option.selected = !!matcher(optionValue, value); } } synchronizeValue() { let options = this.element.options; let count = 0; let value = []; for (let i = 0, ii = options.length; i < ii; i++) { let option = options.item(i); if (!option.selected) { continue; } value.push(option.hasOwnProperty('model') ? option.model : option.value); count++; } if (this.element.multiple) { if (Array.isArray(this.value)) { let matcher = this.element.matcher || ((a, b) => a === b); let i = 0; while (i < this.value.length) { let a = this.value[i]; if (value.findIndex(b => matcher(a, b)) === -1) { this.value.splice(i, 1); } else { i++; } } i = 0; while (i < value.length) { let a = value[i]; if (this.value.findIndex(b => matcher(a, b)) === -1) { this.value.push(a); } i++; } return; } } else { if (count === 0) { value = null; } else { value = value[0]; } } if (value !== this.value) { this.oldValue = this.value; this.value = value; this.notify(); } } notify() { let oldValue = this.oldValue; let newValue = this.value; this.callSubscribers(newValue, oldValue); } handleEvent() { this.synchronizeValue(); } subscribe(context, callable) { if (!this.hasSubscribers()) { this.handler.subscribe(this.element, this); } this.addSubscriber(context, callable); } unsubscribe(context, callable) { if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) { this.handler.dispose(); } } bind() { this.domObserver = DOM.createMutationObserver(() => { this.synchronizeOptions(); this.synchronizeValue(); }); this.domObserver.observe(this.element, { childList: true, subtree: true, characterData: true }); } unbind() { this.domObserver.disconnect(); this.domObserver = null; if (this.arrayObserver) { this.arrayObserver.unsubscribe(selectArrayContext, this); this.arrayObserver = null; } } }) || _class10); let ClassObserver = class ClassObserver { constructor(element) { this.element = element; this.doNotCache = true; this.value = ''; this.version = 0; } getValue() { return this.value; } setValue(newValue) { let nameIndex = this.nameIndex || {}; let version = this.version; let names; let name; if (newValue !== null && newValue !== undefined && newValue.length) { names = newValue.split(/\s+/); for (let i = 0, length = names.length; i < length; i++) { name = names[i]; if (name === '') { continue; } nameIndex[name] = version; this.element.classList.add(name); } } this.value = newValue; this.nameIndex = nameIndex; this.version += 1; if (version === 0) { return; } version -= 1; for (name in nameIndex) { if (!nameIndex.hasOwnProperty(name) || nameIndex[name] !== version) { continue; } this.element.classList.remove(name); } } subscribe() { throw new Error(`Observation of a "${this.element.nodeName}" element\'s "class" property is not supported.`); } }; function hasDeclaredDependencies(descriptor) { return !!(descriptor && descriptor.get && descriptor.get.dependencies); } function declarePropertyDependencies(ctor, propertyName, dependencies) { let descriptor = Object.getOwnPropertyDescriptor(ctor.prototype, propertyName); descriptor.get.dependencies = dependencies; } function computedFrom(...rest) { return function (target, key, descriptor) { descriptor.get.dependencies = rest; return descriptor; }; } let ComputedExpression = class ComputedExpression extends Expression { constructor(name, dependencies) { super(); this.name = name; this.dependencies = dependencies; this.isAssignable = true; } evaluate(scope, lookupFunctions) { return scope.bindingContext[this.name]; } assign(scope, value) { scope.bindingContext[this.name] = value; } accept(visitor) { throw new Error('not implemented'); } connect(binding, scope) { let dependencies = this.dependencies; let i = dependencies.length; while (i--) { dependencies[i].connect(binding, scope); } } }; function createComputedObserver(obj, propertyName, descriptor, observerLocator) { let dependencies = descriptor.get.dependencies; if (!(dependencies instanceof ComputedExpression)) { let i = dependencies.length; while (i--) { dependencies[i] = observerLocator.parser.parse(dependencies[i]); } dependencies = descriptor.get.dependencies = new ComputedExpression(propertyName, dependencies); } let scope = { bindingContext: obj, overrideContext: createOverrideContext(obj) }; return new ExpressionObserver(scope, dependencies, observerLocator); } let svgElements; let svgPresentationElements; let svgPresentationAttributes; let svgAnalyzer; if (typeof FEATURE_NO_SVG === 'undefined') { svgElements = { a: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'target', 'transform', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], altGlyph: ['class', 'dx', 'dy', 'externalResourcesRequired', 'format', 'glyphRef', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rotate', 'style', 'systemLanguage', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], altGlyphDef: ['id', 'xml:base', 'xml:lang', 'xml:space'], altGlyphItem: ['id', 'xml:base', 'xml:lang', 'xml:space'], animate: ['accumulate', 'additive', 'attributeName', 'attributeType', 'begin', 'by', 'calcMode', 'dur', 'end', 'externalResourcesRequired', 'fill', 'from', 'id', 'keySplines', 'keyTimes', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'systemLanguage', 'to', 'values', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], animateColor: ['accumulate', 'additive', 'attributeName', 'attributeType', 'begin', 'by', 'calcMode', 'dur', 'end', 'externalResourcesRequired', 'fill', 'from', 'id', 'keySplines', 'keyTimes', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'systemLanguage', 'to', 'values', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], animateMotion: ['accumulate', 'additive', 'begin', 'by', 'calcMode', 'dur', 'end', 'externalResourcesRequired', 'fill', 'from', 'id', 'keyPoints', 'keySplines', 'keyTimes', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'origin', 'path', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'rotate', 'systemLanguage', 'to', 'values', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], animateTransform: ['accumulate', 'additive', 'attributeName', 'attributeType', 'begin', 'by', 'calcMode', 'dur', 'end', 'externalResourcesRequired', 'fill', 'from', 'id', 'keySplines', 'keyTimes', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'systemLanguage', 'to', 'type', 'values', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], circle: ['class', 'cx', 'cy', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'r', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], clipPath: ['class', 'clipPathUnits', 'externalResourcesRequired', 'id', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], 'color-profile': ['id', 'local', 'name', 'rendering-intent', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], cursor: ['externalResourcesRequired', 'id', 'requiredExtensions', 'requiredFeatures', 'systemLanguage', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], defs: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], desc: ['class', 'id', 'style', 'xml:base', 'xml:lang', 'xml:space'], ellipse: ['class', 'cx', 'cy', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rx', 'ry', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], feBlend: ['class', 'height', 'id', 'in', 'in2', 'mode', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], feColorMatrix: ['class', 'height', 'id', 'in', 'result', 'style', 'type', 'values', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], feComponentTransfer: ['class', 'height', 'id', 'in', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], feComposite: ['class', 'height', 'id', 'in', 'in2', 'k1', 'k2', 'k3', 'k4', 'operator', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], feConvolveMatrix: ['bias', 'class', 'divisor', 'edgeMode', 'height', 'id', 'in', 'kernelMatrix', 'kernelUnitLength', 'order', 'preserveAlpha', 'result', 'style', 'targetX', 'targetY', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], feDiffuseLighting: ['class', 'diffuseConstant', 'height', 'id', 'in', 'kernelUnitLength', 'result', 'style', 'surfaceScale', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], feDisplacementMap: ['class', 'height', 'id', 'in', 'in2', 'result', 'scale', 'style', 'width', 'x', 'xChannelSelector', 'xml:base', 'xml:lang', 'xml:space', 'y', 'yChannelSelector'], feDistantLight: ['azimuth', 'elevation', 'id', 'xml:base', 'xml:lang', 'xml:space'], feFlood: ['class', 'height', 'id', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], feFuncA: ['amplitude', 'exponent', 'id', 'intercept', 'offset', 'slope', 'tableValues', 'type', 'xml:base', 'xml:lang', 'xml:space'], feFuncB: ['amplitude', 'exponent', 'id', 'intercept', 'offset', 'slope', 'tableValues', 'type', 'xml:base', 'xml:lang', 'xml:space'], feFuncG: ['amplitude', 'exponent', 'id', 'intercept', 'offset', 'slope', 'tableValues', 'type', 'xml:base', 'xml:lang', 'xml:space'], feFuncR: ['amplitude', 'exponent', 'id', 'intercept', 'offset', 'slope', 'tableValues', 'type', 'xml:base', 'xml:lang', 'xml:space'], feGaussianBlur: ['class', 'height', 'id', 'in', 'result', 'stdDeviation', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], feImage: ['class', 'externalResourcesRequired', 'height', 'id', 'preserveAspectRatio', 'result', 'style', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], feMerge: ['class', 'height', 'id', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], feMergeNode: ['id', 'xml:base', 'xml:lang', 'xml:space'], feMorphology: ['class', 'height', 'id', 'in', 'operator', 'radius', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], feOffset: ['class', 'dx', 'dy', 'height', 'id', 'in', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], fePointLight: ['id', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y', 'z'], feSpecularLighting: ['class', 'height', 'id', 'in', 'kernelUnitLength', 'result', 'specularConstant', 'specularExponent', 'style', 'surfaceScale', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], feSpotLight: ['id', 'limitingConeAngle', 'pointsAtX', 'pointsAtY', 'pointsAtZ', 'specularExponent', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y', 'z'], feTile: ['class', 'height', 'id', 'in', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], feTurbulence: ['baseFrequency', 'class', 'height', 'id', 'numOctaves', 'result', 'seed', 'stitchTiles', 'style', 'type', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], filter: ['class', 'externalResourcesRequired', 'filterRes', 'filterUnits', 'height', 'id', 'primitiveUnits', 'style', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], font: ['class', 'externalResourcesRequired', 'horiz-adv-x', 'horiz-origin-x', 'horiz-origin-y', 'id', 'style', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'xml:base', 'xml:lang', 'xml:space'], 'font-face': ['accent-height', 'alphabetic', 'ascent', 'bbox', 'cap-height', 'descent', 'font-family', 'font-size', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'hanging', 'id', 'ideographic', 'mathematical', 'overline-position', 'overline-thickness', 'panose-1', 'slope', 'stemh', 'stemv', 'strikethrough-position', 'strikethrough-thickness', 'underline-position', 'underline-thickness', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'widths', 'x-height', 'xml:base', 'xml:lang', 'xml:space'], 'font-face-format': ['id', 'string', 'xml:base', 'xml:lang', 'xml:space'], 'font-face-name': ['id', 'name', 'xml:base', 'xml:lang', 'xml:space'], 'font-face-src': ['id', 'xml:base', 'xml:lang', 'xml:space'], 'font-face-uri': ['id', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], foreignObject: ['class', 'externalResourcesRequired', 'height', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], g: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], glyph: ['arabic-form', 'class', 'd', 'glyph-name', 'horiz-adv-x', 'id', 'lang', 'orientation', 'style', 'unicode', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'xml:base', 'xml:lang', 'xml:space'], glyphRef: ['class', 'dx', 'dy', 'format', 'glyphRef', 'id', 'style', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], hkern: ['g1', 'g2', 'id', 'k', 'u1', 'u2', 'xml:base', 'xml:lang', 'xml:space'], image: ['class', 'externalResourcesRequired', 'height', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'preserveAspectRatio', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], line: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'x1', 'x2', 'xml:base', 'xml:lang', 'xml:space', 'y1', 'y2'], linearGradient: ['class', 'externalResourcesRequired', 'gradientTransform', 'gradientUnits', 'id', 'spreadMethod', 'style', 'x1', 'x2', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y1', 'y2'], marker: ['class', 'externalResourcesRequired', 'id', 'markerHeight', 'markerUnits', 'markerWidth', 'orient', 'preserveAspectRatio', 'refX', 'refY', 'style', 'viewBox', 'xml:base', 'xml:lang', 'xml:space'], mask: ['class', 'externalResourcesRequired', 'height', 'id', 'maskContentUnits', 'maskUnits', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], metadata: ['id', 'xml:base', 'xml:lang', 'xml:space'], 'missing-glyph': ['class', 'd', 'horiz-adv-x', 'id', 'style', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'xml:base', 'xml:lang', 'xml:space'], mpath: ['externalResourcesRequired', 'id', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], path: ['class', 'd', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'pathLength', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], pattern: ['class', 'externalResourcesRequired', 'height', 'id', 'patternContentUnits', 'patternTransform', 'patternUnits', 'preserveAspectRatio', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'viewBox', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], polygon: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'points', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], polyline: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'points', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], radialGradient: ['class', 'cx', 'cy', 'externalResourcesRequired', 'fx', 'fy', 'gradientTransform', 'gradientUnits', 'id', 'r', 'spreadMethod', 'style', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], rect: ['class', 'externalResourcesRequired', 'height', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rx', 'ry', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], script: ['externalResourcesRequired', 'id', 'type', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], set: ['attributeName', 'attributeType', 'begin', 'dur', 'end', 'externalResourcesRequired', 'fill', 'id', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'systemLanguage', 'to', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], stop: ['class', 'id', 'offset', 'style', 'xml:base', 'xml:lang', 'xml:space'], style: ['id', 'media', 'title', 'type', 'xml:base', 'xml:lang', 'xml:space'], svg: ['baseProfile', 'class', 'contentScriptType', 'contentStyleType', 'externalResourcesRequired', 'height', 'id', 'onabort', 'onactivate', 'onclick', 'onerror', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onresize', 'onscroll', 'onunload', 'onzoom', 'preserveAspectRatio', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'version', 'viewBox', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y', 'zoomAndPan'], switch: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'], symbol: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'preserveAspectRatio', 'style', 'viewBox', 'xml:base', 'xml:lang', 'xml:space'], text: ['class', 'dx', 'dy', 'externalResourcesRequired', 'id', 'lengthAdjust', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rotate', 'style', 'systemLanguage', 'textLength', 'transform', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], textPath: ['class', 'externalResourcesRequired', 'id', 'lengthAdjust', 'method', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'spacing', 'startOffset', 'style', 'systemLanguage', 'textLength', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'], title: ['class', 'id', 'style', 'xml:base', 'xml:lang', 'xml:space'], tref: ['class', 'dx', 'dy', 'externalResourcesRequired', 'id', 'lengthAdjust', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rotate', 'style', 'systemLanguage', 'textLength', 'x', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], tspan: ['class', 'dx', 'dy', 'externalResourcesRequired', 'id', 'lengthAdjust', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rotate', 'style', 'systemLanguage', 'textLength', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'], use: ['class', 'externalResourcesRequired', 'height', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'], view: ['externalResourcesRequired', 'id', 'preserveAspectRatio', 'viewBox', 'viewTarget', 'xml:base', 'xml:lang', 'xml:space', 'zoomAndPan'], vkern: ['g1', 'g2', 'id', 'k', 'u1', 'u2', 'xml:base', 'xml:lang', 'xml:space'] }; svgPresentationElements = { 'a': true, 'altGlyph': true, 'animate': true, 'animateColor': true, 'circle': true, 'clipPath': true, 'defs': true, 'ellipse': true, 'feBlend': true, 'feColorMatrix': true, 'feComponentTransfer': true, 'feComposite': true, 'feConvolveMatrix': true, 'feDiffuseLighting': true, 'feDisplacementMap': true, 'feFlood': true, 'feGaussianBlur': true, 'feImage': true, 'feMerge': true, 'feMorphology': true, 'feOffset': true, 'feSpecularLighting': true, 'feTile': true, 'feTurbulence': true, 'filter': true, 'font': true, 'foreignObject': true, 'g': true, 'glyph': true, 'glyphRef': true, 'image': true, 'line': true, 'linearGradient': true, 'marker': true, 'mask': true, 'missing-glyph': true, 'path': true, 'pattern': true, 'polygon': true, 'polyline': true, 'radialGradient': true, 'rect': true, 'stop': true, 'svg': true, 'switch': true, 'symbol': true, 'text': true, 'textPath': true, 'tref': true, 'tspan': true, 'use': true }; svgPresentationAttributes = { 'alignment-baseline': true, 'baseline-shift': true, 'clip-path': true, 'clip-rule': true, 'clip': true, 'color-interpolation-filters': true, 'color-interpolation': true, 'color-profile': true, 'color-rendering': true, 'color': true, 'cursor': true, 'direction': true, 'display': true, 'dominant-baseline': true, 'enable-background': true, 'fill-opacity': true, 'fill-rule': true, 'fill': true, 'filter': true, 'flood-color': true, 'flood-opacity': true, 'font-family': true, 'font-size-adjust': true, 'font-size': true, 'font-stretch': true, 'font-style': true, 'font-variant': true, 'font-weight': true, 'glyph-orientation-horizontal': true, 'glyph-orientation-vertical': true, 'image-rendering': true, 'kerning': true, 'letter-spacing': true, 'lighting-color': true, 'marker-end': true, 'marker-mid': true, 'marker-start': true, 'mask': true, 'opacity': true, 'overflow': true, 'pointer-events': true, 'shape-rendering': true, 'stop-color': true, 'stop-opacity': true, 'stroke-dasharray': true, 'stroke-dashoffset': true, 'stroke-linecap': true, 'stroke-linejoin': true, 'stroke-miterlimit': true, 'stroke-opacity': true, 'stroke-width': true, 'stroke': true, 'text-anchor': true, 'text-decoration': true, 'text-rendering': true, 'unicode-bidi': true, 'visibility': true, 'word-spacing': true, 'writing-mode': true }; let createElement = function (html) { let div = DOM.createElement('div'); div.innerHTML = html; return div.firstChild; }; svgAnalyzer = class SVGAnalyzer { constructor() { if (createElement('<svg><altGlyph /></svg>').firstElementChild.nodeName === 'altglyph' && elements.altGlyph) { elements.altglyph = elements.altGlyph; delete elements.altGlyph; elements.altglyphdef = elements.altGlyphDef; delete elements.altGlyphDef; elements.altglyphitem = elements.altGlyphItem; delete elements.altGlyphItem; elements.glyphref = elements.glyphRef; delete elements.glyphRef; } } isStandardSvgAttribute(nodeName, attributeName) { return presentationElements[nodeName] && presentationAttributes[attributeName] || elements[nodeName] && elements[nodeName].indexOf(attributeName) !== -1; } }; } const elements = svgElements; const presentationElements = svgPresentationElements; const presentationAttributes = svgPresentationAttributes; const SVGAnalyzer = svgAnalyzer || class { isStandardSvgAttribute() { return false; } }; let ObserverLocator = (_temp = _class11 = class ObserverLocator { constructor(taskQueue, eventManager, dirtyChecker, svgAnalyzer, parser) { this.taskQueue = taskQueue; this.eventManager = eventManager; this.dirtyChecker = dirtyChecker; this.svgAnalyzer = svgAnalyzer; this.parser = parser; this.adapters = []; this.logger = getLogger('observer-locator'); } getObserver(obj, propertyName) { let observersLookup = obj.__observers__; let observer; if (observersLookup && propertyName in observersLookup) { return observersLookup[propertyName]; } observer = this.createPropertyObserver(obj, propertyName); if (!observer.doNotCache) { if (observersLookup === undefined) { observersLookup = this.getOrCreateObserversLookup(obj); } observersLookup[propertyName] = observer; } return observer; } getOrCreateObserversLookup(obj) { return obj.__observers__ || this.createObserversLookup(obj); } createObserversLookup(obj) { let value = {}; if (!Reflect.defineProperty(obj, '__observers__', { enumerable: false, configurable: false, writable: false, value: value })) { this.logger.warn('Cannot add observers to object', obj); } return value; } addAdapter(adapter) { this.adapters.push(adapter); } getAdapterObserver(obj, propertyName, descriptor) { for (let i = 0, ii = this.adapters.length; i < ii; i++) { let adapter = this.adapters[i]; let observer = adapter.getObserver(obj, propertyName, descriptor); if (observer) { return observer; } } return null; } createPropertyObserver(obj, propertyName) { let descriptor; let handler; let xlinkResult; if (!(obj instanceof Object)) { return new PrimitiveObserver(obj, propertyName); } if (obj instanceof DOM.Element) { if (propertyName === 'class') { return new ClassObserver(obj); } if (propertyName === 'style' || propertyName === 'css') { return new StyleObserver(obj, propertyName); } handler = this.eventManager.getElementHandler(obj, propertyName); if (propertyName === 'value' && obj.tagName.toLowerCase() === 'select') { return new SelectValueObserver(obj, handler, this); } if (propertyName === 'checked' && obj.tagName.toLowerCase() === 'input') { return new CheckedObserver(obj, handler, this); } if (handler) { return new ValueAttributeObserver(obj, propertyName, handler); } xlinkResult = /^xlink:(.+)$/.exec(propertyName); if (xlinkResult) { return new XLinkAttributeObserver(obj, propertyName, xlinkResult[1]); } if (propertyName === 'role' && (obj instanceof DOM.Element || obj instanceof DOM.SVGElement) || /^\w+:|^data-|^aria-/.test(propertyName) || obj instanceof DOM.SVGElement && this.svgAnalyzer.isStandardSvgAttribute(obj.nodeName, propertyName)) { return new DataAttributeObserver(obj, propertyName); } } descriptor = Object.getPropertyDescriptor(obj, propertyName); if (hasDeclaredDependencies(descriptor)) { return createComputedObserver(obj, propertyName, descriptor, this); } if (descriptor) { const existingGetterOrSetter = descriptor.get || descriptor.set; if (existingGetterOrSetter) { if (existingGetterOrSetter.getObserver) { return existingGetterOrSetter.getObserver(obj); } let adapterObserver = this.getAdapterObserver(obj, propertyName, descriptor); if (adapterObserver) { return adapterObserver; } return new DirtyCheckProperty(this.dirtyChecker, obj, propertyName); } } if (obj instanceof Array) { if (propertyName === 'length') { return this.getArrayObserver(obj).getLengthObserver(); } return new DirtyCheckProperty(this.dirtyChecker, obj, propertyName); } else if (obj instanceof Map) { if (propertyName === 'size') { return this.getMapObserver(obj).getLengthObserver(); } return new DirtyCheckProperty(this.dirtyChecker, obj, propertyName); } else if (obj instanceof Set) { if (propertyName === 'size') { return this.getSetObserver(obj).getLengthObserver(); } return new DirtyCheckProperty(this.dirtyChecker, obj, propertyName); } return new SetterObserver(this.taskQueue, obj, propertyName); } getAccessor(obj, propertyName) { if (obj instanceof DOM.Element) { if (propertyName === 'class' || propertyName === 'style' || propertyName === 'css' || propertyName === 'value' && (obj.tagName.toLowerCase() === 'input' || obj.tagName.toLowerCase() === 'select') || propertyName === 'checked' && obj.tagName.toLowerCase() === 'input' || propertyName === 'model' && obj.tagName.toLowerCase() === 'input' || /^xlink:.+$/.exec(propertyName)) { return this.getObserver(obj, propertyName); } if (/^\w+:|^data-|^aria-/.test(propertyName) || obj instanceof DOM.SVGElement && this.svgAnalyzer.isStandardSvgAttribute(obj.nodeName, propertyName) || obj.tagName.toLowerCase() === 'img' && propertyName === 'src' || obj.tagName.toLowerCase() === 'a' && propertyName === 'href') { return dataAttributeAccessor; } } return propertyAccessor; } getArrayObserver(array) { return getArrayObserver(this.taskQueue, array); } getMapObserver(map) { return getMapObserver(this.taskQueue, map); } getSetObserver(set) { return getSetObserver(this.taskQueue, set); } }, _class11.inject = [TaskQueue, EventManager, DirtyChecker, SVGAnalyzer, Parser], _temp); let ObjectObservationAdapter = class ObjectObservationAdapter { getObserver(object, propertyName, descriptor) { throw new Error('BindingAdapters must implement getObserver(object, propertyName).'); } }; let BindingExpression = class BindingExpression { constructor(observerLocator, targetProperty, sourceExpression, mode, lookupFunctions, attribute) { this.observerLocator = observerLocator; this.targetProperty = targetProperty; this.sourceExpression = sourceExpression; this.mode = mode; this.lookupFunctions = lookupFunctions; this.attribute = attribute; this.discrete = false; } createBinding(target) { return new Binding(this.observerLocator, this.sourceExpression, target, this.targetProperty, this.mode, this.lookupFunctions); } }; let Binding = (_dec10 = connectable(), _dec10(_class12 = class Binding { constructor(observerLocator, sourceExpression, target, targetProperty, mode, lookupFunctions) { this.observerLocator = observerLocator; this.sourceExpression = sourceExpression; this.target = target; this.targetProperty = targetProperty; this.mode = mode; this.lookupFunctions = lookupFunctions; } updateTarget(value) { this.targetObserver.setValue(value, this.target, this.targetProperty); } updateSource(value) { this.sourceExpression.assign(this.source, value, this.lookupFunctions); } call(context, newValue, oldValue) { if (!this.isBound) { return; } if (context === sourceContext) { oldValue = this.targetObserver.getValue(this.target, this.targetProperty); newValue = this.sourceExpression.evaluate(this.source, this.lookupFunctions); if (newValue !== oldValue) { this.updateTarget(newValue); } if (this.mode !== bindingMode.oneTime) { this._version++; this.sourceExpression.connect(this, this.source); this.unobserve(false); } return; } if (context === targetContext) { if (newValue !== this.sourceExpression.evaluate(this.source, this.lookupFunctions)) { this.updateSource(newValue); } return; } throw new Error(`Unexpected call context ${context}`); } bind(source) { if (this.isBound) { if (this.source === source) { return; } this.unbind(); } this.isBound = true; this.source = source; if (this.sourceExpression.bind) { this.sourceExpression.bind(this, source, this.lookupFunctions); } let mode = this.mode; if (!this.targetObserver) { let method = mode === bindingMode.twoWay || mode === bindingMode.fromView ? 'getObserver' : 'getAccessor'; this.targetObserver = this.observerLocator[method](this.target, this.targetProperty); } if ('bind' in this.targetObserver) { this.targetObserver.bind(); } if (this.mode !== bindingMode.fromView) { let value = this.sourceExpression.evaluate(source, this.lookupFunctions); this.updateTarget(value); } if (mode === bindingMode.oneTime) { return; } else if (mode === bindingMode.toView) { enqueueBindingConnect(this); } else if (mode === bindingMode.twoWay) { this.sourceExpression.connect(this, source); this.targetObserver.subscribe(targetContext, this); } else if (mode === bindingMode.fromView) { this.targetObserver.subscribe(targetContext, this); } } unbind() { if (!this.isBound) { return; } this.isBound = false; if (this.sourceExpression.unbind) { this.sourceExpression.unbind(this, this.source); } this.source = null; if ('unbind' in this.targetObserver) { this.targetObserver.unbind(); } if (this.targetObserver.unsubscribe) { this.targetObserver.unsubscribe(targetContext, this); } this.unobserve(true); } connect(evaluate) { if (!this.isBound) { return; } if (evaluate) { let value = this.sourceExpression.evaluate(this.source, this.lookupFunctions); this.updateTarget(value); } this.sourceExpression.connect(this, this.source); } }) || _class12); let CallExpression = class CallExpression { constructor(observerLocator, targetProperty, sourceExpression, lookupFunctions) { this.observerLocator = observerLocator; this.targetProperty = targetProperty; this.sourceExpression = sourceExpression; this.lookupFunctions = lookupFunctions; } createBinding(target) { return new Call(this.observerLocator, this.sourceExpression, target, this.targetProperty, this.lookupFunctions); } }; let Call = class Call { constructor(observerLocator, sourceExpression, target, targetProperty, lookupFunctions) { this.sourceExpression = sourceExpression; this.target = target; this.targetProperty = observerLocator.getObserver(target, targetProperty); this.lookupFunctions = lookupFunctions; } callSource($event) { let overrideContext = this.source.overrideContext; Object.assign(overrideContext, $event); overrideContext.$event = $event; let mustEvaluate = true; let result = this.sourceExpression.evaluate(this.source, this.lookupFunctions, mustEvaluate); delete overrideContext.$event; for (let prop in $event) { delete overrideContext[prop]; } return result; } bind(source) { if (this.isBound) { if (this.source === source) { return; } this.unbind(); } this.isBound = true; this.source = source; if (this.sourceExpression.bind) { this.sourceExpression.bind(this, source, this.lookupFunctions); } this.targetProperty.setValue($event => this.callSource($event)); } unbind() { if (!this.isBound) { return; } this.isBound = false; if (this.sourceExpression.unbind) { this.sourceExpression.unbind(this, this.source); } this.source = null; this.targetProperty.setValue(null); } }; let ValueConverterResource = class ValueConverterResource { constructor(name) { this.name = name; } static convention(name) { if (name.endsWith('ValueConverter')) { return new ValueConverterResource(camelCase(name.substring(0, name.length - 14))); } } initialize(container, target) { this.instance = container.get(target); } register(registry, name) { registry.registerValueConverter(name || this.name, this.instance); } load(container, target) {} }; function valueConverter(nameOrTarget) { if (nameOrTarget === undefined || typeof nameOrTarget === 'string') { return function (target) { metadata.define(metadata.resource, new ValueConverterResource(nameOrTarget), target); }; } metadata.define(metadata.resource, new ValueConverterResource(), nameOrTarget); } let BindingBehaviorResource = class BindingBehaviorResource { constructor(name) { this.name = name; } static convention(name) { if (name.endsWith('BindingBehavior')) { return new BindingBehaviorResource(camelCase(name.substring(0, name.length - 15))); } } initialize(container, target) { this.instance = container.get(target); } register(registry, name) { registry.registerBindingBehavior(name || this.name, this.instance); } load(container, target) {} }; function bindingBehavior(nameOrTarget) { if (nameOrTarget === undefined || typeof nameOrTarget === 'string') { return function (target) { metadata.define(metadata.resource, new BindingBehaviorResource(nameOrTarget), target); }; } metadata.define(metadata.resource, new BindingBehaviorResource(), nameOrTarget); } let ListenerExpression = class ListenerExpression { constructor(eventManager, targetEvent, sourceExpression, delegationStrategy, preventDefault, lookupFunctions) { this.eventManager = eventManager; this.targetEvent = targetEvent; this.sourceExpression = sourceExpression; this.delegationStrategy = delegationStrategy; this.discrete = true; this.preventDefault = preventDefault; this.lookupFunctions = lookupFunctions; } createBinding(target) { return new Listener(this.eventManager, this.targetEvent, this.delegationStrategy, this.sourceExpression, target, this.preventDefault, this.lookupFunctions); } }; let Listener = class Listener { constructor(eventManager, targetEvent, delegationStrategy, sourceExpression, target, preventDefault, lookupFunctions) { this.eventManager = eventManager; this.targetEvent = targetEvent; this.delegationStrategy = delegationStrategy; this.sourceExpression = sourceExpression; this.target = target; this.preventDefault = preventDefault; this.lookupFunctions = lookupFunctions; } callSource(event) { let overrideContext = this.source.overrideContext; overrideContext.$event = event; let mustEvaluate = true; let result = this.sourceExpression.evaluate(this.source, this.lookupFunctions, mustEvaluate); delete overrideContext.$event; if (result !== true && this.preventDefault) { event.preventDefault(); } return result; } handleEvent(event) { this.callSource(event); } bind(source) { if (this.isBound) { if (this.source === source) { return; } this.unbind(); } this.isBound = true; this.source = source; if (this.sourceExpression.bind) { this.sourceExpression.bind(this, source, this.lookupFunctions); } this._handler = this.eventManager.addEventListener(this.target, this.targetEvent, this, this.delegationStrategy, true); } unbind() { if (!this.isBound) { return; } this.isBound = false; if (this.sourceExpression.unbind) { this.sourceExpression.unbind(this, this.source); } this.source = null; this._handler.dispose(); this._handler = null; } }; function getAU(element) { let au = element.au; if (au === undefined) { throw new Error(`No Aurelia APIs are defined for the element: "${element.tagName}".`); } return au; } let NameExpression = class NameExpression { constructor(sourceExpression, apiName, lookupFunctions) { this.sourceExpression = sourceExpression; this.apiName = apiName; this.lookupFunctions = lookupFunctions; this.discrete = true; } createBinding(target) { return new NameBinder(this.sourceExpression, NameExpression.locateAPI(target, this.apiName), this.lookupFunctions); } static locateAPI(element, apiName) { switch (apiName) { case 'element': return element; case 'controller': return getAU(element).controller; case 'view-model': return getAU(element).controller.viewModel; case 'view': return getAU(element).controller.view; default: let target = getAU(element)[apiName]; if (target === undefined) { throw new Error(`Attempted to reference "${apiName}", but it was not found amongst the target's API.`); } return target.viewModel; } } }; let NameBinder = class NameBinder { constructor(sourceExpression, target, lookupFunctions) { this.sourceExpression = sourceExpression; this.target = target; this.lookupFunctions = lookupFunctions; } bind(source) { if (this.isBound) { if (this.source === source) { return; } this.unbind(); } this.isBound = true; this.source = source; if (this.sourceExpression.bind) { this.sourceExpression.bind(this, source, this.lookupFunctions); } this.sourceExpression.assign(this.source, this.target, this.lookupFunctions); } unbind() { if (!this.isBound) { return; } this.isBound = false; if (this.sourceExpression.evaluate(this.source, this.lookupFunctions) === this.target) { this.sourceExpression.assign(this.source, null, this.lookupFunctions); } if (this.sourceExpression.unbind) { this.sourceExpression.unbind(this, this.source); } this.source = null; } }; const LookupFunctions = { bindingBehaviors: name => null, valueConverters: name => null }; let BindingEngine = (_temp2 = _class13 = class BindingEngine { constructor(observerLocator, parser) { this.observerLocator = observerLocator; this.parser = parser; } createBindingExpression(targetProperty, sourceExpression, mode = bindingMode.toView, lookupFunctions = LookupFunctions) { return new BindingExpression(this.observerLocator, targetProperty, this.parser.parse(sourceExpression), mode, lookupFunctions); } propertyObserver(obj, propertyName) { return { subscribe: callback => { let observer = this.observerLocator.getObserver(obj, propertyName); observer.subscribe(callback); return { dispose: () => observer.unsubscribe(callback) }; } }; } collectionObserver(collection) { return { subscribe: callback => { let observer; if (collection instanceof Array) { observer = this.observerLocator.getArrayObserver(collection); } else if (collection instanceof Map) { observer = this.observerLocator.getMapObserver(collection); } else if (collection instanceof Set) { observer = this.observerLocator.getSetObserver(collection); } else { throw new Error('collection must be an instance of Array, Map or Set.'); } observer.subscribe(callback); return { dispose: () => observer.unsubscribe(callback) }; } }; } expressionObserver(bindingContext, expression) { let scope = { bindingContext, overrideContext: createOverrideContext(bindingContext) }; return new ExpressionObserver(scope, this.parser.parse(expression), this.observerLocator, LookupFunctions); } parseExpression(expression) { return this.parser.parse(expression); } registerAdapter(adapter) { this.observerLocator.addAdapter(adapter); } }, _class13.inject = [ObserverLocator, Parser], _temp2); let setProto = Set.prototype; function getSetObserver(taskQueue, set) { return ModifySetObserver.for(taskQueue, set); } let ModifySetObserver = class ModifySetObserver extends ModifyCollectionObserver { constructor(taskQueue, set) { super(taskQueue, set); } static for(taskQueue, set) { if (!('__set_observer__' in set)) { Reflect.defineProperty(set, '__set_observer__', { value: ModifySetObserver.create(taskQueue, set), enumerable: false, configurable: false }); } return set.__set_observer__; } static create(taskQueue, set) { let observer = new ModifySetObserver(taskQueue, set); let proto = setProto; if (proto.add !== set.add || proto.delete !== set.delete || proto.clear !== set.clear) { proto = { add: set.add, delete: set.delete, clear: set.clear }; } set.add = function () { let type = 'add'; let oldSize = set.size; let methodCallResult = proto.add.apply(set, arguments); let hasValue = set.size === oldSize; if (!hasValue) { observer.addChangeRecord({ type: type, object: set, value: Array.from(set).pop() }); } return methodCallResult; }; set.delete = function () { let hasValue = set.has(arguments[0]); let methodCallResult = proto.delete.apply(set, arguments); if (hasValue) { observer.addChangeRecord({ type: 'delete', object: set, value: arguments[0] }); } return methodCallResult; }; set.clear = function () { let methodCallResult = proto.clear.apply(set, arguments); observer.addChangeRecord({ type: 'clear', object: set }); return methodCallResult; }; return observer; } }; function observable(targetOrConfig, key, descriptor) { function deco(target, key, descriptor, config) { const isClassDecorator = key === undefined; if (isClassDecorator) { target = target.prototype; key = typeof config === 'string' ? config : config.name; } let innerPropertyName = `_${key}`; const innerPropertyDescriptor = { configurable: true, enumerable: false, writable: true }; const callbackName = config && config.changeHandler || `${key}Changed`; if (descriptor) { if (typeof descriptor.initializer === 'function') { innerPropertyDescriptor.value = descriptor.initializer(); } } else { descriptor = {}; } if (!('enumerable' in descriptor)) { descriptor.enumerable = true; } delete descriptor.value; delete descriptor.writable; delete descriptor.initializer; Reflect.defineProperty(target, innerPropertyName, innerPropertyDescriptor); descriptor.get = function () { return this[innerPropertyName]; }; descriptor.set = function (newValue) { let oldValue = this[innerPropertyName]; if (newValue === oldValue) { return; } this[innerPropertyName] = newValue; Reflect.defineProperty(this, innerPropertyName, { enumerable: false }); if (this[callbackName]) { this[callbackName](newValue, oldValue, key); } }; descriptor.get.dependencies = [innerPropertyName]; if (isClassDecorator) { Reflect.defineProperty(target, key, descriptor); } else { return descriptor; } } if (key === undefined) { return (t, k, d) => deco(t, k, d, targetOrConfig); } return deco(targetOrConfig, key, descriptor); } const signals = {}; function connectBindingToSignal(binding, name) { if (!signals.hasOwnProperty(name)) { signals[name] = 0; } binding.observeProperty(signals, name); } function signalBindings(name) { if (signals.hasOwnProperty(name)) { signals[name]++; } } var _class$2, _temp$1, _dec$2, _class2$2, _dec2$2, _class3$2, _dec3$2, _class4$1, _dec4$2, _class5$2, _dec5$2, _class6$1, _dec6$2, _class7$2, _class8$1, _temp2$1, _class9$1, _temp3, _class11$1, _dec7$2, _class13$1, _dec8$1, _class14, _class15, _temp4, _dec9$1, _class16, _dec10$1, _class17, _dec11, _class18; const animationEvent = { enterBegin: 'animation:enter:begin', enterActive: 'animation:enter:active', enterDone: 'animation:enter:done', enterTimeout: 'animation:enter:timeout', leaveBegin: 'animation:leave:begin', leaveActive: 'animation:leave:active', leaveDone: 'animation:leave:done', leaveTimeout: 'animation:leave:timeout', staggerNext: 'animation:stagger:next', removeClassBegin: 'animation:remove-class:begin', removeClassActive: 'animation:remove-class:active', removeClassDone: 'animation:remove-class:done', removeClassTimeout: 'animation:remove-class:timeout', addClassBegin: 'animation:add-class:begin', addClassActive: 'animation:add-class:active', addClassDone: 'animation:add-class:done', addClassTimeout: 'animation:add-class:timeout', animateBegin: 'animation:animate:begin', animateActive: 'animation:animate:active', animateDone: 'animation:animate:done', animateTimeout: 'animation:animate:timeout', sequenceBegin: 'animation:sequence:begin', sequenceDone: 'animation:sequence:done' }; let Animator = class Animator { enter(element) { return Promise.resolve(false); } leave(element) { return Promise.resolve(false); } removeClass(element, className) { element.classList.remove(className); return Promise.resolve(false); } addClass(element, className) { element.classList.add(className); return Promise.resolve(false); } animate(element, className) { return Promise.resolve(false); } runSequence(animations) {} registerEffect(effectName, properties) {} unregisterEffect(effectName) {} }; let CompositionTransactionNotifier = class CompositionTransactionNotifier { constructor(owner) { this.owner = owner; this.owner._compositionCount++; } done() { this.owner._compositionCount--; this.owner._tryCompleteTransaction(); } }; let CompositionTransactionOwnershipToken = class CompositionTransactionOwnershipToken { constructor(owner) { this.owner = owner; this.owner._ownershipToken = this; this.thenable = this._createThenable(); } waitForCompositionComplete() { this.owner._tryCompleteTransaction(); return this.thenable; } resolve() { this._resolveCallback(); } _createThenable() { return new Promise((resolve, reject) => { this._resolveCallback = resolve; }); } }; let CompositionTransaction = class CompositionTransaction { constructor() { this._ownershipToken = null; this._compositionCount = 0; } tryCapture() { return this._ownershipToken === null ? new CompositionTransactionOwnershipToken(this) : null; } enlist() { return new CompositionTransactionNotifier(this); } _tryCompleteTransaction() { if (this._compositionCount <= 0) { this._compositionCount = 0; if (this._ownershipToken !== null) { let token = this._ownershipToken; this._ownershipToken = null; token.resolve(); } } } }; const capitalMatcher = /([A-Z])/g; function addHyphenAndLower(char) { return '-' + char.toLowerCase(); } function _hyphenate(name) { return (name.charAt(0).toLowerCase() + name.slice(1)).replace(capitalMatcher, addHyphenAndLower); } function _isAllWhitespace(node) { return !(node.auInterpolationTarget || /[^\t\n\r ]/.test(node.textContent)); } let ViewEngineHooksResource = class ViewEngineHooksResource { constructor() {} initialize(container, target) { this.instance = container.get(target); } register(registry, name) { registry.registerViewEngineHooks(this.instance); } load(container, target) {} static convention(name) { if (name.endsWith('ViewEngineHooks')) { return new ViewEngineHooksResource(); } } }; function viewEngineHooks(target) { let deco = function (t) { metadata.define(metadata.resource, new ViewEngineHooksResource(), t); }; return target ? deco(target) : deco; } let ElementEvents = class ElementEvents { constructor(element) { this.element = element; this.subscriptions = {}; } _enqueueHandler(handler) { this.subscriptions[handler.eventName] = this.subscriptions[handler.eventName] || []; this.subscriptions[handler.eventName].push(handler); } _dequeueHandler(handler) { let index; let subscriptions = this.subscriptions[handler.eventName]; if (subscriptions) { index = subscriptions.indexOf(handler); if (index > -1) { subscriptions.splice(index, 1); } } return handler; } publish(eventName, detail = {}, bubbles = true, cancelable = true) { let event = DOM.createCustomEvent(eventName, { cancelable, bubbles, detail }); this.element.dispatchEvent(event); } subscribe(eventName, handler, captureOrOptions = true) { if (typeof handler === 'function') { const eventHandler = new EventHandlerImpl(this, eventName, handler, captureOrOptions, false); return eventHandler; } return undefined; } subscribeOnce(eventName, handler, captureOrOptions = true) { if (typeof handler === 'function') { const eventHandler = new EventHandlerImpl(this, eventName, handler, captureOrOptions, true); return eventHandler; } return undefined; } dispose(eventName) { if (eventName && typeof eventName === 'string') { let subscriptions = this.subscriptions[eventName]; if (subscriptions) { while (subscriptions.length) { let subscription = subscriptions.pop(); if (subscription) { subscription.dispose(); } } } } else { this.disposeAll(); } } disposeAll() { for (let key in this.subscriptions) { this.dispose(key); } } }; let EventHandlerImpl = class EventHandlerImpl { constructor(owner, eventName, handler, captureOrOptions, once) { this.owner = owner; this.eventName = eventName; this.handler = handler; this.capture = typeof captureOrOptions === 'boolean' ? captureOrOptions : captureOrOptions.capture; this.bubbles = !this.capture; this.captureOrOptions = captureOrOptions; this.once = once; owner.element.addEventListener(eventName, this, captureOrOptions); owner._enqueueHandler(this); } handleEvent(e) { const fn = this.handler; fn(e); if (this.once) { this.dispose(); } } dispose() { this.owner.element.removeEventListener(this.eventName, this, this.captureOrOptions); this.owner._dequeueHandler(this); this.owner = this.handler = null; } }; let ResourceLoadContext = class ResourceLoadContext { constructor() { this.dependencies = {}; } addDependency(url) { this.dependencies[url] = true; } hasDependency(url) { return url in this.dependencies; } }; let ViewCompileInstruction = class ViewCompileInstruction { constructor(targetShadowDOM = false, compileSurrogate = false) { this.targetShadowDOM = targetShadowDOM; this.compileSurrogate = compileSurrogate; this.associatedModuleId = null; } }; ViewCompileInstruction.normal = new ViewCompileInstruction(); let BehaviorInstruction = class BehaviorInstruction { static enhance() { let instruction = new BehaviorInstruction(); instruction.enhance = true; return instruction; } static unitTest(type, attributes) { let instruction = new BehaviorInstruction(); instruction.type = type; instruction.attributes = attributes || {}; return instruction; } static element(node, type) { let instruction = new BehaviorInstruction(); instruction.type = type; instruction.attributes = {}; instruction.anchorIsContainer = !(node.hasAttribute('containerless') || type.containerless); instruction.initiatedByBehavior = true; return instruction; } static attribute(attrName, type) { let instruction = new BehaviorInstruction(); instruction.attrName = attrName; instruction.type = type || null; instruction.attributes = {}; return instruction; } static dynamic(host, viewModel, viewFactory) { let instruction = new BehaviorInstruction(); instruction.host = host; instruction.viewModel = viewModel; instruction.viewFactory = viewFactory; instruction.inheritBindingContext = true; return instruction; } }; const biProto = BehaviorInstruction.prototype; biProto.initiatedByBehavior = false; biProto.enhance = false; biProto.partReplacements = null; biProto.viewFactory = null; biProto.originalAttrName = null; biProto.skipContentProcessing = false; biProto.contentFactory = null; biProto.viewModel = null; biProto.anchorIsContainer = false; biProto.host = null; biProto.attributes = null; biProto.type = null; biProto.attrName = null; biProto.inheritBindingContext = false; BehaviorInstruction.normal = new BehaviorInstruction(); let TargetInstruction = (_temp$1 = _class$2 = class TargetInstruction { static shadowSlot(parentInjectorId) { let instruction = new TargetInstruction(); instruction.parentInjectorId = parentInjectorId; instruction.shadowSlot = true; return instruction; } static contentExpression(expression) { let instruction = new TargetInstruction(); instruction.contentExpression = expression; return instruction; } static letElement(expressions) { let instruction = new TargetInstruction(); instruction.expressions = expressions; instruction.letElement = true; return instruction; } static lifting(parentInjectorId, liftingInstruction) { let instruction = new TargetInstruction(); instruction.parentInjectorId = parentInjectorId; instruction.expressions = TargetInstruction.noExpressions; instruction.behaviorInstructions = [liftingInstruction]; instruction.viewFactory = liftingInstruction.viewFactory; instruction.providers = [liftingInstruction.type.target]; instruction.lifting = true; return instruction; } static normal(injectorId, parentInjectorId, providers, behaviorInstructions, expressions, elementInstruction) { let instruction = new TargetInstruction(); instruction.injectorId = injectorId; instruction.parentInjectorId = parentInjectorId; instruction.providers = providers; instruction.behaviorInstructions = behaviorInstructions; instruction.expressions = expressions; instruction.anchorIsContainer = elementInstruction ? elementInstruction.anchorIsContainer : true; instruction.elementInstruction = elementInstruction; return instruction; } static surrogate(providers, behaviorInstructions, expressions, values) { let instruction = new TargetInstruction(); instruction.expressions = expressions; instruction.behaviorInstructions = behaviorInstructions; instruction.providers = providers; instruction.values = values; return instruction; } }, _class$2.noExpressions = Object.freeze([]), _temp$1); const tiProto = TargetInstruction.prototype; tiProto.injectorId = null; tiProto.parentInjectorId = null; tiProto.shadowSlot = false; tiProto.slotName = null; tiProto.slotFallbackFactory = null; tiProto.contentExpression = null; tiProto.letElement = false; tiProto.expressions = null; tiProto.expressions = null; tiProto.providers = null; tiProto.viewFactory = null; tiProto.anchorIsContainer = false; tiProto.elementInstruction = null; tiProto.lifting = false; tiProto.values = null; const viewStrategy = protocol.create('aurelia:view-strategy', { validate(target) { if (!(typeof target.loadViewFactory === 'function')) { return 'View strategies must implement: loadViewFactory(viewEngine: ViewEngine, compileInstruction: ViewCompileInstruction, loadContext?: ResourceLoadContext): Promise<ViewFactory>'; } return true; }, compose(target) { if (!(typeof target.makeRelativeTo === 'function')) { target.makeRelativeTo = PLATFORM.noop; } } }); let RelativeViewStrategy = (_dec$2 = viewStrategy(), _dec$2(_class2$2 = class RelativeViewStrategy { constructor(path) { this.path = path; this.absolutePath = null; } loadViewFactory(viewEngine, compileInstruction, loadContext, target) { if (this.absolutePath === null && this.moduleId) { this.absolutePath = relativeToFile(this.path, this.moduleId); } compileInstruction.associatedModuleId = this.moduleId; return viewEngine.loadViewFactory(this.absolutePath || this.path, compileInstruction, loadContext, target); } makeRelativeTo(file) { if (this.absolutePath === null) { this.absolutePath = relativeToFile(this.path, file); } } }) || _class2$2); let ConventionalViewStrategy = (_dec2$2 = viewStrategy(), _dec2$2(_class3$2 = class ConventionalViewStrategy { constructor(viewLocator, origin) { this.moduleId = origin.moduleId; this.viewUrl = viewLocator.convertOriginToViewUrl(origin); } loadViewFactory(viewEngine, compileInstruction, loadContext, target) { compileInstruction.associatedModuleId = this.moduleId; return viewEngine.loadViewFactory(this.viewUrl, compileInstruction, loadContext, target); } }) || _class3$2); let NoViewStrategy = (_dec3$2 = viewStrategy(), _dec3$2(_class4$1 = class NoViewStrategy { constructor(dependencies, dependencyBaseUrl) { this.dependencies = dependencies || null; this.dependencyBaseUrl = dependencyBaseUrl || ''; } loadViewFactory(viewEngine, compileInstruction, loadContext, target) { let entry = this.entry; let dependencies = this.dependencies; if (entry && entry.factoryIsReady) { return Promise.resolve(null); } this.entry = entry = new TemplateRegistryEntry(this.moduleId || this.dependencyBaseUrl); entry.dependencies = []; entry.templateIsLoaded = true; if (dependencies !== null) { for (let i = 0, ii = dependencies.length; i < ii; ++i) { let current = dependencies[i]; if (typeof current === 'string' || typeof current === 'function') { entry.addDependency(current); } else { entry.addDependency(current.from, current.as); } } } compileInstruction.associatedModuleId = this.moduleId; return viewEngine.loadViewFactory(entry, compileInstruction, loadContext, target); } }) || _class4$1); let TemplateRegistryViewStrategy = (_dec4$2 = viewStrategy(), _dec4$2(_class5$2 = class TemplateRegistryViewStrategy { constructor(moduleId, entry) { this.moduleId = moduleId; this.entry = entry; } loadViewFactory(viewEngine, compileInstruction, loadContext, target) { let entry = this.entry; if (entry.factoryIsReady) { return Promise.resolve(entry.factory); } compileInstruction.associatedModuleId = this.moduleId; return viewEngine.loadViewFactory(entry, compileInstruction, loadContext, target); } }) || _class5$2); let InlineViewStrategy = (_dec5$2 = viewStrategy(), _dec5$2(_class6$1 = class InlineViewStrategy { constructor(markup, dependencies, dependencyBaseUrl) { this.markup = markup; this.dependencies = dependencies || null; this.dependencyBaseUrl = dependencyBaseUrl || ''; } loadViewFactory(viewEngine, compileInstruction, loadContext, target) { let entry = this.entry; let dependencies = this.dependencies; if (entry && entry.factoryIsReady) { return Promise.resolve(entry.factory); } this.entry = entry = new TemplateRegistryEntry(this.moduleId || this.dependencyBaseUrl); entry.template = DOM.createTemplateFromMarkup(this.markup); if (dependencies !== null) { for (let i = 0, ii = dependencies.length; i < ii; ++i) { let current = dependencies[i]; if (typeof current === 'string' || typeof current === 'function') { entry.addDependency(current); } else { entry.addDependency(current.from, current.as); } } } compileInstruction.associatedModuleId = this.moduleId; return viewEngine.loadViewFactory(entry, compileInstruction, loadContext, target); } }) || _class6$1); let StaticViewStrategy = (_dec6$2 = viewStrategy(), _dec6$2(_class7$2 = class StaticViewStrategy { constructor(config) { if (typeof config === 'string' || config instanceof DOM.Element && config.tagName === 'TEMPLATE') { config = { template: config }; } this.template = config.template; this.dependencies = config.dependencies || []; this.factoryIsReady = false; this.onReady = null; this.moduleId = 'undefined'; } loadViewFactory(viewEngine, compileInstruction, loadContext, target) { if (this.factoryIsReady) { return Promise.resolve(this.factory); } let deps = this.dependencies; deps = typeof deps === 'function' ? deps() : deps; deps = deps ? deps : []; deps = Array.isArray(deps) ? deps : [deps]; return Promise.all(deps).then(dependencies => { const container = viewEngine.container; const appResources = viewEngine.appResources; const viewCompiler = viewEngine.viewCompiler; const viewResources = new ViewResources(appResources); let resource; let elDeps = []; if (target) { viewResources.autoRegister(container, target); } for (let dep of dependencies) { if (typeof dep === 'function') { resource = viewResources.autoRegister(container, dep); if (resource.elementName !== null) { elDeps.push(resource); } } else if (dep && typeof dep === 'object') { for (let key in dep) { let exported = dep[key]; if (typeof exported === 'function') { resource = viewResources.autoRegister(container, exported); if (resource.elementName !== null) { elDeps.push(resource); } } } } else { throw new Error(`dependency neither function nor object. Received: "${typeof dep}"`); } } return Promise.all(elDeps.map(el => el.load(container, el.target))).then(() => { const factory = this.template !== null ? viewCompiler.compile(this.template, viewResources, compileInstruction) : null; this.factoryIsReady = true; this.factory = factory; return factory; }); }); } }) || _class7$2); let ViewLocator = (_temp2$1 = _class8$1 = class ViewLocator { getViewStrategy(value) { if (!value) { return null; } if (typeof value === 'object' && 'getViewStrategy' in value) { let origin = Origin.get(value.constructor); value = value.getViewStrategy(); if (typeof value === 'string') { value = new RelativeViewStrategy(value); } viewStrategy.assert(value); if (origin.moduleId) { value.makeRelativeTo(origin.moduleId); } return value; } if (typeof value === 'string') { value = new RelativeViewStrategy(value); } if (viewStrategy.validate(value)) { return value; } if (typeof value !== 'function') { value = value.constructor; } if ('$view' in value) { let c = value.$view; let view; c = typeof c === 'function' ? c.call(value) : c; if (c === null) { view = new NoViewStrategy(); } else { view = c instanceof StaticViewStrategy ? c : new StaticViewStrategy(c); } metadata.define(ViewLocator.viewStrategyMetadataKey, view, value); return view; } let origin = Origin.get(value); let strategy = metadata.get(ViewLocator.viewStrategyMetadataKey, value); if (!strategy) { if (!origin.moduleId) { throw new Error('Cannot determine default view strategy for object.', value); } strategy = this.createFallbackViewStrategy(origin); } else if (origin.moduleId) { strategy.moduleId = origin.moduleId; } return strategy; } createFallbackViewStrategy(origin) { return new ConventionalViewStrategy(this, origin); } convertOriginToViewUrl(origin) { let moduleId = origin.moduleId; let id = moduleId.endsWith('.js') || moduleId.endsWith('.ts') ? moduleId.substring(0, moduleId.length - 3) : moduleId; return id + '.html'; } }, _class8$1.viewStrategyMetadataKey = 'aurelia:view-strategy', _temp2$1); function mi(name) { throw new Error(`BindingLanguage must implement ${name}().`); } let BindingLanguage = class BindingLanguage { inspectAttribute(resources, elementName, attrName, attrValue) { mi('inspectAttribute'); } createAttributeInstruction(resources, element, info, existingInstruction) { mi('createAttributeInstruction'); } createLetExpressions(resources, element) { mi('createLetExpressions'); } inspectTextContent(resources, value) { mi('inspectTextContent'); } }; let noNodes = Object.freeze([]); let SlotCustomAttribute = class SlotCustomAttribute { static inject() { return [DOM.Element]; } constructor(element) { this.element = element; this.element.auSlotAttribute = this; } valueChanged(newValue, oldValue) {} }; let PassThroughSlot = class PassThroughSlot { constructor(anchor, name, destinationName, fallbackFactory) { this.anchor = anchor; this.anchor.viewSlot = this; this.name = name; this.destinationName = destinationName; this.fallbackFactory = fallbackFactory; this.destinationSlot = null; this.projections = 0; this.contentView = null; let attr = new SlotCustomAttribute(this.anchor); attr.value = this.destinationName; } get needsFallbackRendering() { return this.fallbackFactory && this.projections === 0; } renderFallbackContent(view, nodes, projectionSource, index) { if (this.contentView === null) { this.contentView = this.fallbackFactory.create(this.ownerView.container); this.contentView.bind(this.ownerView.bindingContext, this.ownerView.overrideContext); let slots = Object.create(null); slots[this.destinationSlot.name] = this.destinationSlot; ShadowDOM.distributeView(this.contentView, slots, projectionSource, index, this.destinationSlot.name); } } passThroughTo(destinationSlot) { this.destinationSlot = destinationSlot; } addNode(view, node, projectionSource, index) { if (this.contentView !== null) { this.contentView.removeNodes(); this.contentView.detached(); this.contentView.unbind(); this.contentView = null; } if (node.viewSlot instanceof PassThroughSlot) { node.viewSlot.passThroughTo(this); return; } this.projections++; this.destinationSlot.addNode(view, node, projectionSource, index); } removeView(view, projectionSource) { this.projections--; this.destinationSlot.removeView(view, projectionSource); if (this.needsFallbackRendering) { this.renderFallbackContent(null, noNodes, projectionSource); } } removeAll(projectionSource) { this.projections = 0; this.destinationSlot.removeAll(projectionSource); if (this.needsFallbackRendering) { this.renderFallbackContent(null, noNodes, projectionSource); } } projectFrom(view, projectionSource) { this.destinationSlot.projectFrom(view, projectionSource); } created(ownerView) { this.ownerView = ownerView; } bind(view) { if (this.contentView) { this.contentView.bind(view.bindingContext, view.overrideContext); } } attached() { if (this.contentView) { this.contentView.attached(); } } detached() { if (this.contentView) { this.contentView.detached(); } } unbind() { if (this.contentView) { this.contentView.unbind(); } } }; let ShadowSlot = class ShadowSlot { constructor(anchor, name, fallbackFactory) { this.anchor = anchor; this.anchor.isContentProjectionSource = true; this.anchor.viewSlot = this; this.name = name; this.fallbackFactory = fallbackFactory; this.contentView = null; this.projections = 0; this.children = []; this.projectFromAnchors = null; this.destinationSlots = null; } get needsFallbackRendering() { return this.fallbackFactory && this.projections === 0; } addNode(view, node, projectionSource, index, destination) { if (this.contentView !== null) { this.contentView.removeNodes(); this.contentView.detached(); this.contentView.unbind(); this.contentView = null; } if (node.viewSlot instanceof PassThroughSlot) { node.viewSlot.passThroughTo(this); return; } if (this.destinationSlots !== null) { ShadowDOM.distributeNodes(view, [node], this.destinationSlots, this, index); } else { node.auOwnerView = view; node.auProjectionSource = projectionSource; node.auAssignedSlot = this; let anchor = this._findAnchor(view, node, projectionSource, index); let parent = anchor.parentNode; parent.insertBefore(node, anchor); this.children.push(node); this.projections++; } } removeView(view, projectionSource) { if (this.destinationSlots !== null) { ShadowDOM.undistributeView(view, this.destinationSlots, this); } else if (this.contentView && this.contentView.hasSlots) { ShadowDOM.undistributeView(view, this.contentView.slots, projectionSource); } else { let found = this.children.find(x => x.auSlotProjectFrom === projectionSource); if (found) { let children = found.auProjectionChildren; for (let i = 0, ii = children.length; i < ii; ++i) { let child = children[i]; if (child.auOwnerView === view) { children.splice(i, 1); view.fragment.appendChild(child); i--;ii--; this.projections--; } } if (this.needsFallbackRendering) { this.renderFallbackContent(view, noNodes, projectionSource); } } } } removeAll(projectionSource) { if (this.destinationSlots !== null) { ShadowDOM.undistributeAll(this.destinationSlots, this); } else if (this.contentView && this.contentView.hasSlots) { ShadowDOM.undistributeAll(this.contentView.slots, projectionSource); } else { let found = this.children.find(x => x.auSlotProjectFrom === projectionSource); if (found) { let children = found.auProjectionChildren; for (let i = 0, ii = children.length; i < ii; ++i) { let child = children[i]; child.auOwnerView.fragment.appendChild(child); this.projections--; } found.auProjectionChildren = []; if (this.needsFallbackRendering) { this.renderFallbackContent(null, noNodes, projectionSource); } } } } _findAnchor(view, node, projectionSource, index) { if (projectionSource) { let found = this.children.find(x => x.auSlotProjectFrom === projectionSource); if (found) { if (index !== undefined) { let children = found.auProjectionChildren; let viewIndex = -1; let lastView; for (let i = 0, ii = children.length; i < ii; ++i) { let current = children[i]; if (current.auOwnerView !== lastView) { viewIndex++; lastView = current.auOwnerView; if (viewIndex >= index && lastView !== view) { children.splice(i, 0, node); return current; } } } } found.auProjectionChildren.push(node); return found; } } return this.anchor; } projectTo(slots) { this.destinationSlots = slots; } projectFrom(view, projectionSource) { let anchor = DOM.createComment('anchor'); let parent = this.anchor.parentNode; anchor.auSlotProjectFrom = projectionSource; anchor.auOwnerView = view; anchor.auProjectionChildren = []; parent.insertBefore(anchor, this.anchor); this.children.push(anchor); if (this.projectFromAnchors === null) { this.projectFromAnchors = []; } this.projectFromAnchors.push(anchor); } renderFallbackContent(view, nodes, projectionSource, index) { if (this.contentView === null) { this.contentView = this.fallbackFactory.create(this.ownerView.container); this.contentView.bind(this.ownerView.bindingContext, this.ownerView.overrideContext); this.contentView.insertNodesBefore(this.anchor); } if (this.contentView.hasSlots) { let slots = this.contentView.slots; let projectFromAnchors = this.projectFromAnchors; if (projectFromAnchors !== null) { for (let slotName in slots) { let slot = slots[slotName]; for (let i = 0, ii = projectFromAnchors.length; i < ii; ++i) { let anchor = projectFromAnchors[i]; slot.projectFrom(anchor.auOwnerView, anchor.auSlotProjectFrom); } } } this.fallbackSlots = slots; ShadowDOM.distributeNodes(view, nodes, slots, projectionSource, index); } } created(ownerView) { this.ownerView = ownerView; } bind(view) { if (this.contentView) { this.contentView.bind(view.bindingContext, view.overrideContext); } } attached() { if (this.contentView) { this.contentView.attached(); } } detached() { if (this.contentView) { this.contentView.detached(); } } unbind() { if (this.contentView) { this.contentView.unbind(); } } }; let ShadowDOM = (_temp3 = _class9$1 = class ShadowDOM { static getSlotName(node) { if (node.auSlotAttribute === undefined) { return ShadowDOM.defaultSlotKey; } return node.auSlotAttribute.value; } static distributeView(view, slots, projectionSource, index, destinationOverride) { let nodes; if (view === null) { nodes = noNodes; } else { let childNodes = view.fragment.childNodes; let ii = childNodes.length; nodes = new Array(ii); for (let i = 0; i < ii; ++i) { nodes[i] = childNodes[i]; } } ShadowDOM.distributeNodes(view, nodes, slots, projectionSource, index, destinationOverride); } static undistributeView(view, slots, projectionSource) { for (let slotName in slots) { slots[slotName].removeView(view, projectionSource); } } static undistributeAll(slots, projectionSource) { for (let slotName in slots) { slots[slotName].removeAll(projectionSource); } } static distributeNodes(view, nodes, slots, projectionSource, index, destinationOverride) { for (let i = 0, ii = nodes.length; i < ii; ++i) { let currentNode = nodes[i]; let nodeType = currentNode.nodeType; if (currentNode.isContentProjectionSource) { currentNode.viewSlot.projectTo(slots); for (let slotName in slots) { slots[slotName].projectFrom(view, currentNode.viewSlot); } nodes.splice(i, 1); ii--;i--; } else if (nodeType === 1 || nodeType === 3 || currentNode.viewSlot instanceof PassThroughSlot) { if (nodeType === 3 && _isAllWhitespace(currentNode)) { nodes.splice(i, 1); ii--;i--; } else { let found = slots[destinationOverride || ShadowDOM.getSlotName(currentNode)]; if (found) { found.addNode(view, currentNode, projectionSource, index); nodes.splice(i, 1); ii--;i--; } } } else { nodes.splice(i, 1); ii--;i--; } } for (let slotName in slots) { let slot = slots[slotName]; if (slot.needsFallbackRendering) { slot.renderFallbackContent(view, nodes, projectionSource, index); } } } }, _class9$1.defaultSlotKey = '__au-default-slot-key__', _temp3); function register(lookup, name, resource, type) { if (!name) { return; } let existing = lookup[name]; if (existing) { if (existing !== resource) { throw new Error(`Attempted to register ${type} when one with the same name already exists. Name: ${name}.`); } return; } lookup[name] = resource; } function validateBehaviorName(name, type) { if (/[A-Z]/.test(name)) { let newName = _hyphenate(name); getLogger('templating').warn(`'${name}' is not a valid ${type} name and has been converted to '${newName}'. Upper-case letters are not allowed because the DOM is not case-sensitive.`); return newName; } return name; } const conventionMark = '__au_resource__'; let ViewResources = class ViewResources { static convention(target, existing) { let resource; if (existing && conventionMark in existing) { return existing; } if ('$resource' in target) { let config = target.$resource; if (typeof config === 'string') { resource = existing || new HtmlBehaviorResource(); resource[conventionMark] = true; if (!resource.elementName) { resource.elementName = validateBehaviorName(config, 'custom element'); } } else { if (typeof config === 'function') { config = config.call(target); } if (typeof config === 'string') { config = { name: config }; } config = Object.assign({}, config); let resourceType = config.type || 'element'; let name = config.name; switch (resourceType) { case 'element':case 'attribute': resource = existing || new HtmlBehaviorResource(); resource[conventionMark] = true; if (resourceType === 'element') { if (!resource.elementName) { resource.elementName = name ? validateBehaviorName(name, 'custom element') : _hyphenate(target.name); } } else { if (!resource.attributeName) { resource.attributeName = name ? validateBehaviorName(name, 'custom attribute') : _hyphenate(target.name); } } if ('templateController' in config) { config.liftsContent = config.templateController; delete config.templateController; } if ('defaultBindingMode' in config && resource.attributeDefaultBindingMode !== undefined) { config.attributeDefaultBindingMode = config.defaultBindingMode; delete config.defaultBindingMode; } delete config.name; Object.assign(resource, config); break; case 'valueConverter': resource = new ValueConverterResource(camelCase(name || target.name)); break; case 'bindingBehavior': resource = new BindingBehaviorResource(camelCase(name || target.name)); break; case 'viewEngineHooks': resource = new ViewEngineHooksResource(); break; } } if (resource instanceof HtmlBehaviorResource) { let bindables = typeof config === 'string' ? undefined : config.bindables; let currentProps = resource.properties; if (Array.isArray(bindables)) { for (let i = 0, ii = bindables.length; ii > i; ++i) { let prop = bindables[i]; if (!prop || typeof prop !== 'string' && !prop.name) { throw new Error(`Invalid bindable property at "${i}" for class "${target.name}". Expected either a string or an object with "name" property.`); } let newProp = new BindableProperty(prop); let existed = false; for (let j = 0, jj = currentProps.length; jj > j; ++j) { if (currentProps[j].name === newProp.name) { existed = true; break; } } if (existed) { continue; } newProp.registerWith(target, resource); } } } } return resource; } constructor(parent, viewUrl) { this.bindingLanguage = null; this.parent = parent || null; this.hasParent = this.parent !== null; this.viewUrl = viewUrl || ''; this.lookupFunctions = { valueConverters: this.getValueConverter.bind(this), bindingBehaviors: this.getBindingBehavior.bind(this) }; this.attributes = Object.create(null); this.elements = Object.create(null); this.valueConverters = Object.create(null); this.bindingBehaviors = Object.create(null); this.attributeMap = Object.create(null); this.values = Object.create(null); this.beforeCompile = this.afterCompile = this.beforeCreate = this.afterCreate = this.beforeBind = this.beforeUnbind = false; } _tryAddHook(obj, name) { if (typeof obj[name] === 'function') { let func = obj[name].bind(obj); let counter = 1; let callbackName; while (this[callbackName = name + counter.toString()] !== undefined) { counter++; } this[name] = true; this[callbackName] = func; } } _invokeHook(name, one, two, three, four) { if (this.hasParent) { this.parent._invokeHook(name, one, two, three, four); } if (this[name]) { this[name + '1'](one, two, three, four); let callbackName = name + '2'; if (this[callbackName]) { this[callbackName](one, two, three, four); callbackName = name + '3'; if (this[callbackName]) { this[callbackName](one, two, three, four); let counter = 4; while (this[callbackName = name + counter.toString()] !== undefined) { this[callbackName](one, two, three, four); counter++; } } } } } registerViewEngineHooks(hooks) { this._tryAddHook(hooks, 'beforeCompile'); this._tryAddHook(hooks, 'afterCompile'); this._tryAddHook(hooks, 'beforeCreate'); this._tryAddHook(hooks, 'afterCreate'); this._tryAddHook(hooks, 'beforeBind'); this._tryAddHook(hooks, 'beforeUnbind'); } getBindingLanguage(bindingLanguageFallback) { return this.bindingLanguage || (this.bindingLanguage = bindingLanguageFallback); } patchInParent(newParent) { let originalParent = this.parent; this.parent = newParent || null; this.hasParent = this.parent !== null; if (newParent.parent === null) { newParent.parent = originalParent; newParent.hasParent = originalParent !== null; } } relativeToView(path) { return relativeToFile(path, this.viewUrl); } registerElement(tagName, behavior) { register(this.elements, tagName, behavior, 'an Element'); } getElement(tagName) { return this.elements[tagName] || (this.hasParent ? this.parent.getElement(tagName) : null); } mapAttribute(attribute) { return this.attributeMap[attribute] || (this.hasParent ? this.parent.mapAttribute(attribute) : null); } registerAttribute(attribute, behavior, knownAttribute) { this.attributeMap[attribute] = knownAttribute; register(this.attributes, attribute, behavior, 'an Attribute'); } getAttribute(attribute) { return this.attributes[attribute] || (this.hasParent ? this.parent.getAttribute(attribute) : null); } registerValueConverter(name, valueConverter) { register(this.valueConverters, name, valueConverter, 'a ValueConverter'); } getValueConverter(name) { return this.valueConverters[name] || (this.hasParent ? this.parent.getValueConverter(name) : null); } registerBindingBehavior(name, bindingBehavior) { register(this.bindingBehaviors, name, bindingBehavior, 'a BindingBehavior'); } getBindingBehavior(name) { return this.bindingBehaviors[name] || (this.hasParent ? this.parent.getBindingBehavior(name) : null); } registerValue(name, value) { register(this.values, name, value, 'a value'); } getValue(name) { return this.values[name] || (this.hasParent ? this.parent.getValue(name) : null); } autoRegister(container, impl) { let resourceTypeMeta = metadata.getOwn(metadata.resource, impl); if (resourceTypeMeta) { if (resourceTypeMeta instanceof HtmlBehaviorResource) { ViewResources.convention(impl, resourceTypeMeta); if (resourceTypeMeta.attributeName === null && resourceTypeMeta.elementName === null) { HtmlBehaviorResource.convention(impl.name, resourceTypeMeta); } if (resourceTypeMeta.attributeName === null && resourceTypeMeta.elementName === null) { resourceTypeMeta.elementName = _hyphenate(impl.name); } } } else { resourceTypeMeta = ViewResources.convention(impl) || HtmlBehaviorResource.convention(impl.name) || ValueConverterResource.convention(impl.name) || BindingBehaviorResource.convention(impl.name) || ViewEngineHooksResource.convention(impl.name); if (!resourceTypeMeta) { resourceTypeMeta = new HtmlBehaviorResource(); resourceTypeMeta.elementName = _hyphenate(impl.name); } metadata.define(metadata.resource, resourceTypeMeta, impl); } resourceTypeMeta.initialize(container, impl); resourceTypeMeta.register(this); return resourceTypeMeta; } }; let View = class View { constructor(container, viewFactory, fragment, controllers, bindings, children, slots) { this.container = container; this.viewFactory = viewFactory; this.resources = viewFactory.resources; this.fragment = fragment; this.firstChild = fragment.firstChild; this.lastChild = fragment.lastChild; this.controllers = controllers; this.bindings = bindings; this.children = children; this.slots = slots; this.hasSlots = false; this.fromCache = false; this.isBound = false; this.isAttached = false; this.bindingContext = null; this.overrideContext = null; this.controller = null; this.viewModelScope = null; this.animatableElement = undefined; this._isUserControlled = false; this.contentView = null; for (let key in slots) { this.hasSlots = true; break; } } returnToCache() { this.viewFactory.returnViewToCache(this); } created() { let i; let ii; let controllers = this.controllers; for (i = 0, ii = controllers.length; i < ii; ++i) { controllers[i].created(this); } } bind(bindingContext, overrideContext, _systemUpdate) { let controllers; let bindings; let children; let i; let ii; if (_systemUpdate && this._isUserControlled) { return; } if (this.isBound) { if (this.bindingContext === bindingContext) { return; } this.unbind(); } this.isBound = true; this.bindingContext = bindingContext; this.overrideContext = overrideContext || createOverrideContext(bindingContext); this.resources._invokeHook('beforeBind', this); bindings = this.bindings; for (i = 0, ii = bindings.length; i < ii; ++i) { bindings[i].bind(this); } if (this.viewModelScope !== null) { bindingContext.bind(this.viewModelScope.bindingContext, this.viewModelScope.overrideContext); this.viewModelScope = null; } controllers = this.controllers; for (i = 0, ii = controllers.length; i < ii; ++i) { controllers[i].bind(this); } children = this.children; for (i = 0, ii = children.length; i < ii; ++i) { children[i].bind(bindingContext, overrideContext, true); } if (this.hasSlots) { ShadowDOM.distributeView(this.contentView, this.slots); } } addBinding(binding) { this.bindings.push(binding); if (this.isBound) { binding.bind(this); } } unbind() { let controllers; let bindings; let children; let i; let ii; if (this.isBound) { this.isBound = false; this.resources._invokeHook('beforeUnbind', this); if (this.controller !== null) { this.controller.unbind(); } bindings = this.bindings; for (i = 0, ii = bindings.length; i < ii; ++i) { bindings[i].unbind(); } controllers = this.controllers; for (i = 0, ii = controllers.length; i < ii; ++i) { controllers[i].unbind(); } children = this.children; for (i = 0, ii = children.length; i < ii; ++i) { children[i].unbind(); } this.bindingContext = null; this.overrideContext = null; } } insertNodesBefore(refNode) { refNode.parentNode.insertBefore(this.fragment, refNode); } appendNodesTo(parent) { parent.appendChild(this.fragment); } removeNodes() { let fragment = this.fragment; let current = this.firstChild; let end = this.lastChild; let next; while (current) { next = current.nextSibling; fragment.appendChild(current); if (current === end) { break; } current = next; } } attached() { let controllers; let children; let i; let ii; if (this.isAttached) { return; } this.isAttached = true; if (this.controller !== null) { this.controller.attached(); } controllers = this.controllers; for (i = 0, ii = controllers.length; i < ii; ++i) { controllers[i].attached(); } children = this.children; for (i = 0, ii = children.length; i < ii; ++i) { children[i].attached(); } } detached() { let controllers; let children; let i; let ii; if (this.isAttached) { this.isAttached = false; if (this.controller !== null) { this.controller.detached(); } controllers = this.controllers; for (i = 0, ii = controllers.length; i < ii; ++i) { controllers[i].detached(); } children = this.children; for (i = 0, ii = children.length; i < ii; ++i) { children[i].detached(); } } } }; function getAnimatableElement(view) { if (view.animatableElement !== undefined) { return view.animatableElement; } let current = view.firstChild; while (current && current.nodeType !== 1) { current = current.nextSibling; } if (current && current.nodeType === 1) { return view.animatableElement = current.classList.contains('au-animate') ? current : null; } return view.animatableElement = null; } let ViewSlot = class ViewSlot { constructor(anchor, anchorIsContainer, animator = Animator.instance) { this.anchor = anchor; this.anchorIsContainer = anchorIsContainer; this.bindingContext = null; this.overrideContext = null; this.animator = animator; this.children = []; this.isBound = false; this.isAttached = false; this.contentSelectors = null; anchor.viewSlot = this; anchor.isContentProjectionSource = false; } animateView(view, direction = 'enter') { let animatableElement = getAnimatableElement(view); if (animatableElement !== null) { switch (direction) { case 'enter': return this.animator.enter(animatableElement); case 'leave': return this.animator.leave(animatableElement); default: throw new Error('Invalid animation direction: ' + direction); } } } transformChildNodesIntoView() { let parent = this.anchor; this.children.push({ fragment: parent, firstChild: parent.firstChild, lastChild: parent.lastChild, returnToCache() {}, removeNodes() { let last; while (last = parent.lastChild) { parent.removeChild(last); } }, created() {}, bind() {}, unbind() {}, attached() {}, detached() {} }); } bind(bindingContext, overrideContext) { let i; let ii; let children; if (this.isBound) { if (this.bindingContext === bindingContext) { return; } this.unbind(); } this.isBound = true; this.bindingContext = bindingContext = bindingContext || this.bindingContext; this.overrideContext = overrideContext = overrideContext || this.overrideContext; children = this.children; for (i = 0, ii = children.length; i < ii; ++i) { children[i].bind(bindingContext, overrideContext, true); } } unbind() { if (this.isBound) { let i; let ii; let children = this.children; this.isBound = false; this.bindingContext = null; this.overrideContext = null; for (i = 0, ii = children.length; i < ii; ++i) { children[i].unbind(); } } } add(view) { if (this.anchorIsContainer) { view.appendNodesTo(this.anchor); } else { view.insertNodesBefore(this.anchor); } this.children.push(view); if (this.isAttached) { view.attached(); return this.animateView(view, 'enter'); } } insert(index, view) { let children = this.children; let length = children.length; if (index === 0 && length === 0 || index >= length) { return this.add(view); } view.insertNodesBefore(children[index].firstChild); children.splice(index, 0, view); if (this.isAttached) { view.attached(); return this.animateView(view, 'enter'); } } move(sourceIndex, targetIndex) { if (sourceIndex === targetIndex) { return; } const children = this.children; const view = children[sourceIndex]; view.removeNodes(); view.insertNodesBefore(children[targetIndex].firstChild); children.splice(sourceIndex, 1); children.splice(targetIndex, 0, view); } remove(view, returnToCache, skipAnimation) { return this.removeAt(this.children.indexOf(view), returnToCache, skipAnimation); } removeMany(viewsToRemove, returnToCache, skipAnimation) { const children = this.children; let ii = viewsToRemove.length; let i; let rmPromises = []; viewsToRemove.forEach(child => { if (skipAnimation) { child.removeNodes(); return; } let animation = this.animateView(child, 'leave'); if (animation) { rmPromises.push(animation.then(() => child.removeNodes())); } else { child.removeNodes(); } }); let removeAction = () => { if (this.isAttached) { for (i = 0; i < ii; ++i) { viewsToRemove[i].detached(); } } if (returnToCache) { for (i = 0; i < ii; ++i) { viewsToRemove[i].returnToCache(); } } for (i = 0; i < ii; ++i) { const index = children.indexOf(viewsToRemove[i]); if (index >= 0) { children.splice(index, 1); } } }; if (rmPromises.length > 0) { return Promise.all(rmPromises).then(() => removeAction()); } return removeAction(); } removeAt(index, returnToCache, skipAnimation) { let view = this.children[index]; let removeAction = () => { index = this.children.indexOf(view); view.removeNodes(); this.children.splice(index, 1); if (this.isAttached) { view.detached(); } if (returnToCache) { view.returnToCache(); } return view; }; if (!skipAnimation) { let animation = this.animateView(view, 'leave'); if (animation) { return animation.then(() => removeAction()); } } return removeAction(); } removeAll(returnToCache, skipAnimation) { let children = this.children; let ii = children.length; let i; let rmPromises = []; children.forEach(child => { if (skipAnimation) { child.removeNodes(); return; } let animation = this.animateView(child, 'leave'); if (animation) { rmPromises.push(animation.then(() => child.removeNodes())); } else { child.removeNodes(); } }); let removeAction = () => { if (this.isAttached) { for (i = 0; i < ii; ++i) { children[i].detached(); } } if (returnToCache) { for (i = 0; i < ii; ++i) { const child = children[i]; if (child) { child.returnToCache(); } } } this.children = []; }; if (rmPromises.length > 0) { return Promise.all(rmPromises).then(() => removeAction()); } return removeAction(); } attached() { let i; let ii; let children; let child; if (this.isAttached) { return; } this.isAttached = true; children = this.children; for (i = 0, ii = children.length; i < ii; ++i) { child = children[i]; child.attached(); this.animateView(child, 'enter'); } } detached() { let i; let ii; let children; if (this.isAttached) { this.isAttached = false; children = this.children; for (i = 0, ii = children.length; i < ii; ++i) { children[i].detached(); } } } projectTo(slots) { this.projectToSlots = slots; this.add = this._projectionAdd; this.insert = this._projectionInsert; this.move = this._projectionMove; this.remove = this._projectionRemove; this.removeAt = this._projectionRemoveAt; this.removeMany = this._projectionRemoveMany; this.removeAll = this._projectionRemoveAll; this.children.forEach(view => ShadowDOM.distributeView(view, slots, this)); } _projectionAdd(view) { ShadowDOM.distributeView(view, this.projectToSlots, this); this.children.push(view); if (this.isAttached) { view.attached(); } } _projectionInsert(index, view) { if (index === 0 && !this.children.length || index >= this.children.length) { this.add(view); } else { ShadowDOM.distributeView(view, this.projectToSlots, this, index); this.children.splice(index, 0, view); if (this.isAttached) { view.attached(); } } } _projectionMove(sourceIndex, targetIndex) { if (sourceIndex === targetIndex) { return; } const children = this.children; const view = children[sourceIndex]; ShadowDOM.undistributeView(view, this.projectToSlots, this); ShadowDOM.distributeView(view, this.projectToSlots, this, targetIndex); children.splice(sourceIndex, 1); children.splice(targetIndex, 0, view); } _projectionRemove(view, returnToCache) { ShadowDOM.undistributeView(view, this.projectToSlots, this); this.children.splice(this.children.indexOf(view), 1); if (this.isAttached) { view.detached(); } if (returnToCache) { view.returnToCache(); } } _projectionRemoveAt(index, returnToCache) { let view = this.children[index]; ShadowDOM.undistributeView(view, this.projectToSlots, this); this.children.splice(index, 1); if (this.isAttached) { view.detached(); } if (returnToCache) { view.returnToCache(); } } _projectionRemoveMany(viewsToRemove, returnToCache) { viewsToRemove.forEach(view => this.remove(view, returnToCache)); } _projectionRemoveAll(returnToCache) { ShadowDOM.undistributeAll(this.projectToSlots, this); let children = this.children; let ii = children.length; for (let i = 0; i < ii; ++i) { if (returnToCache) { children[i].returnToCache(); } else if (this.isAttached) { children[i].detached(); } } this.children = []; } }; let ProviderResolver = resolver(_class11$1 = class ProviderResolver { get(container, key) { let id = key.__providerId__; return id in container ? container[id] : container[id] = container.invoke(key); } }) || _class11$1; let providerResolverInstance = new ProviderResolver(); function elementContainerGet(key) { if (key === DOM.Element) { return this.element; } if (key === BoundViewFactory) { if (this.boundViewFactory) { return this.boundViewFactory; } let factory = this.instruction.viewFactory; let partReplacements = this.partReplacements; if (partReplacements) { factory = partReplacements[factory.part] || factory; } this.boundViewFactory = new BoundViewFactory(this, factory, partReplacements); return this.boundViewFactory; } if (key === ViewSlot) { if (this.viewSlot === undefined) { this.viewSlot = new ViewSlot(this.element, this.instruction.anchorIsContainer); this.element.isContentProjectionSource = this.instruction.lifting; this.children.push(this.viewSlot); } return this.viewSlot; } if (key === ElementEvents) { return this.elementEvents || (this.elementEvents = new ElementEvents(this.element)); } if (key === CompositionTransaction) { return this.compositionTransaction || (this.compositionTransaction = this.parent.get(key)); } if (key === ViewResources) { return this.viewResources; } if (key === TargetInstruction) { return this.instruction; } return this.superGet(key); } function createElementContainer(parent, element, instruction, children, partReplacements, resources) { let container = parent.createChild(); let providers; let i; container.element = element; container.instruction = instruction; container.children = children; container.viewResources = resources; container.partReplacements = partReplacements; providers = instruction.providers; i = providers.length; while (i--) { container._resolvers.set(providers[i], providerResolverInstance); } container.superGet = container.get; container.get = elementContainerGet; return container; } function hasAttribute(name) { return this._element.hasAttribute(name); } function getAttribute(name) { return this._element.getAttribute(name); } function setAttribute(name, value) { this._element.setAttribute(name, value); } function makeElementIntoAnchor(element, elementInstruction) { let anchor = DOM.createComment('anchor'); if (elementInstruction) { let firstChild = element.firstChild; if (firstChild && firstChild.tagName === 'AU-CONTENT') { anchor.contentElement = firstChild; } anchor._element = element; anchor.hasAttribute = hasAttribute; anchor.getAttribute = getAttribute; anchor.setAttribute = setAttribute; } DOM.replaceNode(anchor, element); return anchor; } function applyInstructions(containers, element, instruction, controllers, bindings, children, shadowSlots, partReplacements, resources) { let behaviorInstructions = instruction.behaviorInstructions; let expressions = instruction.expressions; let elementContainer; let i; let ii; let current; let instance; if (instruction.contentExpression) { bindings.push(instruction.contentExpression.createBinding(element.nextSibling)); element.nextSibling.auInterpolationTarget = true; element.parentNode.removeChild(element); return; } if (instruction.shadowSlot) { let commentAnchor = DOM.createComment('slot'); let slot; if (instruction.slotDestination) { slot = new PassThroughSlot(commentAnchor, instruction.slotName, instruction.slotDestination, instruction.slotFallbackFactory); } else { slot = new ShadowSlot(commentAnchor, instruction.slotName, instruction.slotFallbackFactory); } DOM.replaceNode(commentAnchor, element); shadowSlots[instruction.slotName] = slot; controllers.push(slot); return; } if (instruction.letElement) { for (i = 0, ii = expressions.length; i < ii; ++i) { bindings.push(expressions[i].createBinding()); } element.parentNode.removeChild(element); return; } if (behaviorInstructions.length) { if (!instruction.anchorIsContainer) { element = makeElementIntoAnchor(element, instruction.elementInstruction); } containers[instruction.injectorId] = elementContainer = createElementContainer(containers[instruction.parentInjectorId], element, instruction, children, partReplacements, resources); for (i = 0, ii = behaviorInstructions.length; i < ii; ++i) { current = behaviorInstructions[i]; instance = current.type.create(elementContainer, current, element, bindings); controllers.push(instance); } } for (i = 0, ii = expressions.length; i < ii; ++i) { bindings.push(expressions[i].createBinding(element)); } } function styleStringToObject(style, target) { let attributes = style.split(';'); let firstIndexOfColon; let i; let current; let key; let value; target = target || {}; for (i = 0; i < attributes.length; i++) { current = attributes[i]; firstIndexOfColon = current.indexOf(':'); key = current.substring(0, firstIndexOfColon).trim(); value = current.substring(firstIndexOfColon + 1).trim(); target[key] = value; } return target; } function styleObjectToString(obj) { let result = ''; for (let key in obj) { result += key + ':' + obj[key] + ';'; } return result; } function applySurrogateInstruction(container, element, instruction, controllers, bindings, children) { let behaviorInstructions = instruction.behaviorInstructions; let expressions = instruction.expressions; let providers = instruction.providers; let values = instruction.values; let i; let ii; let current; let instance; let currentAttributeValue; i = providers.length; while (i--) { container._resolvers.set(providers[i], providerResolverInstance); } for (let key in values) { currentAttributeValue = element.getAttribute(key); if (currentAttributeValue) { if (key === 'class') { element.setAttribute('class', currentAttributeValue + ' ' + values[key]); } else if (key === 'style') { let styleObject = styleStringToObject(values[key]); styleStringToObject(currentAttributeValue, styleObject); element.setAttribute('style', styleObjectToString(styleObject)); } } else { element.setAttribute(key, values[key]); } } if (behaviorInstructions.length) { for (i = 0, ii = behaviorInstructions.length; i < ii; ++i) { current = behaviorInstructions[i]; instance = current.type.create(container, current, element, bindings); if (instance.contentView) { children.push(instance.contentView); } controllers.push(instance); } } for (i = 0, ii = expressions.length; i < ii; ++i) { bindings.push(expressions[i].createBinding(element)); } } let BoundViewFactory = class BoundViewFactory { constructor(parentContainer, viewFactory, partReplacements) { this.parentContainer = parentContainer; this.viewFactory = viewFactory; this.factoryCreateInstruction = { partReplacements: partReplacements }; } create() { let view = this.viewFactory.create(this.parentContainer.createChild(), this.factoryCreateInstruction); view._isUserControlled = true; return view; } get isCaching() { return this.viewFactory.isCaching; } setCacheSize(size, doNotOverrideIfAlreadySet) { this.viewFactory.setCacheSize(size, doNotOverrideIfAlreadySet); } getCachedView() { return this.viewFactory.getCachedView(); } returnViewToCache(view) { this.viewFactory.returnViewToCache(view); } }; let ViewFactory = class ViewFactory { constructor(template, instructions, resources) { this.isCaching = false; this.template = template; this.instructions = instructions; this.resources = resources; this.cacheSize = -1; this.cache = null; } setCacheSize(size, doNotOverrideIfAlreadySet) { if (size) { if (size === '*') { size = Number.MAX_VALUE; } else if (typeof size === 'string') { size = parseInt(size, 10); } } if (this.cacheSize === -1 || !doNotOverrideIfAlreadySet) { this.cacheSize = size; } if (this.cacheSize > 0) { this.cache = []; } else { this.cache = null; } this.isCaching = this.cacheSize > 0; } getCachedView() { return this.cache !== null ? this.cache.pop() || null : null; } returnViewToCache(view) { if (view.isAttached) { view.detached(); } if (view.isBound) { view.unbind(); } if (this.cache !== null && this.cache.length < this.cacheSize) { view.fromCache = true; this.cache.push(view); } } create(container, createInstruction, element) { createInstruction = createInstruction || BehaviorInstruction.normal; let cachedView = this.getCachedView(); if (cachedView !== null) { return cachedView; } let fragment = createInstruction.enhance ? this.template : this.template.cloneNode(true); let instructables = fragment.querySelectorAll('.au-target'); let instructions = this.instructions; let resources = this.resources; let controllers = []; let bindings = []; let children = []; let shadowSlots = Object.create(null); let containers = { root: container }; let partReplacements = createInstruction.partReplacements; let i; let ii; let view; let instructable; let instruction; this.resources._invokeHook('beforeCreate', this, container, fragment, createInstruction); if (element && this.surrogateInstruction !== null) { applySurrogateInstruction(container, element, this.surrogateInstruction, controllers, bindings, children); } if (createInstruction.enhance && fragment.hasAttribute('au-target-id')) { instructable = fragment; instruction = instructions[instructable.getAttribute('au-target-id')]; applyInstructions(containers, instructable, instruction, controllers, bindings, children, shadowSlots, partReplacements, resources); } for (i = 0, ii = instructables.length; i < ii; ++i) { instructable = instructables[i]; instruction = instructions[instructable.getAttribute('au-target-id')]; applyInstructions(containers, instructable, instruction, controllers, bindings, children, shadowSlots, partReplacements, resources); } view = new View(container, this, fragment, controllers, bindings, children, shadowSlots); if (!createInstruction.initiatedByBehavior) { view.created(); } this.resources._invokeHook('afterCreate', view); return view; } }; let nextInjectorId = 0; function getNextInjectorId() { return ++nextInjectorId; } let lastAUTargetID = 0; function getNextAUTargetID() { return (++lastAUTargetID).toString(); } function makeIntoInstructionTarget(element) { let value = element.getAttribute('class'); let auTargetID = getNextAUTargetID(); element.setAttribute('class', value ? value + ' au-target' : 'au-target'); element.setAttribute('au-target-id', auTargetID); return auTargetID; } function makeShadowSlot(compiler, resources, node, instructions, parentInjectorId) { let auShadowSlot = DOM.createElement('au-shadow-slot'); DOM.replaceNode(auShadowSlot, node); let auTargetID = makeIntoInstructionTarget(auShadowSlot); let instruction = TargetInstruction.shadowSlot(parentInjectorId); instruction.slotName = node.getAttribute('name') || ShadowDOM.defaultSlotKey; instruction.slotDestination = node.getAttribute('slot'); if (node.innerHTML.trim()) { let fragment = DOM.createDocumentFragment(); let child; while (child = node.firstChild) { fragment.appendChild(child); } instruction.slotFallbackFactory = compiler.compile(fragment, resources); } instructions[auTargetID] = instruction; return auShadowSlot; } const defaultLetHandler = BindingLanguage.prototype.createLetExpressions; let ViewCompiler = (_dec7$2 = inject(BindingLanguage, ViewResources), _dec7$2(_class13$1 = class ViewCompiler { constructor(bindingLanguage, resources) { this.bindingLanguage = bindingLanguage; this.resources = resources; } compile(source, resources, compileInstruction) { resources = resources || this.resources; compileInstruction = compileInstruction || ViewCompileInstruction.normal; source = typeof source === 'string' ? DOM.createTemplateFromMarkup(source) : source; let content; let part; let cacheSize; if (source.content) { part = source.getAttribute('part'); cacheSize = source.getAttribute('view-cache'); content = DOM.adoptNode(source.content); } else { content = source; } compileInstruction.targetShadowDOM = compileInstruction.targetShadowDOM && FEATURE.shadowDOM; resources._invokeHook('beforeCompile', content, resources, compileInstruction); let instructions = {}; this._compileNode(content, resources, instructions, source, 'root', !compileInstruction.targetShadowDOM); let firstChild = content.firstChild; if (firstChild && firstChild.nodeType === 1) { let targetId = firstChild.getAttribute('au-target-id'); if (targetId) { let ins = instructions[targetId]; if (ins.shadowSlot || ins.lifting || ins.elementInstruction && !ins.elementInstruction.anchorIsContainer) { content.insertBefore(DOM.createComment('view'), firstChild); } } } let factory = new ViewFactory(content, instructions, resources); factory.surrogateInstruction = compileInstruction.compileSurrogate ? this._compileSurrogate(source, resources) : null; factory.part = part; if (cacheSize) { factory.setCacheSize(cacheSize); } resources._invokeHook('afterCompile', factory); return factory; } _compileNode(node, resources, instructions, parentNode, parentInjectorId, targetLightDOM) { switch (node.nodeType) { case 1: return this._compileElement(node, resources, instructions, parentNode, parentInjectorId, targetLightDOM); case 3: let expression = resources.getBindingLanguage(this.bindingLanguage).inspectTextContent(resources, node.wholeText); if (expression) { let marker = DOM.createElement('au-marker'); let auTargetID = makeIntoInstructionTarget(marker); (node.parentNode || parentNode).insertBefore(marker, node); node.textContent = ' '; instructions[auTargetID] = TargetInstruction.contentExpression(expression); while (node.nextSibling && node.nextSibling.nodeType === 3) { (node.parentNode || parentNode).removeChild(node.nextSibling); } } else { while (node.nextSibling && node.nextSibling.nodeType === 3) { node = node.nextSibling; } } return node.nextSibling; case 11: let currentChild = node.firstChild; while (currentChild) { currentChild = this._compileNode(currentChild, resources, instructions, node, parentInjectorId, targetLightDOM); } break; default: break; } return node.nextSibling; } _compileSurrogate(node, resources) { let tagName = node.tagName.toLowerCase(); let attributes = node.attributes; let bindingLanguage = resources.getBindingLanguage(this.bindingLanguage); let knownAttribute; let property; let instruction; let i; let ii; let attr; let attrName; let attrValue; let info; let type; let expressions = []; let expression; let behaviorInstructions = []; let values = {}; let hasValues = false; let providers = []; for (i = 0, ii = attributes.length; i < ii; ++i) { attr = attributes[i]; attrName = attr.name; attrValue = attr.value; info = bindingLanguage.inspectAttribute(resources, tagName, attrName, attrValue); type = resources.getAttribute(info.attrName); if (type) { knownAttribute = resources.mapAttribute(info.attrName); if (knownAttribute) { property = type.attributes[knownAttribute]; if (property) { info.defaultBindingMode = property.defaultBindingMode; if (!info.command && !info.expression) { info.command = property.hasOptions ? 'options' : null; } if (info.command && info.command !== 'options' && type.primaryProperty) { const primaryProperty = type.primaryProperty; attrName = info.attrName = primaryProperty.attribute; info.defaultBindingMode = primaryProperty.defaultBindingMode; } } } } instruction = bindingLanguage.createAttributeInstruction(resources, node, info, undefined, type); if (instruction) { if (instruction.alteredAttr) { type = resources.getAttribute(instruction.attrName); } if (instruction.discrete) { expressions.push(instruction); } else { if (type) { instruction.type = type; this._configureProperties(instruction, resources); if (type.liftsContent) { throw new Error('You cannot place a template controller on a surrogate element.'); } else { behaviorInstructions.push(instruction); } } else { expressions.push(instruction.attributes[instruction.attrName]); } } } else { if (type) { instruction = BehaviorInstruction.attribute(attrName, type); instruction.attributes[resources.mapAttribute(attrName)] = attrValue; if (type.liftsContent) { throw new Error('You cannot place a template controller on a surrogate element.'); } else { behaviorInstructions.push(instruction); } } else if (attrName !== 'id' && attrName !== 'part' && attrName !== 'replace-part') { hasValues = true; values[attrName] = attrValue; } } } if (expressions.length || behaviorInstructions.length || hasValues) { for (i = 0, ii = behaviorInstructions.length; i < ii; ++i) { instruction = behaviorInstructions[i]; instruction.type.compile(this, resources, node, instruction); providers.push(instruction.type.target); } for (i = 0, ii = expressions.length; i < ii; ++i) { expression = expressions[i]; if (expression.attrToRemove !== undefined) { node.removeAttribute(expression.attrToRemove); } } return TargetInstruction.surrogate(providers, behaviorInstructions, expressions, values); } return null; } _compileElement(node, resources, instructions, parentNode, parentInjectorId, targetLightDOM) { let tagName = node.tagName.toLowerCase(); let attributes = node.attributes; let expressions = []; let expression; let behaviorInstructions = []; let providers = []; let bindingLanguage = resources.getBindingLanguage(this.bindingLanguage); let liftingInstruction; let viewFactory; let type; let elementInstruction; let elementProperty; let i; let ii; let attr; let attrName; let attrValue; let originalAttrName; let instruction; let info; let property; let knownAttribute; let auTargetID; let injectorId; if (tagName === 'slot') { if (targetLightDOM) { node = makeShadowSlot(this, resources, node, instructions, parentInjectorId); } return node.nextSibling; } else if (tagName === 'template') { if (!('content' in node)) { throw new Error('You cannot place a template element within ' + node.namespaceURI + ' namespace'); } viewFactory = this.compile(node, resources); viewFactory.part = node.getAttribute('part'); } else { type = resources.getElement(node.getAttribute('as-element') || tagName); if (tagName === 'let' && !type && bindingLanguage.createLetExpressions !== defaultLetHandler) { expressions = bindingLanguage.createLetExpressions(resources, node); auTargetID = makeIntoInstructionTarget(node); instructions[auTargetID] = TargetInstruction.letElement(expressions); return node.nextSibling; } if (type) { elementInstruction = BehaviorInstruction.element(node, type); type.processAttributes(this, resources, node, attributes, elementInstruction); behaviorInstructions.push(elementInstruction); } } for (i = 0, ii = attributes.length; i < ii; ++i) { attr = attributes[i]; originalAttrName = attrName = attr.name; attrValue = attr.value; info = bindingLanguage.inspectAttribute(resources, tagName, attrName, attrValue); if (targetLightDOM && info.attrName === 'slot') { info.attrName = attrName = 'au-slot'; } type = resources.getAttribute(info.attrName); elementProperty = null; if (type) { knownAttribute = resources.mapAttribute(info.attrName); if (knownAttribute) { property = type.attributes[knownAttribute]; if (property) { info.defaultBindingMode = property.defaultBindingMode; if (!info.command && !info.expression) { info.command = property.hasOptions ? 'options' : null; } if (info.command && info.command !== 'options' && type.primaryProperty) { const primaryProperty = type.primaryProperty; attrName = info.attrName = primaryProperty.attribute; info.defaultBindingMode = primaryProperty.defaultBindingMode; } } } } else if (elementInstruction) { elementProperty = elementInstruction.type.attributes[info.attrName]; if (elementProperty) { info.defaultBindingMode = elementProperty.defaultBindingMode; } } if (elementProperty) { instruction = bindingLanguage.createAttributeInstruction(resources, node, info, elementInstruction); } else { instruction = bindingLanguage.createAttributeInstruction(resources, node, info, undefined, type); } if (instruction) { if (instruction.alteredAttr) { type = resources.getAttribute(instruction.attrName); } if (instruction.discrete) { expressions.push(instruction); } else { if (type) { instruction.type = type; this._configureProperties(instruction, resources); if (type.liftsContent) { instruction.originalAttrName = originalAttrName; liftingInstruction = instruction; break; } else { behaviorInstructions.push(instruction); } } else if (elementProperty) { elementInstruction.attributes[info.attrName].targetProperty = elementProperty.name; } else { expressions.push(instruction.attributes[instruction.attrName]); } } } else { if (type) { instruction = BehaviorInstruction.attribute(attrName, type); instruction.attributes[resources.mapAttribute(attrName)] = attrValue; if (type.liftsContent) { instruction.originalAttrName = originalAttrName; liftingInstruction = instruction; break; } else { behaviorInstructions.push(instruction); } } else if (elementProperty) { elementInstruction.attributes[attrName] = attrValue; } } } if (liftingInstruction) { liftingInstruction.viewFactory = viewFactory; node = liftingInstruction.type.compile(this, resources, node, liftingInstruction, parentNode); auTargetID = makeIntoInstructionTarget(node); instructions[auTargetID] = TargetInstruction.lifting(parentInjectorId, liftingInstruction); } else { let skipContentProcessing = false; if (expressions.length || behaviorInstructions.length) { injectorId = behaviorInstructions.length ? getNextInjectorId() : false; for (i = 0, ii = behaviorInstructions.length; i < ii; ++i) { instruction = behaviorInstructions[i]; instruction.type.compile(this, resources, node, instruction, parentNode); providers.push(instruction.type.target); skipContentProcessing = skipContentProcessing || instruction.skipContentProcessing; } for (i = 0, ii = expressions.length; i < ii; ++i) { expression = expressions[i]; if (expression.attrToRemove !== undefined) { node.removeAttribute(expression.attrToRemove); } } auTargetID = makeIntoInstructionTarget(node); instructions[auTargetID] = TargetInstruction.normal(injectorId, parentInjectorId, providers, behaviorInstructions, expressions, elementInstruction); } if (skipContentProcessing) { return node.nextSibling; } let currentChild = node.firstChild; while (currentChild) { currentChild = this._compileNode(currentChild, resources, instructions, node, injectorId || parentInjectorId, targetLightDOM); } } return node.nextSibling; } _configureProperties(instruction, resources) { let type = instruction.type; let attrName = instruction.attrName; let attributes = instruction.attributes; let property; let key; let value; let knownAttribute = resources.mapAttribute(attrName); if (knownAttribute && attrName in attributes && knownAttribute !== attrName) { attributes[knownAttribute] = attributes[attrName]; delete attributes[attrName]; } for (key in attributes) { value = attributes[key]; if (value !== null && typeof value === 'object') { property = type.attributes[key]; if (property !== undefined) { value.targetProperty = property.name; } else { value.targetProperty = key; } } } } }) || _class13$1); let ResourceModule = class ResourceModule { constructor(moduleId) { this.id = moduleId; this.moduleInstance = null; this.mainResource = null; this.resources = null; this.viewStrategy = null; this.isInitialized = false; this.onLoaded = null; this.loadContext = null; } initialize(container) { let current = this.mainResource; let resources = this.resources; let vs = this.viewStrategy; if (this.isInitialized) { return; } this.isInitialized = true; if (current !== undefined) { current.metadata.viewStrategy = vs; current.initialize(container); } for (let i = 0, ii = resources.length; i < ii; ++i) { current = resources[i]; current.metadata.viewStrategy = vs; current.initialize(container); } } register(registry, name) { let main = this.mainResource; let resources = this.resources; if (main !== undefined) { main.register(registry, name); name = null; } for (let i = 0, ii = resources.length; i < ii; ++i) { resources[i].register(registry, name); name = null; } } load(container, loadContext) { if (this.onLoaded !== null) { return this.loadContext === loadContext ? Promise.resolve() : this.onLoaded; } let main = this.mainResource; let resources = this.resources; let loads; if (main !== undefined) { loads = new Array(resources.length + 1); loads[0] = main.load(container, loadContext); for (let i = 0, ii = resources.length; i < ii; ++i) { loads[i + 1] = resources[i].load(container, loadContext); } } else { loads = new Array(resources.length); for (let i = 0, ii = resources.length; i < ii; ++i) { loads[i] = resources[i].load(container, loadContext); } } this.loadContext = loadContext; this.onLoaded = Promise.all(loads); return this.onLoaded; } }; let ResourceDescription = class ResourceDescription { constructor(key, exportedValue, resourceTypeMeta) { if (!resourceTypeMeta) { resourceTypeMeta = metadata.get(metadata.resource, exportedValue); if (!resourceTypeMeta) { resourceTypeMeta = new HtmlBehaviorResource(); resourceTypeMeta.elementName = _hyphenate(key); metadata.define(metadata.resource, resourceTypeMeta, exportedValue); } } if (resourceTypeMeta instanceof HtmlBehaviorResource) { if (resourceTypeMeta.elementName === undefined) { resourceTypeMeta.elementName = _hyphenate(key); } else if (resourceTypeMeta.attributeName === undefined) { resourceTypeMeta.attributeName = _hyphenate(key); } else if (resourceTypeMeta.attributeName === null && resourceTypeMeta.elementName === null) { HtmlBehaviorResource.convention(key, resourceTypeMeta); } } else if (!resourceTypeMeta.name) { resourceTypeMeta.name = _hyphenate(key); } this.metadata = resourceTypeMeta; this.value = exportedValue; } initialize(container) { this.metadata.initialize(container, this.value); } register(registry, name) { this.metadata.register(registry, name); } load(container, loadContext) { return this.metadata.load(container, this.value, loadContext); } }; let ModuleAnalyzer = class ModuleAnalyzer { constructor() { this.cache = Object.create(null); } getAnalysis(moduleId) { return this.cache[moduleId]; } analyze(moduleId, moduleInstance, mainResourceKey) { let mainResource; let fallbackValue; let fallbackKey; let resourceTypeMeta; let key; let exportedValue; let resources = []; let conventional; let vs; let resourceModule; resourceModule = this.cache[moduleId]; if (resourceModule) { return resourceModule; } resourceModule = new ResourceModule(moduleId); this.cache[moduleId] = resourceModule; if (typeof moduleInstance === 'function') { moduleInstance = { 'default': moduleInstance }; } if (mainResourceKey) { mainResource = new ResourceDescription(mainResourceKey, moduleInstance[mainResourceKey]); } for (key in moduleInstance) { exportedValue = moduleInstance[key]; if (key === mainResourceKey || typeof exportedValue !== 'function') { continue; } resourceTypeMeta = metadata.get(metadata.resource, exportedValue); if (resourceTypeMeta) { if (resourceTypeMeta instanceof HtmlBehaviorResource) { ViewResources.convention(exportedValue, resourceTypeMeta); if (resourceTypeMeta.attributeName === null && resourceTypeMeta.elementName === null) { HtmlBehaviorResource.convention(key, resourceTypeMeta); } if (resourceTypeMeta.attributeName === null && resourceTypeMeta.elementName === null) { resourceTypeMeta.elementName = _hyphenate(key); } } if (!mainResource && resourceTypeMeta instanceof HtmlBehaviorResource && resourceTypeMeta.elementName !== null) { mainResource = new ResourceDescription(key, exportedValue, resourceTypeMeta); } else { resources.push(new ResourceDescription(key, exportedValue, resourceTypeMeta)); } } else if (viewStrategy.decorates(exportedValue)) { vs = exportedValue; } else if (exportedValue instanceof TemplateRegistryEntry) { vs = new TemplateRegistryViewStrategy(moduleId, exportedValue); } else { if (conventional = ViewResources.convention(exportedValue)) { if (conventional.elementName !== null && !mainResource) { mainResource = new ResourceDescription(key, exportedValue, conventional); } else { resources.push(new ResourceDescription(key, exportedValue, conventional)); } metadata.define(metadata.resource, conventional, exportedValue); } else if (conventional = HtmlBehaviorResource.convention(key)) { if (conventional.elementName !== null && !mainResource) { mainResource = new ResourceDescription(key, exportedValue, conventional); } else { resources.push(new ResourceDescription(key, exportedValue, conventional)); } metadata.define(metadata.resource, conventional, exportedValue); } else if (conventional = ValueConverterResource.convention(key) || BindingBehaviorResource.convention(key) || ViewEngineHooksResource.convention(key)) { resources.push(new ResourceDescription(key, exportedValue, conventional)); metadata.define(metadata.resource, conventional, exportedValue); } else if (!fallbackValue) { fallbackValue = exportedValue; fallbackKey = key; } } } if (!mainResource && fallbackValue) { mainResource = new ResourceDescription(fallbackKey, fallbackValue); } resourceModule.moduleInstance = moduleInstance; resourceModule.mainResource = mainResource; resourceModule.resources = resources; resourceModule.viewStrategy = vs; return resourceModule; } }; let logger$1 = getLogger('templating'); function ensureRegistryEntry(loader, urlOrRegistryEntry) { if (urlOrRegistryEntry instanceof TemplateRegistryEntry) { return Promise.resolve(urlOrRegistryEntry); } return loader.loadTemplate(urlOrRegistryEntry); } let ProxyViewFactory = class ProxyViewFactory { constructor(promise) { promise.then(x => this.viewFactory = x); } create(container, bindingContext, createInstruction, element) { return this.viewFactory.create(container, bindingContext, createInstruction, element); } get isCaching() { return this.viewFactory.isCaching; } setCacheSize(size, doNotOverrideIfAlreadySet) { this.viewFactory.setCacheSize(size, doNotOverrideIfAlreadySet); } getCachedView() { return this.viewFactory.getCachedView(); } returnViewToCache(view) { this.viewFactory.returnViewToCache(view); } }; let auSlotBehavior = null; let ViewEngine = (_dec8$1 = inject(Loader, Container, ViewCompiler, ModuleAnalyzer, ViewResources), _dec8$1(_class14 = (_temp4 = _class15 = class ViewEngine { constructor(loader, container, viewCompiler, moduleAnalyzer, appResources) { this.loader = loader; this.container = container; this.viewCompiler = viewCompiler; this.moduleAnalyzer = moduleAnalyzer; this.appResources = appResources; this._pluginMap = {}; if (auSlotBehavior === null) { auSlotBehavior = new HtmlBehaviorResource(); auSlotBehavior.attributeName = 'au-slot'; metadata.define(metadata.resource, auSlotBehavior, SlotCustomAttribute); } auSlotBehavior.initialize(container, SlotCustomAttribute); auSlotBehavior.register(appResources); } addResourcePlugin(extension, implementation) { let name = extension.replace('.', '') + '-resource-plugin'; this._pluginMap[extension] = name; this.loader.addPlugin(name, implementation); } loadViewFactory(urlOrRegistryEntry, compileInstruction, loadContext, target) { loadContext = loadContext || new ResourceLoadContext(); return ensureRegistryEntry(this.loader, urlOrRegistryEntry).then(registryEntry => { const url = registryEntry.address; if (registryEntry.onReady) { if (!loadContext.hasDependency(url)) { loadContext.addDependency(url); return registryEntry.onReady; } if (registryEntry.template === null) { return registryEntry.onReady; } return Promise.resolve(new ProxyViewFactory(registryEntry.onReady)); } loadContext.addDependency(url); registryEntry.onReady = this.loadTemplateResources(registryEntry, compileInstruction, loadContext, target).then(resources => { registryEntry.resources = resources; if (registryEntry.template === null) { return registryEntry.factory = null; } let viewFactory = this.viewCompiler.compile(registryEntry.template, resources, compileInstruction); return registryEntry.factory = viewFactory; }); return registryEntry.onReady; }); } loadTemplateResources(registryEntry, compileInstruction, loadContext, target) { let resources = new ViewResources(this.appResources, registryEntry.address); let dependencies = registryEntry.dependencies; let importIds; let names; compileInstruction = compileInstruction || ViewCompileInstruction.normal; if (dependencies.length === 0 && !compileInstruction.associatedModuleId) { return Promise.resolve(resources); } importIds = dependencies.map(x => x.src); names = dependencies.map(x => x.name); logger$1.debug(`importing resources for ${registryEntry.address}`, importIds); if (target) { let viewModelRequires = metadata.get(ViewEngine.viewModelRequireMetadataKey, target); if (viewModelRequires) { let templateImportCount = importIds.length; for (let i = 0, ii = viewModelRequires.length; i < ii; ++i) { let req = viewModelRequires[i]; let importId = typeof req === 'function' ? Origin.get(req).moduleId : relativeToFile(req.src || req, registryEntry.address); if (importIds.indexOf(importId) === -1) { importIds.push(importId); names.push(req.as); } } logger$1.debug(`importing ViewModel resources for ${compileInstruction.associatedModuleId}`, importIds.slice(templateImportCount)); } } return this.importViewResources(importIds, names, resources, compileInstruction, loadContext); } importViewModelResource(moduleImport, moduleMember) { return this.loader.loadModule(moduleImport).then(viewModelModule => { let normalizedId = Origin.get(viewModelModule).moduleId; let resourceModule = this.moduleAnalyzer.analyze(normalizedId, viewModelModule, moduleMember); if (!resourceModule.mainResource) { throw new Error(`No view model found in module "${moduleImport}".`); } resourceModule.initialize(this.container); return resourceModule.mainResource; }); } importViewResources(moduleIds, names, resources, compileInstruction, loadContext) { loadContext = loadContext || new ResourceLoadContext(); compileInstruction = compileInstruction || ViewCompileInstruction.normal; moduleIds = moduleIds.map(x => this._applyLoaderPlugin(x)); return this.loader.loadAllModules(moduleIds).then(imports => { let i; let ii; let analysis; let normalizedId; let current; let associatedModule; let container = this.container; let moduleAnalyzer = this.moduleAnalyzer; let allAnalysis = new Array(imports.length); for (i = 0, ii = imports.length; i < ii; ++i) { current = imports[i]; normalizedId = Origin.get(current).moduleId; analysis = moduleAnalyzer.analyze(normalizedId, current); analysis.initialize(container); analysis.register(resources, names[i]); allAnalysis[i] = analysis; } if (compileInstruction.associatedModuleId) { associatedModule = moduleAnalyzer.getAnalysis(compileInstruction.associatedModuleId); if (associatedModule) { associatedModule.register(resources); } } for (i = 0, ii = allAnalysis.length; i < ii; ++i) { allAnalysis[i] = allAnalysis[i].load(container, loadContext); } return Promise.all(allAnalysis).then(() => resources); }); } _applyLoaderPlugin(id) { let index = id.lastIndexOf('.'); if (index !== -1) { let ext = id.substring(index); let pluginName = this._pluginMap[ext]; if (pluginName === undefined) { return id; } return this.loader.applyPluginToUrl(id, pluginName); } return id; } }, _class15.viewModelRequireMetadataKey = 'aurelia:view-model-require', _temp4)) || _class14); let Controller = class Controller { constructor(behavior, instruction, viewModel, container) { this.behavior = behavior; this.instruction = instruction; this.viewModel = viewModel; this.isAttached = false; this.view = null; this.isBound = false; this.scope = null; this.container = container; this.elementEvents = container.elementEvents || null; let observerLookup = behavior.observerLocator.getOrCreateObserversLookup(viewModel); let handlesBind = behavior.handlesBind; let attributes = instruction.attributes; let boundProperties = this.boundProperties = []; let properties = behavior.properties; let i; let ii; behavior._ensurePropertiesDefined(viewModel, observerLookup); for (i = 0, ii = properties.length; i < ii; ++i) { properties[i]._initialize(viewModel, observerLookup, attributes, handlesBind, boundProperties); } } created(owningView) { if (this.behavior.handlesCreated) { this.viewModel.created(owningView, this.view); } } automate(overrideContext, owningView) { this.view.bindingContext = this.viewModel; this.view.overrideContext = overrideContext || createOverrideContext(this.viewModel); this.view._isUserControlled = true; if (this.behavior.handlesCreated) { this.viewModel.created(owningView || null, this.view); } this.bind(this.view); } bind(scope) { let skipSelfSubscriber = this.behavior.handlesBind; let boundProperties = this.boundProperties; let i; let ii; let x; let observer; let selfSubscriber; if (this.isBound) { if (this.scope === scope) { return; } this.unbind(); } this.isBound = true; this.scope = scope; for (i = 0, ii = boundProperties.length; i < ii; ++i) { x = boundProperties[i]; observer = x.observer; selfSubscriber = observer.selfSubscriber; observer.publishing = false; if (skipSelfSubscriber) { observer.selfSubscriber = null; } x.binding.bind(scope); observer.call(); observer.publishing = true; observer.selfSubscriber = selfSubscriber; } let overrideContext; if (this.view !== null) { if (skipSelfSubscriber) { this.view.viewModelScope = scope; } if (this.viewModel === scope.overrideContext.bindingContext) { overrideContext = scope.overrideContext; } else if (this.instruction.inheritBindingContext) { overrideContext = createOverrideContext(this.viewModel, scope.overrideContext); } else { overrideContext = createOverrideContext(this.viewModel); overrideContext.__parentOverrideContext = scope.overrideContext; } this.view.bind(this.viewModel, overrideContext); } else if (skipSelfSubscriber) { overrideContext = scope.overrideContext; if (scope.overrideContext.__parentOverrideContext !== undefined && this.viewModel.viewFactory && this.viewModel.viewFactory.factoryCreateInstruction.partReplacements) { overrideContext = Object.assign({}, scope.overrideContext); overrideContext.parentOverrideContext = scope.overrideContext.__parentOverrideContext; } this.viewModel.bind(scope.bindingContext, overrideContext); } } unbind() { if (this.isBound) { let boundProperties = this.boundProperties; let i; let ii; this.isBound = false; this.scope = null; if (this.view !== null) { this.view.unbind(); } if (this.behavior.handlesUnbind) { this.viewModel.unbind(); } if (this.elementEvents !== null) { this.elementEvents.disposeAll(); } for (i = 0, ii = boundProperties.length; i < ii; ++i) { boundProperties[i].binding.unbind(); } } } attached() { if (this.isAttached) { return; } this.isAttached = true; if (this.behavior.handlesAttached) { this.viewModel.attached(); } if (this.view !== null) { this.view.attached(); } } detached() { if (this.isAttached) { this.isAttached = false; if (this.view !== null) { this.view.detached(); } if (this.behavior.handlesDetached) { this.viewModel.detached(); } } } }; let BehaviorPropertyObserver = (_dec9$1 = subscriberCollection(), _dec9$1(_class16 = class BehaviorPropertyObserver { constructor(taskQueue, obj, propertyName, selfSubscriber, initialValue) { this.taskQueue = taskQueue; this.obj = obj; this.propertyName = propertyName; this.notqueued = true; this.publishing = false; this.selfSubscriber = selfSubscriber; this.currentValue = this.oldValue = initialValue; } getValue() { return this.currentValue; } setValue(newValue) { let oldValue = this.currentValue; if (!Object.is(newValue, oldValue)) { this.oldValue = oldValue; this.currentValue = newValue; if (this.publishing && this.notqueued) { if (this.taskQueue.flushing) { this.call(); } else { this.notqueued = false; this.taskQueue.queueMicroTask(this); } } } } call() { let oldValue = this.oldValue; let newValue = this.currentValue; this.notqueued = true; if (Object.is(newValue, oldValue)) { return; } if (this.selfSubscriber) { this.selfSubscriber(newValue, oldValue); } this.callSubscribers(newValue, oldValue); this.oldValue = newValue; } subscribe(context, callable) { this.addSubscriber(context, callable); } unsubscribe(context, callable) { this.removeSubscriber(context, callable); } }) || _class16); function getObserver(instance, name) { let lookup = instance.__observers__; if (lookup === undefined) { let ctor = Object.getPrototypeOf(instance).constructor; let behavior = metadata.get(metadata.resource, ctor); if (!behavior.isInitialized) { behavior.initialize(Container.instance || new Container(), instance.constructor); } lookup = behavior.observerLocator.getOrCreateObserversLookup(instance); behavior._ensurePropertiesDefined(instance, lookup); } return lookup[name]; } let BindableProperty = class BindableProperty { constructor(nameOrConfig) { if (typeof nameOrConfig === 'string') { this.name = nameOrConfig; } else { Object.assign(this, nameOrConfig); } this.attribute = this.attribute || _hyphenate(this.name); let defaultBindingMode = this.defaultBindingMode; if (defaultBindingMode === null || defaultBindingMode === undefined) { this.defaultBindingMode = bindingMode.oneWay; } else if (typeof defaultBindingMode === 'string') { this.defaultBindingMode = bindingMode[defaultBindingMode] || bindingMode.oneWay; } this.changeHandler = this.changeHandler || null; this.owner = null; this.descriptor = null; } registerWith(target, behavior, descriptor) { behavior.properties.push(this); behavior.attributes[this.attribute] = this; this.owner = behavior; if (descriptor) { this.descriptor = descriptor; return this._configureDescriptor(descriptor); } return undefined; } _configureDescriptor(descriptor) { let name = this.name; descriptor.configurable = true; descriptor.enumerable = true; if ('initializer' in descriptor) { this.defaultValue = descriptor.initializer; delete descriptor.initializer; delete descriptor.writable; } if ('value' in descriptor) { this.defaultValue = descriptor.value; delete descriptor.value; delete descriptor.writable; } descriptor.get = function () { return getObserver(this, name).getValue(); }; descriptor.set = function (value) { getObserver(this, name).setValue(value); }; descriptor.get.getObserver = function (obj) { return getObserver(obj, name); }; return descriptor; } defineOn(target, behavior) { let name = this.name; let handlerName; if (this.changeHandler === null) { handlerName = name + 'Changed'; if (handlerName in target.prototype) { this.changeHandler = handlerName; } } if (this.descriptor === null) { Object.defineProperty(target.prototype, name, this._configureDescriptor(behavior, {})); } } createObserver(viewModel) { let selfSubscriber = null; let defaultValue = this.defaultValue; let changeHandlerName = this.changeHandler; let name = this.name; let initialValue; if (this.hasOptions) { return undefined; } if (changeHandlerName in viewModel) { if ('propertyChanged' in viewModel) { selfSubscriber = (newValue, oldValue) => { viewModel[changeHandlerName](newValue, oldValue); viewModel.propertyChanged(name, newValue, oldValue); }; } else { selfSubscriber = (newValue, oldValue) => viewModel[changeHandlerName](newValue, oldValue); } } else if ('propertyChanged' in viewModel) { selfSubscriber = (newValue, oldValue) => viewModel.propertyChanged(name, newValue, oldValue); } else if (changeHandlerName !== null) { throw new Error(`Change handler ${changeHandlerName} was specified but not declared on the class.`); } if (defaultValue !== undefined) { initialValue = typeof defaultValue === 'function' ? defaultValue.call(viewModel) : defaultValue; } return new BehaviorPropertyObserver(this.owner.taskQueue, viewModel, this.name, selfSubscriber, initialValue); } _initialize(viewModel, observerLookup, attributes, behaviorHandlesBind, boundProperties) { let selfSubscriber; let observer; let attribute; let defaultValue = this.defaultValue; if (this.isDynamic) { for (let key in attributes) { this._createDynamicProperty(viewModel, observerLookup, behaviorHandlesBind, key, attributes[key], boundProperties); } } else if (!this.hasOptions) { observer = observerLookup[this.name]; if (attributes !== null) { selfSubscriber = observer.selfSubscriber; attribute = attributes[this.attribute]; if (behaviorHandlesBind) { observer.selfSubscriber = null; } if (typeof attribute === 'string') { viewModel[this.name] = attribute; observer.call(); } else if (attribute) { boundProperties.push({ observer: observer, binding: attribute.createBinding(viewModel) }); } else if (defaultValue !== undefined) { observer.call(); } observer.selfSubscriber = selfSubscriber; } observer.publishing = true; } } _createDynamicProperty(viewModel, observerLookup, behaviorHandlesBind, name, attribute, boundProperties) { let changeHandlerName = name + 'Changed'; let selfSubscriber = null; let observer; let info; if (changeHandlerName in viewModel) { if ('propertyChanged' in viewModel) { selfSubscriber = (newValue, oldValue) => { viewModel[changeHandlerName](newValue, oldValue); viewModel.propertyChanged(name, newValue, oldValue); }; } else { selfSubscriber = (newValue, oldValue) => viewModel[changeHandlerName](newValue, oldValue); } } else if ('propertyChanged' in viewModel) { selfSubscriber = (newValue, oldValue) => viewModel.propertyChanged(name, newValue, oldValue); } observer = observerLookup[name] = new BehaviorPropertyObserver(this.owner.taskQueue, viewModel, name, selfSubscriber); Object.defineProperty(viewModel, name, { configurable: true, enumerable: true, get: observer.getValue.bind(observer), set: observer.setValue.bind(observer) }); if (behaviorHandlesBind) { observer.selfSubscriber = null; } if (typeof attribute === 'string') { viewModel[name] = attribute; observer.call(); } else if (attribute) { info = { observer: observer, binding: attribute.createBinding(viewModel) }; boundProperties.push(info); } observer.publishing = true; observer.selfSubscriber = selfSubscriber; } }; let lastProviderId = 0; function nextProviderId() { return ++lastProviderId; } function doProcessContent() { return true; } function doProcessAttributes() {} let HtmlBehaviorResource = class HtmlBehaviorResource { constructor() { this.elementName = null; this.attributeName = null; this.attributeDefaultBindingMode = undefined; this.liftsContent = false; this.targetShadowDOM = false; this.shadowDOMOptions = null; this.processAttributes = doProcessAttributes; this.processContent = doProcessContent; this.usesShadowDOM = false; this.childBindings = null; this.hasDynamicOptions = false; this.containerless = false; this.properties = []; this.attributes = {}; this.isInitialized = false; this.primaryProperty = null; } static convention(name, existing) { let behavior; if (name.endsWith('CustomAttribute')) { behavior = existing || new HtmlBehaviorResource(); behavior.attributeName = _hyphenate(name.substring(0, name.length - 15)); } if (name.endsWith('CustomElement')) { behavior = existing || new HtmlBehaviorResource(); behavior.elementName = _hyphenate(name.substring(0, name.length - 13)); } return behavior; } addChildBinding(behavior) { if (this.childBindings === null) { this.childBindings = []; } this.childBindings.push(behavior); } initialize(container, target) { let proto = target.prototype; let properties = this.properties; let attributeName = this.attributeName; let attributeDefaultBindingMode = this.attributeDefaultBindingMode; let i; let ii; let current; if (this.isInitialized) { return; } this.isInitialized = true; target.__providerId__ = nextProviderId(); this.observerLocator = container.get(ObserverLocator); this.taskQueue = container.get(TaskQueue); this.target = target; this.usesShadowDOM = this.targetShadowDOM && FEATURE.shadowDOM; this.handlesCreated = 'created' in proto; this.handlesBind = 'bind' in proto; this.handlesUnbind = 'unbind' in proto; this.handlesAttached = 'attached' in proto; this.handlesDetached = 'detached' in proto; this.htmlName = this.elementName || this.attributeName; if (attributeName !== null) { if (properties.length === 0) { new BindableProperty({ name: 'value', changeHandler: 'valueChanged' in proto ? 'valueChanged' : null, attribute: attributeName, defaultBindingMode: attributeDefaultBindingMode }).registerWith(target, this); } current = properties[0]; if (properties.length === 1 && current.name === 'value') { current.isDynamic = current.hasOptions = this.hasDynamicOptions; current.defineOn(target, this); } else { for (i = 0, ii = properties.length; i < ii; ++i) { properties[i].defineOn(target, this); if (properties[i].primaryProperty) { if (this.primaryProperty) { throw new Error('Only one bindable property on a custom element can be defined as the default'); } this.primaryProperty = properties[i]; } } current = new BindableProperty({ name: 'value', changeHandler: 'valueChanged' in proto ? 'valueChanged' : null, attribute: attributeName, defaultBindingMode: attributeDefaultBindingMode }); current.hasOptions = true; current.registerWith(target, this); } } else { for (i = 0, ii = properties.length; i < ii; ++i) { properties[i].defineOn(target, this); } this._copyInheritedProperties(container, target); } } register(registry, name) { if (this.attributeName !== null) { registry.registerAttribute(name || this.attributeName, this, this.attributeName); if (Array.isArray(this.aliases)) { this.aliases.forEach(alias => { registry.registerAttribute(alias, this, this.attributeName); }); } } if (this.elementName !== null) { registry.registerElement(name || this.elementName, this); } } load(container, target, loadContext, viewStrategy, transientView) { let options; if (this.elementName !== null) { viewStrategy = container.get(ViewLocator).getViewStrategy(viewStrategy || this.viewStrategy || target); options = new ViewCompileInstruction(this.targetShadowDOM, true); if (!viewStrategy.moduleId) { viewStrategy.moduleId = Origin.get(target).moduleId; } return viewStrategy.loadViewFactory(container.get(ViewEngine), options, loadContext, target).then(viewFactory => { if (!transientView || !this.viewFactory) { this.viewFactory = viewFactory; } return viewFactory; }); } return Promise.resolve(this); } compile(compiler, resources, node, instruction, parentNode) { if (this.liftsContent) { if (!instruction.viewFactory) { let template = DOM.createElement('template'); let fragment = DOM.createDocumentFragment(); let cacheSize = node.getAttribute('view-cache'); let part = node.getAttribute('part'); node.removeAttribute(instruction.originalAttrName); DOM.replaceNode(template, node, parentNode); fragment.appendChild(node); instruction.viewFactory = compiler.compile(fragment, resources); if (part) { instruction.viewFactory.part = part; node.removeAttribute('part'); } if (cacheSize) { instruction.viewFactory.setCacheSize(cacheSize); node.removeAttribute('view-cache'); } node = template; } } else if (this.elementName !== null) { let partReplacements = {}; if (this.processContent(compiler, resources, node, instruction) && node.hasChildNodes()) { let currentChild = node.firstChild; let contentElement = this.usesShadowDOM ? null : DOM.createElement('au-content'); let nextSibling; let toReplace; while (currentChild) { nextSibling = currentChild.nextSibling; if (currentChild.tagName === 'TEMPLATE' && (toReplace = currentChild.getAttribute('replace-part'))) { partReplacements[toReplace] = compiler.compile(currentChild, resources); DOM.removeNode(currentChild, parentNode); instruction.partReplacements = partReplacements; } else if (contentElement !== null) { if (currentChild.nodeType === 3 && _isAllWhitespace(currentChild)) { DOM.removeNode(currentChild, parentNode); } else { contentElement.appendChild(currentChild); } } currentChild = nextSibling; } if (contentElement !== null && contentElement.hasChildNodes()) { node.appendChild(contentElement); } instruction.skipContentProcessing = false; } else { instruction.skipContentProcessing = true; } } else if (!this.processContent(compiler, resources, node, instruction)) { instruction.skipContentProcessing = true; } return node; } create(container, instruction, element, bindings) { let viewHost; let au = null; instruction = instruction || BehaviorInstruction.normal; element = element || null; bindings = bindings || null; if (this.elementName !== null && element) { if (this.usesShadowDOM) { viewHost = element.attachShadow(this.shadowDOMOptions); container.registerInstance(DOM.boundary, viewHost); } else { viewHost = element; if (this.targetShadowDOM) { container.registerInstance(DOM.boundary, viewHost); } } } if (element !== null) { element.au = au = element.au || {}; } let viewModel = instruction.viewModel || container.get(this.target); let controller = new Controller(this, instruction, viewModel, container); let childBindings = this.childBindings; let viewFactory; if (this.liftsContent) { au.controller = controller; } else if (this.elementName !== null) { viewFactory = instruction.viewFactory || this.viewFactory; container.viewModel = viewModel; if (viewFactory) { controller.view = viewFactory.create(container, instruction, element); } if (element !== null) { au.controller = controller; if (controller.view) { if (!this.usesShadowDOM && (element.childNodes.length === 1 || element.contentElement)) { let contentElement = element.childNodes[0] || element.contentElement; controller.view.contentView = { fragment: contentElement }; contentElement.parentNode && DOM.removeNode(contentElement); } if (instruction.anchorIsContainer) { if (childBindings !== null) { for (let i = 0, ii = childBindings.length; i < ii; ++i) { controller.view.addBinding(childBindings[i].create(element, viewModel, controller)); } } controller.view.appendNodesTo(viewHost); } else { controller.view.insertNodesBefore(viewHost); } } else if (childBindings !== null) { for (let i = 0, ii = childBindings.length; i < ii; ++i) { bindings.push(childBindings[i].create(element, viewModel, controller)); } } } else if (controller.view) { controller.view.controller = controller; if (childBindings !== null) { for (let i = 0, ii = childBindings.length; i < ii; ++i) { controller.view.addBinding(childBindings[i].create(instruction.host, viewModel, controller)); } } } else if (childBindings !== null) { for (let i = 0, ii = childBindings.length; i < ii; ++i) { bindings.push(childBindings[i].create(instruction.host, viewModel, controller)); } } } else if (childBindings !== null) { for (let i = 0, ii = childBindings.length; i < ii; ++i) { bindings.push(childBindings[i].create(element, viewModel, controller)); } } if (au !== null) { au[this.htmlName] = controller; } if (instruction.initiatedByBehavior && viewFactory) { controller.view.created(); } return controller; } _ensurePropertiesDefined(instance, lookup) { let properties; let i; let ii; let observer; if ('__propertiesDefined__' in lookup) { return; } lookup.__propertiesDefined__ = true; properties = this.properties; for (i = 0, ii = properties.length; i < ii; ++i) { observer = properties[i].createObserver(instance); if (observer !== undefined) { lookup[observer.propertyName] = observer; } } } _copyInheritedProperties(container, target) { let behavior; let derived = target; while (true) { let proto = Object.getPrototypeOf(target.prototype); target = proto && proto.constructor; if (!target) { return; } behavior = metadata.getOwn(metadata.resource, target); if (behavior) { break; } } behavior.initialize(container, target); for (let i = 0, ii = behavior.properties.length; i < ii; ++i) { let prop = behavior.properties[i]; if (this.properties.some(p => p.name === prop.name)) { continue; } new BindableProperty(prop).registerWith(derived, this); } } }; function createChildObserverDecorator(selectorOrConfig, all) { return function (target, key, descriptor) { let actualTarget = typeof key === 'string' ? target.constructor : target; let r = metadata.getOrCreateOwn(metadata.resource, HtmlBehaviorResource, actualTarget); if (typeof selectorOrConfig === 'string') { selectorOrConfig = { selector: selectorOrConfig, name: key }; } if (descriptor) { descriptor.writable = true; descriptor.configurable = true; } selectorOrConfig.all = all; r.addChildBinding(new ChildObserver(selectorOrConfig)); }; } function children(selectorOrConfig) { return createChildObserverDecorator(selectorOrConfig, true); } function child(selectorOrConfig) { return createChildObserverDecorator(selectorOrConfig, false); } let ChildObserver = class ChildObserver { constructor(config) { this.name = config.name; this.changeHandler = config.changeHandler || this.name + 'Changed'; this.selector = config.selector; this.all = config.all; } create(viewHost, viewModel, controller) { return new ChildObserverBinder(this.selector, viewHost, this.name, viewModel, controller, this.changeHandler, this.all); } }; const noMutations = []; function trackMutation(groupedMutations, binder, record) { let mutations = groupedMutations.get(binder); if (!mutations) { mutations = []; groupedMutations.set(binder, mutations); } mutations.push(record); } function onChildChange(mutations, observer) { let binders = observer.binders; let bindersLength = binders.length; let groupedMutations = new Map(); for (let i = 0, ii = mutations.length; i < ii; ++i) { let record = mutations[i]; let added = record.addedNodes; let removed = record.removedNodes; for (let j = 0, jj = removed.length; j < jj; ++j) { let node = removed[j]; if (node.nodeType === 1) { for (let k = 0; k < bindersLength; ++k) { let binder = binders[k]; if (binder.onRemove(node)) { trackMutation(groupedMutations, binder, record); } } } } for (let j = 0, jj = added.length; j < jj; ++j) { let node = added[j]; if (node.nodeType === 1) { for (let k = 0; k < bindersLength; ++k) { let binder = binders[k]; if (binder.onAdd(node)) { trackMutation(groupedMutations, binder, record); } } } } } groupedMutations.forEach((value, key) => { if (key.changeHandler !== null) { key.viewModel[key.changeHandler](value); } }); } let ChildObserverBinder = class ChildObserverBinder { constructor(selector, viewHost, property, viewModel, controller, changeHandler, all) { this.selector = selector; this.viewHost = viewHost; this.property = property; this.viewModel = viewModel; this.controller = controller; this.changeHandler = changeHandler in viewModel ? changeHandler : null; this.usesShadowDOM = controller.behavior.usesShadowDOM; this.all = all; if (!this.usesShadowDOM && controller.view && controller.view.contentView) { this.contentView = controller.view.contentView; } else { this.contentView = null; } } matches(element) { if (element.matches(this.selector)) { if (this.contentView === null) { return true; } let contentView = this.contentView; let assignedSlot = element.auAssignedSlot; if (assignedSlot && assignedSlot.projectFromAnchors) { let anchors = assignedSlot.projectFromAnchors; for (let i = 0, ii = anchors.length; i < ii; ++i) { if (anchors[i].auOwnerView === contentView) { return true; } } return false; } return element.auOwnerView === contentView; } return false; } bind(source) { let viewHost = this.viewHost; let viewModel = this.viewModel; let observer = viewHost.__childObserver__; if (!observer) { observer = viewHost.__childObserver__ = DOM.createMutationObserver(onChildChange); let options = { childList: true, subtree: !this.usesShadowDOM }; observer.observe(viewHost, options); observer.binders = []; } observer.binders.push(this); if (this.usesShadowDOM) { let current = viewHost.firstElementChild; if (this.all) { let items = viewModel[this.property]; if (!items) { items = viewModel[this.property] = []; } else { items.splice(0); } while (current) { if (this.matches(current)) { items.push(current.au && current.au.controller ? current.au.controller.viewModel : current); } current = current.nextElementSibling; } if (this.changeHandler !== null) { this.viewModel[this.changeHandler](noMutations); } } else { while (current) { if (this.matches(current)) { let value = current.au && current.au.controller ? current.au.controller.viewModel : current; this.viewModel[this.property] = value; if (this.changeHandler !== null) { this.viewModel[this.changeHandler](value); } break; } current = current.nextElementSibling; } } } } onRemove(element) { if (this.matches(element)) { let value = element.au && element.au.controller ? element.au.controller.viewModel : element; if (this.all) { let items = this.viewModel[this.property] || (this.viewModel[this.property] = []); let index = items.indexOf(value); if (index !== -1) { items.splice(index, 1); } return true; } return false; } return false; } onAdd(element) { if (this.matches(element)) { let value = element.au && element.au.controller ? element.au.controller.viewModel : element; if (this.all) { let items = this.viewModel[this.property] || (this.viewModel[this.property] = []); if (this.selector === '*') { items.push(value); return true; } let index = 0; let prev = element.previousElementSibling; while (prev) { if (this.matches(prev)) { index++; } prev = prev.previousElementSibling; } items.splice(index, 0, value); return true; } this.viewModel[this.property] = value; if (this.changeHandler !== null) { this.viewModel[this.changeHandler](value); } } return false; } unbind() { if (this.viewHost.__childObserver__) { this.viewHost.__childObserver__.disconnect(); this.viewHost.__childObserver__ = null; this.viewModel[this.property] = null; } } }; function remove(viewSlot, previous) { return Array.isArray(previous) ? viewSlot.removeMany(previous, true) : viewSlot.remove(previous, true); } const SwapStrategies = { before(viewSlot, previous, callback) { return previous === undefined ? callback() : callback().then(() => remove(viewSlot, previous)); }, with(viewSlot, previous, callback) { return previous === undefined ? callback() : Promise.all([remove(viewSlot, previous), callback()]); }, after(viewSlot, previous, callback) { return Promise.resolve(viewSlot.removeAll(true)).then(callback); } }; function tryActivateViewModel(context) { if (context.skipActivation || typeof context.viewModel.activate !== 'function') { return Promise.resolve(); } return context.viewModel.activate(context.model) || Promise.resolve(); } let CompositionEngine = (_dec10$1 = inject(ViewEngine, ViewLocator), _dec10$1(_class17 = class CompositionEngine { constructor(viewEngine, viewLocator) { this.viewEngine = viewEngine; this.viewLocator = viewLocator; } _swap(context, view) { let swapStrategy = SwapStrategies[context.swapOrder] || SwapStrategies.after; let previousViews = context.viewSlot.children.slice(); return swapStrategy(context.viewSlot, previousViews, () => { return Promise.resolve(context.viewSlot.add(view)).then(() => { if (context.currentController) { context.currentController.unbind(); } }); }).then(() => { if (context.compositionTransactionNotifier) { context.compositionTransactionNotifier.done(); } }); } _createControllerAndSwap(context) { return this.createController(context).then(controller => { if (context.compositionTransactionOwnershipToken) { return context.compositionTransactionOwnershipToken.waitForCompositionComplete().then(() => { controller.automate(context.overrideContext, context.owningView); return this._swap(context, controller.view); }).then(() => controller); } controller.automate(context.overrideContext, context.owningView); return this._swap(context, controller.view).then(() => controller); }); } createController(context) { let childContainer; let viewModel; let viewModelResource; let m; return this.ensureViewModel(context).then(tryActivateViewModel).then(() => { childContainer = context.childContainer; viewModel = context.viewModel; viewModelResource = context.viewModelResource; m = viewModelResource.metadata; let viewStrategy = this.viewLocator.getViewStrategy(context.view || viewModel); if (context.viewResources) { viewStrategy.makeRelativeTo(context.viewResources.viewUrl); } return m.load(childContainer, viewModelResource.value, null, viewStrategy, true); }).then(viewFactory => m.create(childContainer, BehaviorInstruction.dynamic(context.host, viewModel, viewFactory))); } ensureViewModel(context) { let childContainer = context.childContainer = context.childContainer || context.container.createChild(); if (typeof context.viewModel === 'string') { context.viewModel = context.viewResources ? context.viewResources.relativeToView(context.viewModel) : context.viewModel; return this.viewEngine.importViewModelResource(context.viewModel).then(viewModelResource => { childContainer.autoRegister(viewModelResource.value); if (context.host) { childContainer.registerInstance(DOM.Element, context.host); } context.viewModel = childContainer.viewModel = childContainer.get(viewModelResource.value); context.viewModelResource = viewModelResource; return context; }); } let ctor = context.viewModel.constructor; let isClass = typeof context.viewModel === 'function'; if (isClass) { ctor = context.viewModel; childContainer.autoRegister(ctor); } let m = metadata.getOrCreateOwn(metadata.resource, HtmlBehaviorResource, ctor); m.elementName = m.elementName || 'dynamic-element'; m.initialize(isClass ? childContainer : context.container || childContainer, ctor); context.viewModelResource = { metadata: m, value: ctor }; if (context.host) { childContainer.registerInstance(DOM.Element, context.host); } childContainer.viewModel = context.viewModel = isClass ? childContainer.get(ctor) : context.viewModel; return Promise.resolve(context); } compose(context) { context.childContainer = context.childContainer || context.container.createChild(); context.view = this.viewLocator.getViewStrategy(context.view); let transaction = context.childContainer.get(CompositionTransaction); let compositionTransactionOwnershipToken = transaction.tryCapture(); if (compositionTransactionOwnershipToken) { context.compositionTransactionOwnershipToken = compositionTransactionOwnershipToken; } else { context.compositionTransactionNotifier = transaction.enlist(); } if (context.viewModel) { return this._createControllerAndSwap(context); } else if (context.view) { if (context.viewResources) { context.view.makeRelativeTo(context.viewResources.viewUrl); } return context.view.loadViewFactory(this.viewEngine, new ViewCompileInstruction()).then(viewFactory => { let result = viewFactory.create(context.childContainer); result.bind(context.bindingContext, context.overrideContext); if (context.compositionTransactionOwnershipToken) { return context.compositionTransactionOwnershipToken.waitForCompositionComplete().then(() => this._swap(context, result)).then(() => result); } return this._swap(context, result).then(() => result); }); } else if (context.viewSlot) { context.viewSlot.removeAll(); if (context.compositionTransactionNotifier) { context.compositionTransactionNotifier.done(); } return Promise.resolve(null); } return Promise.resolve(null); } }) || _class17); let ElementConfigResource = class ElementConfigResource { initialize(container, target) {} register(registry, name) {} load(container, target) { let config = new target(); let eventManager = container.get(EventManager); eventManager.registerElementConfig(config); } }; function resource(instanceOrConfig) { return function (target) { let isConfig = typeof instanceOrConfig === 'string' || Object.getPrototypeOf(instanceOrConfig) === Object.prototype; if (isConfig) { target.$resource = instanceOrConfig; } else { metadata.define(metadata.resource, instanceOrConfig, target); } }; } function behavior(override) { return function (target) { if (override instanceof HtmlBehaviorResource) { metadata.define(metadata.resource, override, target); } else { let r = metadata.getOrCreateOwn(metadata.resource, HtmlBehaviorResource, target); Object.assign(r, override); } }; } function customElement(name) { return function (target) { let r = metadata.getOrCreateOwn(metadata.resource, HtmlBehaviorResource, target); r.elementName = validateBehaviorName(name, 'custom element'); }; } function customAttribute(name, defaultBindingMode, aliases) { return function (target) { let r = metadata.getOrCreateOwn(metadata.resource, HtmlBehaviorResource, target); r.attributeName = validateBehaviorName(name, 'custom attribute'); r.attributeDefaultBindingMode = defaultBindingMode; r.aliases = aliases; }; } function templateController(target) { let deco = function (t) { let r = metadata.getOrCreateOwn(metadata.resource, HtmlBehaviorResource, t); r.liftsContent = true; }; return target ? deco(target) : deco; } function bindable(nameOrConfigOrTarget, key, descriptor) { let deco = function (target, key2, descriptor2) { let actualTarget = key2 ? target.constructor : target; let r = metadata.getOrCreateOwn(metadata.resource, HtmlBehaviorResource, actualTarget); let prop; if (key2) { nameOrConfigOrTarget = nameOrConfigOrTarget || {}; nameOrConfigOrTarget.name = key2; } prop = new BindableProperty(nameOrConfigOrTarget); return prop.registerWith(actualTarget, r, descriptor2); }; if (!nameOrConfigOrTarget) { return deco; } if (key) { let target = nameOrConfigOrTarget; nameOrConfigOrTarget = null; return deco(target, key, descriptor); } return deco; } function dynamicOptions(target) { let deco = function (t) { let r = metadata.getOrCreateOwn(metadata.resource, HtmlBehaviorResource, t); r.hasDynamicOptions = true; }; return target ? deco(target) : deco; } const defaultShadowDOMOptions = { mode: 'open' }; function useShadowDOM(targetOrOptions) { let options = typeof targetOrOptions === 'function' || !targetOrOptions ? defaultShadowDOMOptions : targetOrOptions; let deco = function (t) { let r = metadata.getOrCreateOwn(metadata.resource, HtmlBehaviorResource, t); r.targetShadowDOM = true; r.shadowDOMOptions = options; }; return typeof targetOrOptions === 'function' ? deco(targetOrOptions) : deco; } function processAttributes(processor) { return function (t) { let r = metadata.getOrCreateOwn(metadata.resource, HtmlBehaviorResource, t); r.processAttributes = function (compiler, resources, node, attributes, elementInstruction) { try { processor(compiler, resources, node, attributes, elementInstruction); } catch (error) { getLogger('templating').error(error); } }; }; } function doNotProcessContent() { return false; } function processContent(processor) { return function (t) { let r = metadata.getOrCreateOwn(metadata.resource, HtmlBehaviorResource, t); r.processContent = processor ? function (compiler, resources, node, instruction) { try { return processor(compiler, resources, node, instruction); } catch (error) { getLogger('templating').error(error); return false; } } : doNotProcessContent; }; } function containerless(target) { let deco = function (t) { let r = metadata.getOrCreateOwn(metadata.resource, HtmlBehaviorResource, t); r.containerless = true; }; return target ? deco(target) : deco; } function useViewStrategy(strategy) { return function (target) { metadata.define(ViewLocator.viewStrategyMetadataKey, strategy, target); }; } function useView(path) { return useViewStrategy(new RelativeViewStrategy(path)); } function inlineView(markup, dependencies, dependencyBaseUrl) { return useViewStrategy(new InlineViewStrategy(markup, dependencies, dependencyBaseUrl)); } function noView(targetOrDependencies, dependencyBaseUrl) { let target; let dependencies; if (typeof targetOrDependencies === 'function') { target = targetOrDependencies; } else { dependencies = targetOrDependencies; target = undefined; } let deco = function (t) { metadata.define(ViewLocator.viewStrategyMetadataKey, new NoViewStrategy(dependencies, dependencyBaseUrl), t); }; return target ? deco(target) : deco; } function view(templateOrConfig) { return function (target) { target.$view = templateOrConfig; }; } function elementConfig(target) { let deco = function (t) { metadata.define(metadata.resource, new ElementConfigResource(), t); }; return target ? deco(target) : deco; } function viewResources(...resources) { return function (target) { metadata.define(ViewEngine.viewModelRequireMetadataKey, resources, target); }; } let TemplatingEngine = (_dec11 = inject(Container, ModuleAnalyzer, ViewCompiler, CompositionEngine), _dec11(_class18 = class TemplatingEngine { constructor(container, moduleAnalyzer, viewCompiler, compositionEngine) { this._container = container; this._moduleAnalyzer = moduleAnalyzer; this._viewCompiler = viewCompiler; this._compositionEngine = compositionEngine; container.registerInstance(Animator, Animator.instance = new Animator()); } configureAnimator(animator) { this._container.unregister(Animator); this._container.registerInstance(Animator, Animator.instance = animator); } compose(context) { return this._compositionEngine.compose(context); } enhance(instruction) { if (instruction instanceof DOM.Element) { instruction = { element: instruction }; } let compilerInstructions = { letExpressions: [] }; let resources = instruction.resources || this._container.get(ViewResources); this._viewCompiler._compileNode(instruction.element, resources, compilerInstructions, instruction.element.parentNode, 'root', true); let factory = new ViewFactory(instruction.element, compilerInstructions, resources); let container = instruction.container || this._container.createChild(); let view = factory.create(container, BehaviorInstruction.enhance()); view.bind(instruction.bindingContext || {}, instruction.overrideContext); view.firstChild = view.lastChild = view.fragment; view.fragment = DOM.createDocumentFragment(); view.attached(); return view; } }) || _class18); function preventActionlessFormSubmit() { DOM.addEventListener('submit', evt => { const target = evt.target; const action = target.action; if (target.tagName.toLowerCase() === 'form' && !action) { evt.preventDefault(); } }); } let Aurelia = class Aurelia { constructor(loader, container, resources) { this.loader = loader || new PLATFORM.Loader(); this.container = container || new Container().makeGlobal(); this.resources = resources || new ViewResources(); this.use = new FrameworkConfiguration(this); this.logger = getLogger('aurelia'); this.hostConfigured = false; this.host = null; this.use.instance(Aurelia, this); this.use.instance(Loader, this.loader); this.use.instance(ViewResources, this.resources); } start() { if (this._started) { return this._started; } this.logger.info('Aurelia Starting'); return this._started = this.use.apply().then(() => { preventActionlessFormSubmit(); if (!this.container.hasResolver(BindingLanguage)) { let message = 'You must configure Aurelia with a BindingLanguage implementation.'; this.logger.error(message); throw new Error(message); } this.logger.info('Aurelia Started'); let evt = DOM.createCustomEvent('aurelia-started', { bubbles: true, cancelable: true }); DOM.dispatchEvent(evt); return this; }); } enhance(bindingContext = {}, applicationHost = null) { this._configureHost(applicationHost || DOM.querySelectorAll('body')[0]); return new Promise(resolve => { let engine = this.container.get(TemplatingEngine); this.root = engine.enhance({ container: this.container, element: this.host, resources: this.resources, bindingContext: bindingContext }); this.root.attached(); this._onAureliaComposed(); resolve(this); }); } setRoot(root = null, applicationHost = null) { let instruction = {}; if (this.root && this.root.viewModel && this.root.viewModel.router) { this.root.viewModel.router.deactivate(); this.root.viewModel.router.reset(); } this._configureHost(applicationHost); let engine = this.container.get(TemplatingEngine); let transaction = this.container.get(CompositionTransaction); delete transaction.initialComposition; if (!root) { if (this.configModuleId) { root = relativeToFile('./app', this.configModuleId); } else { root = 'app'; } } instruction.viewModel = root; instruction.container = instruction.childContainer = this.container; instruction.viewSlot = this.hostSlot; instruction.host = this.host; return engine.compose(instruction).then(r => { this.root = r; instruction.viewSlot.attached(); this._onAureliaComposed(); return this; }); } _configureHost(applicationHost) { if (this.hostConfigured) { return; } applicationHost = applicationHost || this.host; if (!applicationHost || typeof applicationHost === 'string') { this.host = DOM.getElementById(applicationHost || 'applicationHost'); } else { this.host = applicationHost; } if (!this.host) { throw new Error('No applicationHost was specified.'); } this.hostConfigured = true; this.host.aurelia = this; this.hostSlot = new ViewSlot(this.host, true); this.hostSlot.transformChildNodesIntoView(); this.container.registerInstance(DOM.boundary, this.host); } _onAureliaComposed() { let evt = DOM.createCustomEvent('aurelia-composed', { bubbles: true, cancelable: true }); setTimeout(() => DOM.dispatchEvent(evt), 1); } }; const logger$2 = getLogger('aurelia'); const extPattern = /\.[^/.]+$/; function runTasks(config, tasks) { let current; let next = () => { current = tasks.shift(); if (current) { return Promise.resolve(current(config)).then(next); } return Promise.resolve(); }; return next(); } function loadPlugin(fwConfig, loader, info) { logger$2.debug(`Loading plugin ${info.moduleId}.`); if (typeof info.moduleId === 'string') { fwConfig.resourcesRelativeTo = info.resourcesRelativeTo; let id = info.moduleId; if (info.resourcesRelativeTo.length > 1) { return loader.normalize(info.moduleId, info.resourcesRelativeTo[1]).then(normalizedId => _loadPlugin(normalizedId)); } return _loadPlugin(id); } else if (typeof info.configure === 'function') { if (fwConfig.configuredPlugins.indexOf(info.configure) !== -1) { return Promise.resolve(); } fwConfig.configuredPlugins.push(info.configure); return Promise.resolve(info.configure.call(null, fwConfig, info.config || {})); } throw new Error(invalidConfigMsg(info.moduleId || info.configure, 'plugin')); function _loadPlugin(moduleId) { return loader.loadModule(moduleId).then(m => { if ('configure' in m) { if (fwConfig.configuredPlugins.indexOf(m.configure) !== -1) { return Promise.resolve(); } return Promise.resolve(m.configure(fwConfig, info.config || {})).then(() => { fwConfig.configuredPlugins.push(m.configure); fwConfig.resourcesRelativeTo = null; logger$2.debug(`Configured plugin ${info.moduleId}.`); }); } fwConfig.resourcesRelativeTo = null; logger$2.debug(`Loaded plugin ${info.moduleId}.`); }); } } function loadResources(aurelia, resourcesToLoad, appResources) { if (Object.keys(resourcesToLoad).length === 0) { return Promise.resolve(); } let viewEngine = aurelia.container.get(ViewEngine); return Promise.all(Object.keys(resourcesToLoad).map(n => _normalize(resourcesToLoad[n]))).then(loads => { let names = []; let importIds = []; loads.forEach(l => { names.push(undefined); importIds.push(l.importId); }); return viewEngine.importViewResources(importIds, names, appResources); }); function _normalize(load) { let moduleId = load.moduleId; let ext = getExt(moduleId); if (isOtherResource(moduleId)) { moduleId = removeExt(moduleId); } return aurelia.loader.normalize(moduleId, load.relativeTo).then(normalized => { return { name: load.moduleId, importId: isOtherResource(load.moduleId) ? addOriginalExt(normalized, ext) : normalized }; }); } function isOtherResource(name) { let ext = getExt(name); if (!ext) return false; if (ext === '') return false; if (ext === '.js' || ext === '.ts') return false; return true; } function removeExt(name) { return name.replace(extPattern, ''); } function addOriginalExt(normalized, ext) { return removeExt(normalized) + '.' + ext; } } function getExt(name) { let match = name.match(extPattern); if (match && match.length > 0) { return match[0].split('.')[1]; } } function loadBehaviors(config) { return Promise.all(config.behaviorsToLoad.map(m => m.load(config.container, m.target))).then(() => { config.behaviorsToLoad = null; }); } function assertProcessed(plugins) { if (plugins.processed) { throw new Error('This config instance has already been applied. To load more plugins or global resources, create a new FrameworkConfiguration instance.'); } } function invalidConfigMsg(cfg, type) { return `Invalid ${type} [${cfg}], ${type} must be specified as functions or relative module IDs.`; } let FrameworkConfiguration = class FrameworkConfiguration { constructor(aurelia) { this.aurelia = aurelia; this.container = aurelia.container; this.info = []; this.processed = false; this.preTasks = []; this.postTasks = []; this.behaviorsToLoad = []; this.configuredPlugins = []; this.resourcesToLoad = {}; this.preTask(() => aurelia.loader.normalize('aurelia-bootstrapper').then(name => this.bootstrapperName = name)); this.postTask(() => loadResources(aurelia, this.resourcesToLoad, aurelia.resources)); } instance(type, instance) { this.container.registerInstance(type, instance); return this; } singleton(type, implementation) { this.container.registerSingleton(type, implementation); return this; } transient(type, implementation) { this.container.registerTransient(type, implementation); return this; } preTask(task) { assertProcessed(this); this.preTasks.push(task); return this; } postTask(task) { assertProcessed(this); this.postTasks.push(task); return this; } feature(plugin, config = {}) { switch (typeof plugin) { case 'string': let hasIndex = /\/index$/i.test(plugin); let moduleId = hasIndex || getExt(plugin) ? plugin : plugin + '/index'; let root = hasIndex ? plugin.substr(0, plugin.length - 6) : plugin; this.info.push({ moduleId, resourcesRelativeTo: [root, ''], config }); break; case 'function': this.info.push({ configure: plugin, config: config || {} }); break; default: throw new Error(invalidConfigMsg(plugin, 'feature')); } return this; } globalResources(resources) { assertProcessed(this); let toAdd = Array.isArray(resources) ? resources : arguments; let resource; let resourcesRelativeTo = this.resourcesRelativeTo || ['', '']; for (let i = 0, ii = toAdd.length; i < ii; ++i) { resource = toAdd[i]; switch (typeof resource) { case 'string': let parent = resourcesRelativeTo[0]; let grandParent = resourcesRelativeTo[1]; let name = resource; if ((resource.startsWith('./') || resource.startsWith('../')) && parent !== '') { name = join(parent, resource); } this.resourcesToLoad[name] = { moduleId: name, relativeTo: grandParent }; break; case 'function': let meta = this.aurelia.resources.autoRegister(this.container, resource); if (meta instanceof HtmlBehaviorResource && meta.elementName !== null) { if (this.behaviorsToLoad.push(meta) === 1) { this.postTask(() => loadBehaviors(this)); } } break; default: throw new Error(invalidConfigMsg(resource, 'resource')); } } return this; } globalName(resourcePath, newName) { assertProcessed(this); this.resourcesToLoad[resourcePath] = { moduleId: newName, relativeTo: '' }; return this; } plugin(plugin, pluginConfig) { assertProcessed(this); let info; switch (typeof plugin) { case 'string': info = { moduleId: plugin, resourcesRelativeTo: [plugin, ''], config: pluginConfig || {} }; break; case 'function': info = { configure: plugin, config: pluginConfig || {} }; break; default: throw new Error(invalidConfigMsg(plugin, 'plugin')); } this.info.push(info); return this; } _addNormalizedPlugin(name, config) { let plugin = { moduleId: name, resourcesRelativeTo: [name, ''], config: config || {} }; this.info.push(plugin); this.preTask(() => { let relativeTo = [name, this.bootstrapperName]; plugin.moduleId = name; plugin.resourcesRelativeTo = relativeTo; return Promise.resolve(); }); return this; } defaultBindingLanguage() { return this._addNormalizedPlugin('aurelia-templating-binding'); } router() { return this._addNormalizedPlugin('aurelia-templating-router'); } history() { return this._addNormalizedPlugin('aurelia-history-browser'); } defaultResources() { return this._addNormalizedPlugin('aurelia-templating-resources'); } eventAggregator() { return this._addNormalizedPlugin('aurelia-event-aggregator'); } basicConfiguration() { return this.defaultBindingLanguage().defaultResources().eventAggregator(); } standardConfiguration() { return this.basicConfiguration().history().router(); } developmentLogging(level) { let logLevel$1 = level ? logLevel[level] : undefined; if (logLevel$1 === undefined) { logLevel$1 = logLevel.debug; } this.preTask(() => { return this.aurelia.loader.normalize('aurelia-logging-console', this.bootstrapperName).then(name => { return this.aurelia.loader.loadModule(name).then(m => { addAppender(new m.ConsoleAppender()); setLevel(logLevel$1); }); }); }); return this; } apply() { if (this.processed) { return Promise.resolve(); } return runTasks(this, this.preTasks).then(() => { let loader = this.aurelia.loader; let info = this.info; let current; let next = () => { current = info.shift(); if (current) { return loadPlugin(this, loader, current).then(next); } this.processed = true; this.configuredPlugins = null; return Promise.resolve(); }; return next().then(() => runTasks(this, this.postTasks)); }); } }; const LogManager = TheLogManager; var _class$3, _temp$2, _dec$3, _class2$3, _dec2$3, _class3$3, _class4$2, _temp2$2, _class5$3, _temp3$1; let AttributeMap = (_temp$2 = _class$3 = class AttributeMap { constructor(svg) { this.elements = Object.create(null); this.allElements = Object.create(null); this.svg = svg; this.registerUniversal('accesskey', 'accessKey'); this.registerUniversal('contenteditable', 'contentEditable'); this.registerUniversal('tabindex', 'tabIndex'); this.registerUniversal('textcontent', 'textContent'); this.registerUniversal('innerhtml', 'innerHTML'); this.registerUniversal('scrolltop', 'scrollTop'); this.registerUniversal('scrollleft', 'scrollLeft'); this.registerUniversal('readonly', 'readOnly'); this.register('label', 'for', 'htmlFor'); this.register('img', 'usemap', 'useMap'); this.register('input', 'maxlength', 'maxLength'); this.register('input', 'minlength', 'minLength'); this.register('input', 'formaction', 'formAction'); this.register('input', 'formenctype', 'formEncType'); this.register('input', 'formmethod', 'formMethod'); this.register('input', 'formnovalidate', 'formNoValidate'); this.register('input', 'formtarget', 'formTarget'); this.register('textarea', 'maxlength', 'maxLength'); this.register('td', 'rowspan', 'rowSpan'); this.register('td', 'colspan', 'colSpan'); this.register('th', 'rowspan', 'rowSpan'); this.register('th', 'colspan', 'colSpan'); } register(elementName, attributeName, propertyName) { elementName = elementName.toLowerCase(); attributeName = attributeName.toLowerCase(); const element = this.elements[elementName] = this.elements[elementName] || Object.create(null); element[attributeName] = propertyName; } registerUniversal(attributeName, propertyName) { attributeName = attributeName.toLowerCase(); this.allElements[attributeName] = propertyName; } map(elementName, attributeName) { if (this.svg.isStandardSvgAttribute(elementName, attributeName)) { return attributeName; } elementName = elementName.toLowerCase(); attributeName = attributeName.toLowerCase(); const element = this.elements[elementName]; if (element !== undefined && attributeName in element) { return element[attributeName]; } if (attributeName in this.allElements) { return this.allElements[attributeName]; } if (/(?:^data-)|(?:^aria-)|:/.test(attributeName)) { return attributeName; } return camelCase(attributeName); } }, _class$3.inject = [SVGAnalyzer], _temp$2); let InterpolationBindingExpression = class InterpolationBindingExpression { constructor(observerLocator, targetProperty, parts, mode, lookupFunctions, attribute) { this.observerLocator = observerLocator; this.targetProperty = targetProperty; this.parts = parts; this.mode = mode; this.lookupFunctions = lookupFunctions; this.attribute = this.attrToRemove = attribute; this.discrete = false; } createBinding(target) { if (this.parts.length === 3) { return new ChildInterpolationBinding(target, this.observerLocator, this.parts[1], this.mode, this.lookupFunctions, this.targetProperty, this.parts[0], this.parts[2]); } return new InterpolationBinding(this.observerLocator, this.parts, target, this.targetProperty, this.mode, this.lookupFunctions); } }; function validateTarget(target, propertyName) { if (propertyName === 'style') { getLogger('templating-binding').info('Internet Explorer does not support interpolation in "style" attributes. Use the style attribute\'s alias, "css" instead.'); } else if (target.parentElement && target.parentElement.nodeName === 'TEXTAREA' && propertyName === 'textContent') { throw new Error('Interpolation binding cannot be used in the content of a textarea element. Use <textarea value.bind="expression"></textarea> instead.'); } } let InterpolationBinding = class InterpolationBinding { constructor(observerLocator, parts, target, targetProperty, mode, lookupFunctions) { validateTarget(target, targetProperty); this.observerLocator = observerLocator; this.parts = parts; this.target = target; this.targetProperty = targetProperty; this.targetAccessor = observerLocator.getAccessor(target, targetProperty); this.mode = mode; this.lookupFunctions = lookupFunctions; } interpolate() { if (this.isBound) { let value = ''; let parts = this.parts; for (let i = 0, ii = parts.length; i < ii; i++) { value += i % 2 === 0 ? parts[i] : this[`childBinding${i}`].value; } this.targetAccessor.setValue(value, this.target, this.targetProperty); } } updateOneTimeBindings() { for (let i = 1, ii = this.parts.length; i < ii; i += 2) { let child = this[`childBinding${i}`]; if (child.mode === bindingMode.oneTime) { child.call(); } } } bind(source) { if (this.isBound) { if (this.source === source) { return; } this.unbind(); } this.source = source; let parts = this.parts; for (let i = 1, ii = parts.length; i < ii; i += 2) { let binding = new ChildInterpolationBinding(this, this.observerLocator, parts[i], this.mode, this.lookupFunctions); binding.bind(source); this[`childBinding${i}`] = binding; } this.isBound = true; this.interpolate(); } unbind() { if (!this.isBound) { return; } this.isBound = false; this.source = null; let parts = this.parts; for (let i = 1, ii = parts.length; i < ii; i += 2) { let name = `childBinding${i}`; this[name].unbind(); } } }; let ChildInterpolationBinding = (_dec$3 = connectable(), _dec$3(_class2$3 = class ChildInterpolationBinding { constructor(target, observerLocator, sourceExpression, mode, lookupFunctions, targetProperty, left, right) { if (target instanceof InterpolationBinding) { this.parent = target; } else { validateTarget(target, targetProperty); this.target = target; this.targetProperty = targetProperty; this.targetAccessor = observerLocator.getAccessor(target, targetProperty); } this.observerLocator = observerLocator; this.sourceExpression = sourceExpression; this.mode = mode; this.lookupFunctions = lookupFunctions; this.left = left; this.right = right; } updateTarget(value) { value = value === null || value === undefined ? '' : value.toString(); if (value !== this.value) { this.value = value; if (this.parent) { this.parent.interpolate(); } else { this.targetAccessor.setValue(this.left + value + this.right, this.target, this.targetProperty); } } } call() { if (!this.isBound) { return; } this.rawValue = this.sourceExpression.evaluate(this.source, this.lookupFunctions); this.updateTarget(this.rawValue); if (this.mode !== bindingMode.oneTime) { this._version++; this.sourceExpression.connect(this, this.source); if (this.rawValue instanceof Array) { this.observeArray(this.rawValue); } this.unobserve(false); } } bind(source) { if (this.isBound) { if (this.source === source) { return; } this.unbind(); } this.isBound = true; this.source = source; let sourceExpression = this.sourceExpression; if (sourceExpression.bind) { sourceExpression.bind(this, source, this.lookupFunctions); } this.rawValue = sourceExpression.evaluate(source, this.lookupFunctions); this.updateTarget(this.rawValue); if (this.mode === bindingMode.oneWay) { enqueueBindingConnect(this); } } unbind() { if (!this.isBound) { return; } this.isBound = false; let sourceExpression = this.sourceExpression; if (sourceExpression.unbind) { sourceExpression.unbind(this, this.source); } this.source = null; this.value = null; this.rawValue = null; this.unobserve(true); } connect(evaluate) { if (!this.isBound) { return; } if (evaluate) { this.rawValue = this.sourceExpression.evaluate(this.source, this.lookupFunctions); this.updateTarget(this.rawValue); } this.sourceExpression.connect(this, this.source); if (this.rawValue instanceof Array) { this.observeArray(this.rawValue); } } }) || _class2$3); let LetExpression = class LetExpression { constructor(observerLocator, targetProperty, sourceExpression, lookupFunctions, toBindingContext) { this.observerLocator = observerLocator; this.sourceExpression = sourceExpression; this.targetProperty = targetProperty; this.lookupFunctions = lookupFunctions; this.toBindingContext = toBindingContext; } createBinding() { return new LetBinding(this.observerLocator, this.sourceExpression, this.targetProperty, this.lookupFunctions, this.toBindingContext); } }; let LetBinding = (_dec2$3 = connectable(), _dec2$3(_class3$3 = class LetBinding { constructor(observerLocator, sourceExpression, targetProperty, lookupFunctions, toBindingContext) { this.observerLocator = observerLocator; this.sourceExpression = sourceExpression; this.targetProperty = targetProperty; this.lookupFunctions = lookupFunctions; this.source = null; this.target = null; this.toBindingContext = toBindingContext; } updateTarget() { const value = this.sourceExpression.evaluate(this.source, this.lookupFunctions); this.target[this.targetProperty] = value; } call(context) { if (!this.isBound) { return; } if (context === sourceContext) { this.updateTarget(); return; } throw new Error(`Unexpected call context ${context}`); } bind(source) { if (this.isBound) { if (this.source === source) { return; } this.unbind(); } this.isBound = true; this.source = source; this.target = this.toBindingContext ? source.bindingContext : source.overrideContext; if (this.sourceExpression.bind) { this.sourceExpression.bind(this, source, this.lookupFunctions); } enqueueBindingConnect(this); } unbind() { if (!this.isBound) { return; } this.isBound = false; if (this.sourceExpression.unbind) { this.sourceExpression.unbind(this, this.source); } this.source = null; this.target = null; this.unobserve(true); } connect() { if (!this.isBound) { return; } this.updateTarget(); this.sourceExpression.connect(this, this.source); } }) || _class3$3); let LetInterpolationBindingExpression = class LetInterpolationBindingExpression { constructor(observerLocator, targetProperty, parts, lookupFunctions, toBindingContext) { this.observerLocator = observerLocator; this.targetProperty = targetProperty; this.parts = parts; this.lookupFunctions = lookupFunctions; this.toBindingContext = toBindingContext; } createBinding() { return new LetInterpolationBinding(this.observerLocator, this.targetProperty, this.parts, this.lookupFunctions, this.toBindingContext); } }; let LetInterpolationBinding = class LetInterpolationBinding { constructor(observerLocator, targetProperty, parts, lookupFunctions, toBindingContext) { this.observerLocator = observerLocator; this.parts = parts; this.targetProperty = targetProperty; this.lookupFunctions = lookupFunctions; this.toBindingContext = toBindingContext; this.target = null; } bind(source) { if (this.isBound) { if (this.source === source) { return; } this.unbind(); } this.isBound = true; this.source = source; this.target = this.toBindingContext ? source.bindingContext : source.overrideContext; this.interpolationBinding = this.createInterpolationBinding(); this.interpolationBinding.bind(source); } unbind() { if (!this.isBound) { return; } this.isBound = false; this.source = null; this.target = null; this.interpolationBinding.unbind(); this.interpolationBinding = null; } createInterpolationBinding() { if (this.parts.length === 3) { return new ChildInterpolationBinding(this.target, this.observerLocator, this.parts[1], bindingMode.oneWay, this.lookupFunctions, this.targetProperty, this.parts[0], this.parts[2]); } return new InterpolationBinding(this.observerLocator, this.parts, this.target, this.targetProperty, bindingMode.oneWay, this.lookupFunctions); } }; let SyntaxInterpreter = (_temp2$2 = _class4$2 = class SyntaxInterpreter { constructor(parser, observerLocator, eventManager, attributeMap) { this.parser = parser; this.observerLocator = observerLocator; this.eventManager = eventManager; this.attributeMap = attributeMap; } interpret(resources, element, info, existingInstruction, context) { if (info.command in this) { return this[info.command](resources, element, info, existingInstruction, context); } return this.handleUnknownCommand(resources, element, info, existingInstruction, context); } handleUnknownCommand(resources, element, info, existingInstruction, context) { getLogger('templating-binding').warn('Unknown binding command.', info); return existingInstruction; } determineDefaultBindingMode(element, attrName, context) { let tagName = element.tagName.toLowerCase(); if (tagName === 'input' && (attrName === 'value' || attrName === 'files') && element.type !== 'checkbox' && element.type !== 'radio' || tagName === 'input' && attrName === 'checked' && (element.type === 'checkbox' || element.type === 'radio') || (tagName === 'textarea' || tagName === 'select') && attrName === 'value' || (attrName === 'textcontent' || attrName === 'innerhtml') && element.contentEditable === 'true' || attrName === 'scrolltop' || attrName === 'scrollleft') { return bindingMode.twoWay; } if (context && attrName in context.attributes && context.attributes[attrName] && context.attributes[attrName].defaultBindingMode >= bindingMode.oneTime) { return context.attributes[attrName].defaultBindingMode; } return bindingMode.oneWay; } bind(resources, element, info, existingInstruction, context) { let instruction = existingInstruction || BehaviorInstruction.attribute(info.attrName); instruction.attributes[info.attrName] = new BindingExpression(this.observerLocator, this.attributeMap.map(element.tagName, info.attrName), this.parser.parse(info.attrValue), info.defaultBindingMode === undefined || info.defaultBindingMode === null ? this.determineDefaultBindingMode(element, info.attrName, context) : info.defaultBindingMode, resources.lookupFunctions); return instruction; } trigger(resources, element, info) { return new ListenerExpression(this.eventManager, info.attrName, this.parser.parse(info.attrValue), delegationStrategy.none, true, resources.lookupFunctions); } capture(resources, element, info) { return new ListenerExpression(this.eventManager, info.attrName, this.parser.parse(info.attrValue), delegationStrategy.capturing, true, resources.lookupFunctions); } delegate(resources, element, info) { return new ListenerExpression(this.eventManager, info.attrName, this.parser.parse(info.attrValue), delegationStrategy.bubbling, true, resources.lookupFunctions); } call(resources, element, info, existingInstruction) { let instruction = existingInstruction || BehaviorInstruction.attribute(info.attrName); instruction.attributes[info.attrName] = new CallExpression(this.observerLocator, info.attrName, this.parser.parse(info.attrValue), resources.lookupFunctions); return instruction; } options(resources, element, info, existingInstruction, context) { let instruction = existingInstruction || BehaviorInstruction.attribute(info.attrName); let attrValue = info.attrValue; let language = this.language; let name = null; let target = ''; let current; let i; let ii; let inString = false; let inEscape = false; let foundName = false; for (i = 0, ii = attrValue.length; i < ii; ++i) { current = attrValue[i]; if (current === ';' && !inString) { if (!foundName) { name = this._getPrimaryPropertyName(resources, context); } info = language.inspectAttribute(resources, '?', name, target.trim()); language.createAttributeInstruction(resources, element, info, instruction, context); if (!instruction.attributes[info.attrName]) { instruction.attributes[info.attrName] = info.attrValue; } target = ''; name = null; } else if (current === ':' && name === null) { foundName = true; name = target.trim(); target = ''; } else if (current === '\\') { target += current; inEscape = true; continue; } else { target += current; if (name !== null && inEscape === false && current === '\'') { inString = !inString; } } inEscape = false; } if (!foundName) { name = this._getPrimaryPropertyName(resources, context); } if (name !== null) { info = language.inspectAttribute(resources, '?', name, target.trim()); language.createAttributeInstruction(resources, element, info, instruction, context); if (!instruction.attributes[info.attrName]) { instruction.attributes[info.attrName] = info.attrValue; } } return instruction; } _getPrimaryPropertyName(resources, context) { let type = resources.getAttribute(context.attributeName); if (type && type.primaryProperty) { return type.primaryProperty.attribute; } return null; } 'for'(resources, element, info, existingInstruction) { let parts; let keyValue; let instruction; let attrValue; let isDestructuring; attrValue = info.attrValue; isDestructuring = attrValue.match(/^ *[[].+[\]]/); parts = isDestructuring ? attrValue.split('of ') : attrValue.split(' of '); if (parts.length !== 2) { throw new Error('Incorrect syntax for "for". The form is: "$local of $items" or "[$key, $value] of $items".'); } instruction = existingInstruction || BehaviorInstruction.attribute(info.attrName); if (isDestructuring) { keyValue = parts[0].replace(/[[\]]/g, '').replace(/,/g, ' ').replace(/\s+/g, ' ').trim().split(' '); instruction.attributes.key = keyValue[0]; instruction.attributes.value = keyValue[1]; } else { instruction.attributes.local = parts[0]; } instruction.attributes.items = new BindingExpression(this.observerLocator, 'items', this.parser.parse(parts[1]), bindingMode.oneWay, resources.lookupFunctions); return instruction; } 'two-way'(resources, element, info, existingInstruction) { let instruction = existingInstruction || BehaviorInstruction.attribute(info.attrName); instruction.attributes[info.attrName] = new BindingExpression(this.observerLocator, this.attributeMap.map(element.tagName, info.attrName), this.parser.parse(info.attrValue), bindingMode.twoWay, resources.lookupFunctions); return instruction; } 'to-view'(resources, element, info, existingInstruction) { let instruction = existingInstruction || BehaviorInstruction.attribute(info.attrName); instruction.attributes[info.attrName] = new BindingExpression(this.observerLocator, this.attributeMap.map(element.tagName, info.attrName), this.parser.parse(info.attrValue), bindingMode.toView, resources.lookupFunctions); return instruction; } 'from-view'(resources, element, info, existingInstruction) { let instruction = existingInstruction || BehaviorInstruction.attribute(info.attrName); instruction.attributes[info.attrName] = new BindingExpression(this.observerLocator, this.attributeMap.map(element.tagName, info.attrName), this.parser.parse(info.attrValue), bindingMode.fromView, resources.lookupFunctions); return instruction; } 'one-time'(resources, element, info, existingInstruction) { let instruction = existingInstruction || BehaviorInstruction.attribute(info.attrName); instruction.attributes[info.attrName] = new BindingExpression(this.observerLocator, this.attributeMap.map(element.tagName, info.attrName), this.parser.parse(info.attrValue), bindingMode.oneTime, resources.lookupFunctions); return instruction; } }, _class4$2.inject = [Parser, ObserverLocator, EventManager, AttributeMap], _temp2$2); SyntaxInterpreter.prototype['one-way'] = SyntaxInterpreter.prototype['to-view']; let info = {}; let TemplatingBindingLanguage = (_temp3$1 = _class5$3 = class TemplatingBindingLanguage extends BindingLanguage { constructor(parser, observerLocator, syntaxInterpreter, attributeMap) { super(); this.parser = parser; this.observerLocator = observerLocator; this.syntaxInterpreter = syntaxInterpreter; this.emptyStringExpression = this.parser.parse('\'\''); syntaxInterpreter.language = this; this.attributeMap = attributeMap; this.toBindingContextAttr = 'to-binding-context'; } inspectAttribute(resources, elementName, attrName, attrValue) { let parts = attrName.split('.'); info.defaultBindingMode = null; if (parts.length === 2) { info.attrName = parts[0].trim(); info.attrValue = attrValue; info.command = parts[1].trim(); if (info.command === 'ref') { info.expression = new NameExpression(this.parser.parse(attrValue), info.attrName, resources.lookupFunctions); info.command = null; info.attrName = 'ref'; } else { info.expression = null; } } else if (attrName === 'ref') { info.attrName = attrName; info.attrValue = attrValue; info.command = null; info.expression = new NameExpression(this.parser.parse(attrValue), 'element', resources.lookupFunctions); } else { info.attrName = attrName; info.attrValue = attrValue; info.command = null; const interpolationParts = this.parseInterpolation(resources, attrValue); if (interpolationParts === null) { info.expression = null; } else { info.expression = new InterpolationBindingExpression(this.observerLocator, this.attributeMap.map(elementName, attrName), interpolationParts, bindingMode.oneWay, resources.lookupFunctions, attrName); } } return info; } createAttributeInstruction(resources, element, theInfo, existingInstruction, context) { let instruction; if (theInfo.expression) { if (theInfo.attrName === 'ref') { return theInfo.expression; } instruction = existingInstruction || BehaviorInstruction.attribute(theInfo.attrName); instruction.attributes[theInfo.attrName] = theInfo.expression; } else if (theInfo.command) { instruction = this.syntaxInterpreter.interpret(resources, element, theInfo, existingInstruction, context); } return instruction; } createLetExpressions(resources, letElement) { let expressions = []; let attributes = letElement.attributes; let attr; let parts; let attrName; let attrValue; let command; let toBindingContextAttr = this.toBindingContextAttr; let toBindingContext = letElement.hasAttribute(toBindingContextAttr); for (let i = 0, ii = attributes.length; ii > i; ++i) { attr = attributes[i]; attrName = attr.name; attrValue = attr.nodeValue; parts = attrName.split('.'); if (attrName === toBindingContextAttr) { continue; } if (parts.length === 2) { command = parts[1]; if (command !== 'bind') { getLogger('templating-binding-language').warn(`Detected invalid let command. Expected "${parts[0]}.bind", given "${attrName}"`); continue; } expressions.push(new LetExpression(this.observerLocator, camelCase(parts[0]), this.parser.parse(attrValue), resources.lookupFunctions, toBindingContext)); } else { attrName = camelCase(attrName); parts = this.parseInterpolation(resources, attrValue); if (parts === null) { getLogger('templating-binding-language').warn(`Detected string literal in let bindings. Did you mean "${attrName}.bind=${attrValue}" or "${attrName}=\${${attrValue}}" ?`); } if (parts) { expressions.push(new LetInterpolationBindingExpression(this.observerLocator, attrName, parts, resources.lookupFunctions, toBindingContext)); } else { expressions.push(new LetExpression(this.observerLocator, attrName, new LiteralString(attrValue), resources.lookupFunctions, toBindingContext)); } } } return expressions; } inspectTextContent(resources, value) { const parts = this.parseInterpolation(resources, value); if (parts === null) { return null; } return new InterpolationBindingExpression(this.observerLocator, 'textContent', parts, bindingMode.oneWay, resources.lookupFunctions, 'textContent'); } parseInterpolation(resources, value) { let i = value.indexOf('${', 0); let ii = value.length; let char; let pos = 0; let open = 0; let quote = null; let interpolationStart; let parts; let partIndex = 0; while (i >= 0 && i < ii - 2) { open = 1; interpolationStart = i; i += 2; do { char = value[i]; i++; if (char === "'" || char === '"') { if (quote === null) { quote = char; } else if (quote === char) { quote = null; } continue; } if (char === '\\') { i++; continue; } if (quote !== null) { continue; } if (char === '{') { open++; } else if (char === '}') { open--; } } while (open > 0 && i < ii); if (open === 0) { parts = parts || []; if (value[interpolationStart - 1] === '\\' && value[interpolationStart - 2] !== '\\') { parts[partIndex] = value.substring(pos, interpolationStart - 1) + value.substring(interpolationStart, i); partIndex++; parts[partIndex] = this.emptyStringExpression; partIndex++; } else { parts[partIndex] = value.substring(pos, interpolationStart); partIndex++; parts[partIndex] = this.parser.parse(value.substring(interpolationStart + 2, i - 1)); partIndex++; } pos = i; i = value.indexOf('${', i); } else { break; } } if (partIndex === 0) { return null; } parts[partIndex] = value.substr(pos); return parts; } }, _class5$3.inject = [Parser, ObserverLocator, SyntaxInterpreter, AttributeMap], _temp3$1); function configure(config) { config.container.registerSingleton(BindingLanguage, TemplatingBindingLanguage); config.container.registerAlias(BindingLanguage, TemplatingBindingLanguage); } var _dec$4, _class$4, _class2$4, _descriptor, _descriptor2, _descriptor3, _descriptor4; function _initDefineProp(target, property, descriptor, context) { if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 }); } function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { var desc = {}; Object['ke' + 'ys'](descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object['define' + 'Property'](target, property, desc); desc = null; } return desc; } let Compose = (_dec$4 = customElement('compose'), _dec$4(_class$4 = noView(_class$4 = (_class2$4 = class Compose { static inject() { return [DOM.Element, Container, CompositionEngine, ViewSlot, ViewResources, TaskQueue]; } constructor(element, container, compositionEngine, viewSlot, viewResources, taskQueue) { _initDefineProp(this, 'model', _descriptor, this); _initDefineProp(this, 'view', _descriptor2, this); _initDefineProp(this, 'viewModel', _descriptor3, this); _initDefineProp(this, 'swapOrder', _descriptor4, this); this.element = element; this.container = container; this.compositionEngine = compositionEngine; this.viewSlot = viewSlot; this.viewResources = viewResources; this.taskQueue = taskQueue; this.currentController = null; this.currentViewModel = null; this.changes = Object.create(null); } created(owningView) { this.owningView = owningView; } bind(bindingContext, overrideContext) { this.bindingContext = bindingContext; this.overrideContext = overrideContext; this.changes.view = this.view; this.changes.viewModel = this.viewModel; this.changes.model = this.model; if (!this.pendingTask) { processChanges(this); } } unbind() { this.changes = Object.create(null); this.bindingContext = null; this.overrideContext = null; let returnToCache = true; let skipAnimation = true; this.viewSlot.removeAll(returnToCache, skipAnimation); } modelChanged(newValue, oldValue) { this.changes.model = newValue; requestUpdate(this); } viewChanged(newValue, oldValue) { this.changes.view = newValue; requestUpdate(this); } viewModelChanged(newValue, oldValue) { this.changes.viewModel = newValue; requestUpdate(this); } }, (_descriptor = _applyDecoratedDescriptor(_class2$4.prototype, 'model', [bindable], { enumerable: true, initializer: null }), _descriptor2 = _applyDecoratedDescriptor(_class2$4.prototype, 'view', [bindable], { enumerable: true, initializer: null }), _descriptor3 = _applyDecoratedDescriptor(_class2$4.prototype, 'viewModel', [bindable], { enumerable: true, initializer: null }), _descriptor4 = _applyDecoratedDescriptor(_class2$4.prototype, 'swapOrder', [bindable], { enumerable: true, initializer: null })), _class2$4)) || _class$4) || _class$4); function isEmpty(obj) { for (const key in obj) { return false; } return true; } function tryActivateViewModel$1(vm, model) { if (vm && typeof vm.activate === 'function') { return Promise.resolve(vm.activate(model)); } } function createInstruction(composer, instruction) { return Object.assign(instruction, { bindingContext: composer.bindingContext, overrideContext: composer.overrideContext, owningView: composer.owningView, container: composer.container, viewSlot: composer.viewSlot, viewResources: composer.viewResources, currentController: composer.currentController, host: composer.element, swapOrder: composer.swapOrder }); } function processChanges(composer) { const changes = composer.changes; composer.changes = Object.create(null); if (!('view' in changes) && !('viewModel' in changes) && 'model' in changes) { composer.pendingTask = tryActivateViewModel$1(composer.currentViewModel, changes.model); if (!composer.pendingTask) { return; } } else { let instruction = { view: composer.view, viewModel: composer.currentViewModel || composer.viewModel, model: composer.model }; instruction = Object.assign(instruction, changes); instruction = createInstruction(composer, instruction); composer.pendingTask = composer.compositionEngine.compose(instruction).then(controller => { composer.currentController = controller; composer.currentViewModel = controller ? controller.viewModel : null; }); } composer.pendingTask = composer.pendingTask.then(() => { completeCompositionTask(composer); }, reason => { completeCompositionTask(composer); throw reason; }); } function completeCompositionTask(composer) { composer.pendingTask = null; if (!isEmpty(composer.changes)) { processChanges(composer); } } function requestUpdate(composer) { if (composer.pendingTask || composer.updateRequested) { return; } composer.updateRequested = true; composer.taskQueue.queueMicroTask(() => { composer.updateRequested = false; processChanges(composer); }); } let IfCore = class IfCore { constructor(viewFactory, viewSlot) { this.viewFactory = viewFactory; this.viewSlot = viewSlot; this.view = null; this.bindingContext = null; this.overrideContext = null; this.showing = false; } bind(bindingContext, overrideContext) { this.bindingContext = bindingContext; this.overrideContext = overrideContext; } unbind() { if (this.view === null) { return; } this.view.unbind(); if (!this.viewFactory.isCaching) { return; } if (this.showing) { this.showing = false; this.viewSlot.remove(this.view, true, true); } else { this.view.returnToCache(); } this.view = null; } _show() { if (this.showing) { if (!this.view.isBound) { this.view.bind(this.bindingContext, this.overrideContext); } return; } if (this.view === null) { this.view = this.viewFactory.create(); } if (!this.view.isBound) { this.view.bind(this.bindingContext, this.overrideContext); } this.showing = true; return this.viewSlot.add(this.view); } _hide() { if (!this.showing) { return; } this.showing = false; let removed = this.viewSlot.remove(this.view); if (removed instanceof Promise) { return removed.then(() => this.view.unbind()); } this.view.unbind(); } }; var _dec$5, _dec2$4, _dec3$3, _class$5, _class2$5, _descriptor$1, _descriptor2$1; function _initDefineProp$1(target, property, descriptor, context) { if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 }); } function _applyDecoratedDescriptor$1(target, property, decorators, descriptor, context) { var desc = {}; Object['ke' + 'ys'](descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object['define' + 'Property'](target, property, desc); desc = null; } return desc; } let If = (_dec$5 = customAttribute('if'), _dec2$4 = inject(BoundViewFactory, ViewSlot), _dec3$3 = bindable({ primaryProperty: true }), _dec$5(_class$5 = templateController(_class$5 = _dec2$4(_class$5 = (_class2$5 = class If extends IfCore { constructor(...args) { var _temp; return _temp = super(...args), _initDefineProp$1(this, 'condition', _descriptor$1, this), _initDefineProp$1(this, 'swapOrder', _descriptor2$1, this), _temp; } bind(bindingContext, overrideContext) { super.bind(bindingContext, overrideContext); if (this.condition) { this._show(); } else { this._hide(); } } conditionChanged(newValue) { this._update(newValue); } _update(show) { if (this.animating) { return; } let promise; if (this.elseVm) { promise = show ? this._swap(this.elseVm, this) : this._swap(this, this.elseVm); } else { promise = show ? this._show() : this._hide(); } if (promise) { this.animating = true; promise.then(() => { this.animating = false; if (this.condition !== this.showing) { this._update(this.condition); } }); } } _swap(remove, add) { switch (this.swapOrder) { case 'before': return Promise.resolve(add._show()).then(() => remove._hide()); case 'with': return Promise.all([remove._hide(), add._show()]); default: let promise = remove._hide(); return promise ? promise.then(() => add._show()) : add._show(); } } }, (_descriptor$1 = _applyDecoratedDescriptor$1(_class2$5.prototype, 'condition', [_dec3$3], { enumerable: true, initializer: null }), _descriptor2$1 = _applyDecoratedDescriptor$1(_class2$5.prototype, 'swapOrder', [bindable], { enumerable: true, initializer: null })), _class2$5)) || _class$5) || _class$5) || _class$5); var _dec$6, _dec2$5, _class$6; let Else = (_dec$6 = customAttribute('else'), _dec2$5 = inject(BoundViewFactory, ViewSlot), _dec$6(_class$6 = templateController(_class$6 = _dec2$5(_class$6 = class Else extends IfCore { constructor(viewFactory, viewSlot) { super(viewFactory, viewSlot); this._registerInIf(); } bind(bindingContext, overrideContext) { super.bind(bindingContext, overrideContext); if (this.ifVm.condition) { this._hide(); } else { this._show(); } } _registerInIf() { let previous = this.viewSlot.anchor.previousSibling; while (previous && !previous.au) { previous = previous.previousSibling; } if (!previous || !previous.au.if) { throw new Error("Can't find matching If for Else custom attribute."); } this.ifVm = previous.au.if.viewModel; this.ifVm.elseVm = this; } }) || _class$6) || _class$6) || _class$6); var _dec$7, _dec2$6, _class$7; let With = (_dec$7 = customAttribute('with'), _dec2$6 = inject(BoundViewFactory, ViewSlot), _dec$7(_class$7 = templateController(_class$7 = _dec2$6(_class$7 = class With { constructor(viewFactory, viewSlot) { this.viewFactory = viewFactory; this.viewSlot = viewSlot; this.parentOverrideContext = null; this.view = null; } bind(bindingContext, overrideContext) { this.parentOverrideContext = overrideContext; this.valueChanged(this.value); } valueChanged(newValue) { let overrideContext = createOverrideContext(newValue, this.parentOverrideContext); if (!this.view) { this.view = this.viewFactory.create(); this.view.bind(newValue, overrideContext); this.viewSlot.add(this.view); } else { this.view.bind(newValue, overrideContext); } } unbind() { this.parentOverrideContext = null; if (this.view) { this.view.unbind(); } } }) || _class$7) || _class$7) || _class$7); let NullRepeatStrategy = class NullRepeatStrategy { instanceChanged(repeat, items) { repeat.removeAllViews(true); } getCollectionObserver(observerLocator, items) {} }; const oneTime = bindingMode.oneTime; function updateOverrideContexts(views, startIndex) { let length = views.length; if (startIndex > 0) { startIndex = startIndex - 1; } for (; startIndex < length; ++startIndex) { updateOverrideContext(views[startIndex].overrideContext, startIndex, length); } } function createFullOverrideContext(repeat, data, index, length, key) { let bindingContext = {}; let overrideContext = createOverrideContext(bindingContext, repeat.scope.overrideContext); if (typeof key !== 'undefined') { bindingContext[repeat.key] = key; bindingContext[repeat.value] = data; } else { bindingContext[repeat.local] = data; } updateOverrideContext(overrideContext, index, length); return overrideContext; } function updateOverrideContext(overrideContext, index, length) { let first = index === 0; let last = index === length - 1; let even = index % 2 === 0; overrideContext.$index = index; overrideContext.$first = first; overrideContext.$last = last; overrideContext.$middle = !(first || last); overrideContext.$odd = !even; overrideContext.$even = even; } function getItemsSourceExpression(instruction, attrName) { return instruction.behaviorInstructions.filter(bi => bi.originalAttrName === attrName)[0].attributes.items.sourceExpression; } function unwrapExpression(expression) { let unwrapped = false; while (expression instanceof BindingBehavior) { expression = expression.expression; } while (expression instanceof ValueConverter) { expression = expression.expression; unwrapped = true; } return unwrapped ? expression : null; } function isOneTime(expression) { while (expression instanceof BindingBehavior) { if (expression.name === 'oneTime') { return true; } expression = expression.expression; } return false; } function updateOneTimeBinding(binding) { if (binding.call && binding.mode === oneTime) { binding.call(sourceContext); } else if (binding.updateOneTimeBindings) { binding.updateOneTimeBindings(); } } function indexOf(array, item, matcher, startIndex) { if (!matcher) { return array.indexOf(item); } const length = array.length; for (let index = startIndex || 0; index < length; index++) { if (matcher(array[index], item)) { return index; } } return -1; } let ArrayRepeatStrategy = class ArrayRepeatStrategy { getCollectionObserver(observerLocator, items) { return observerLocator.getArrayObserver(items); } instanceChanged(repeat, items) { const itemsLength = items.length; if (!items || itemsLength === 0) { repeat.removeAllViews(true, !repeat.viewsRequireLifecycle); return; } const children = repeat.views(); const viewsLength = children.length; if (viewsLength === 0) { this._standardProcessInstanceChanged(repeat, items); return; } if (repeat.viewsRequireLifecycle) { const childrenSnapshot = children.slice(0); const itemNameInBindingContext = repeat.local; const matcher = repeat.matcher(); let itemsPreviouslyInViews = []; const viewsToRemove = []; for (let index = 0; index < viewsLength; index++) { const view = childrenSnapshot[index]; const oldItem = view.bindingContext[itemNameInBindingContext]; if (indexOf(items, oldItem, matcher) === -1) { viewsToRemove.push(view); } else { itemsPreviouslyInViews.push(oldItem); } } let updateViews; let removePromise; if (itemsPreviouslyInViews.length > 0) { removePromise = repeat.removeViews(viewsToRemove, true, !repeat.viewsRequireLifecycle); updateViews = () => { for (let index = 0; index < itemsLength; index++) { const item = items[index]; const indexOfView = indexOf(itemsPreviouslyInViews, item, matcher, index); let view; if (indexOfView === -1) { const overrideContext = createFullOverrideContext(repeat, items[index], index, itemsLength); repeat.insertView(index, overrideContext.bindingContext, overrideContext); itemsPreviouslyInViews.splice(index, 0, undefined); } else if (indexOfView === index) { view = children[indexOfView]; itemsPreviouslyInViews[indexOfView] = undefined; } else { view = children[indexOfView]; repeat.moveView(indexOfView, index); itemsPreviouslyInViews.splice(indexOfView, 1); itemsPreviouslyInViews.splice(index, 0, undefined); } if (view) { updateOverrideContext(view.overrideContext, index, itemsLength); } } this._inPlaceProcessItems(repeat, items); }; } else { removePromise = repeat.removeAllViews(true, !repeat.viewsRequireLifecycle); updateViews = () => this._standardProcessInstanceChanged(repeat, items); } if (removePromise instanceof Promise) { removePromise.then(updateViews); } else { updateViews(); } } else { this._inPlaceProcessItems(repeat, items); } } _standardProcessInstanceChanged(repeat, items) { for (let i = 0, ii = items.length; i < ii; i++) { let overrideContext = createFullOverrideContext(repeat, items[i], i, ii); repeat.addView(overrideContext.bindingContext, overrideContext); } } _inPlaceProcessItems(repeat, items) { let itemsLength = items.length; let viewsLength = repeat.viewCount(); while (viewsLength > itemsLength) { viewsLength--; repeat.removeView(viewsLength, true, !repeat.viewsRequireLifecycle); } let local = repeat.local; for (let i = 0; i < viewsLength; i++) { let view = repeat.view(i); let last = i === itemsLength - 1; let middle = i !== 0 && !last; if (view.bindingContext[local] === items[i] && view.overrideContext.$middle === middle && view.overrideContext.$last === last) { continue; } view.bindingContext[local] = items[i]; view.overrideContext.$middle = middle; view.overrideContext.$last = last; repeat.updateBindings(view); } for (let i = viewsLength; i < itemsLength; i++) { let overrideContext = createFullOverrideContext(repeat, items[i], i, itemsLength); repeat.addView(overrideContext.bindingContext, overrideContext); } } instanceMutated(repeat, array, splices) { if (repeat.__queuedSplices) { for (let i = 0, ii = splices.length; i < ii; ++i) { let { index, removed, addedCount } = splices[i]; mergeSplice(repeat.__queuedSplices, index, removed, addedCount); } repeat.__array = array.slice(0); return; } let maybePromise = this._runSplices(repeat, array.slice(0), splices); if (maybePromise instanceof Promise) { let queuedSplices = repeat.__queuedSplices = []; let runQueuedSplices = () => { if (!queuedSplices.length) { repeat.__queuedSplices = undefined; repeat.__array = undefined; return; } let nextPromise = this._runSplices(repeat, repeat.__array, queuedSplices) || Promise.resolve(); queuedSplices = repeat.__queuedSplices = []; nextPromise.then(runQueuedSplices); }; maybePromise.then(runQueuedSplices); } } _runSplices(repeat, array, splices) { let removeDelta = 0; let rmPromises = []; for (let i = 0, ii = splices.length; i < ii; ++i) { let splice = splices[i]; let removed = splice.removed; for (let j = 0, jj = removed.length; j < jj; ++j) { let viewOrPromise = repeat.removeView(splice.index + removeDelta + rmPromises.length, true); if (viewOrPromise instanceof Promise) { rmPromises.push(viewOrPromise); } } removeDelta -= splice.addedCount; } if (rmPromises.length > 0) { return Promise.all(rmPromises).then(() => { let spliceIndexLow = this._handleAddedSplices(repeat, array, splices); updateOverrideContexts(repeat.views(), spliceIndexLow); }); } let spliceIndexLow = this._handleAddedSplices(repeat, array, splices); updateOverrideContexts(repeat.views(), spliceIndexLow); return undefined; } _handleAddedSplices(repeat, array, splices) { let spliceIndex; let spliceIndexLow; let arrayLength = array.length; for (let i = 0, ii = splices.length; i < ii; ++i) { let splice = splices[i]; let addIndex = spliceIndex = splice.index; let end = splice.index + splice.addedCount; if (typeof spliceIndexLow === 'undefined' || spliceIndexLow === null || spliceIndexLow > splice.index) { spliceIndexLow = spliceIndex; } for (; addIndex < end; ++addIndex) { let overrideContext = createFullOverrideContext(repeat, array[addIndex], addIndex, arrayLength); repeat.insertView(addIndex, overrideContext.bindingContext, overrideContext); } } return spliceIndexLow; } }; let MapRepeatStrategy = class MapRepeatStrategy { getCollectionObserver(observerLocator, items) { return observerLocator.getMapObserver(items); } instanceChanged(repeat, items) { let removePromise = repeat.removeAllViews(true, !repeat.viewsRequireLifecycle); if (removePromise instanceof Promise) { removePromise.then(() => this._standardProcessItems(repeat, items)); return; } this._standardProcessItems(repeat, items); } _standardProcessItems(repeat, items) { let index = 0; let overrideContext; items.forEach((value, key) => { overrideContext = createFullOverrideContext(repeat, value, index, items.size, key); repeat.addView(overrideContext.bindingContext, overrideContext); ++index; }); } instanceMutated(repeat, map, records) { let key; let i; let ii; let overrideContext; let removeIndex; let addIndex; let record; let rmPromises = []; let viewOrPromise; for (i = 0, ii = records.length; i < ii; ++i) { record = records[i]; key = record.key; switch (record.type) { case 'update': removeIndex = this._getViewIndexByKey(repeat, key); viewOrPromise = repeat.removeView(removeIndex, true, !repeat.viewsRequireLifecycle); if (viewOrPromise instanceof Promise) { rmPromises.push(viewOrPromise); } overrideContext = createFullOverrideContext(repeat, map.get(key), removeIndex, map.size, key); repeat.insertView(removeIndex, overrideContext.bindingContext, overrideContext); break; case 'add': addIndex = repeat.viewCount() <= map.size - 1 ? repeat.viewCount() : map.size - 1; overrideContext = createFullOverrideContext(repeat, map.get(key), addIndex, map.size, key); repeat.insertView(map.size - 1, overrideContext.bindingContext, overrideContext); break; case 'delete': if (record.oldValue === undefined) { return; } removeIndex = this._getViewIndexByKey(repeat, key); viewOrPromise = repeat.removeView(removeIndex, true, !repeat.viewsRequireLifecycle); if (viewOrPromise instanceof Promise) { rmPromises.push(viewOrPromise); } break; case 'clear': repeat.removeAllViews(true, !repeat.viewsRequireLifecycle); break; default: continue; } } if (rmPromises.length > 0) { Promise.all(rmPromises).then(() => { updateOverrideContexts(repeat.views(), 0); }); } else { updateOverrideContexts(repeat.views(), 0); } } _getViewIndexByKey(repeat, key) { let i; let ii; let child; for (i = 0, ii = repeat.viewCount(); i < ii; ++i) { child = repeat.view(i); if (child.bindingContext[repeat.key] === key) { return i; } } return undefined; } }; let SetRepeatStrategy = class SetRepeatStrategy { getCollectionObserver(observerLocator, items) { return observerLocator.getSetObserver(items); } instanceChanged(repeat, items) { let removePromise = repeat.removeAllViews(true, !repeat.viewsRequireLifecycle); if (removePromise instanceof Promise) { removePromise.then(() => this._standardProcessItems(repeat, items)); return; } this._standardProcessItems(repeat, items); } _standardProcessItems(repeat, items) { let index = 0; let overrideContext; items.forEach(value => { overrideContext = createFullOverrideContext(repeat, value, index, items.size); repeat.addView(overrideContext.bindingContext, overrideContext); ++index; }); } instanceMutated(repeat, set, records) { let value; let i; let ii; let overrideContext; let removeIndex; let record; let rmPromises = []; let viewOrPromise; for (i = 0, ii = records.length; i < ii; ++i) { record = records[i]; value = record.value; switch (record.type) { case 'add': let size = Math.max(set.size - 1, 0); overrideContext = createFullOverrideContext(repeat, value, size, set.size); repeat.insertView(size, overrideContext.bindingContext, overrideContext); break; case 'delete': removeIndex = this._getViewIndexByValue(repeat, value); viewOrPromise = repeat.removeView(removeIndex, true, !repeat.viewsRequireLifecycle); if (viewOrPromise instanceof Promise) { rmPromises.push(viewOrPromise); } break; case 'clear': repeat.removeAllViews(true, !repeat.viewsRequireLifecycle); break; default: continue; } } if (rmPromises.length > 0) { Promise.all(rmPromises).then(() => { updateOverrideContexts(repeat.views(), 0); }); } else { updateOverrideContexts(repeat.views(), 0); } } _getViewIndexByValue(repeat, value) { let i; let ii; let child; for (i = 0, ii = repeat.viewCount(); i < ii; ++i) { child = repeat.view(i); if (child.bindingContext[repeat.local] === value) { return i; } } return undefined; } }; let NumberRepeatStrategy = class NumberRepeatStrategy { getCollectionObserver() { return null; } instanceChanged(repeat, value) { let removePromise = repeat.removeAllViews(true, !repeat.viewsRequireLifecycle); if (removePromise instanceof Promise) { removePromise.then(() => this._standardProcessItems(repeat, value)); return; } this._standardProcessItems(repeat, value); } _standardProcessItems(repeat, value) { let childrenLength = repeat.viewCount(); let i; let ii; let overrideContext; let viewsToRemove; value = Math.floor(value); viewsToRemove = childrenLength - value; if (viewsToRemove > 0) { if (viewsToRemove > childrenLength) { viewsToRemove = childrenLength; } for (i = 0, ii = viewsToRemove; i < ii; ++i) { repeat.removeView(childrenLength - (i + 1), true, !repeat.viewsRequireLifecycle); } return; } for (i = childrenLength, ii = value; i < ii; ++i) { overrideContext = createFullOverrideContext(repeat, i, i, ii); repeat.addView(overrideContext.bindingContext, overrideContext); } updateOverrideContexts(repeat.views(), 0); } }; let RepeatStrategyLocator = class RepeatStrategyLocator { constructor() { this.matchers = []; this.strategies = []; this.addStrategy(items => items === null || items === undefined, new NullRepeatStrategy()); this.addStrategy(items => items instanceof Array, new ArrayRepeatStrategy()); this.addStrategy(items => items instanceof Map, new MapRepeatStrategy()); this.addStrategy(items => items instanceof Set, new SetRepeatStrategy()); this.addStrategy(items => typeof items === 'number', new NumberRepeatStrategy()); } addStrategy(matcher, strategy) { this.matchers.push(matcher); this.strategies.push(strategy); } getStrategy(items) { let matchers = this.matchers; for (let i = 0, ii = matchers.length; i < ii; ++i) { if (matchers[i](items)) { return this.strategies[i]; } } return null; } }; const lifecycleOptionalBehaviors = ['focus', 'if', 'else', 'repeat', 'show', 'hide', 'with']; function behaviorRequiresLifecycle(instruction) { let t = instruction.type; let name = t.elementName !== null ? t.elementName : t.attributeName; return lifecycleOptionalBehaviors.indexOf(name) === -1 && (t.handlesAttached || t.handlesBind || t.handlesCreated || t.handlesDetached || t.handlesUnbind) || t.viewFactory && viewsRequireLifecycle(t.viewFactory) || instruction.viewFactory && viewsRequireLifecycle(instruction.viewFactory); } function targetRequiresLifecycle(instruction) { let behaviors = instruction.behaviorInstructions; if (behaviors) { let i = behaviors.length; while (i--) { if (behaviorRequiresLifecycle(behaviors[i])) { return true; } } } return instruction.viewFactory && viewsRequireLifecycle(instruction.viewFactory); } function viewsRequireLifecycle(viewFactory) { if ('_viewsRequireLifecycle' in viewFactory) { return viewFactory._viewsRequireLifecycle; } viewFactory._viewsRequireLifecycle = false; if (viewFactory.viewFactory) { viewFactory._viewsRequireLifecycle = viewsRequireLifecycle(viewFactory.viewFactory); return viewFactory._viewsRequireLifecycle; } if (viewFactory.template.querySelector('.au-animate')) { viewFactory._viewsRequireLifecycle = true; return true; } for (let id in viewFactory.instructions) { if (targetRequiresLifecycle(viewFactory.instructions[id])) { viewFactory._viewsRequireLifecycle = true; return true; } } viewFactory._viewsRequireLifecycle = false; return false; } let AbstractRepeater = class AbstractRepeater { constructor(options) { Object.assign(this, { local: 'items', viewsRequireLifecycle: true }, options); } viewCount() { throw new Error('subclass must implement `viewCount`'); } views() { throw new Error('subclass must implement `views`'); } view(index) { throw new Error('subclass must implement `view`'); } matcher() { throw new Error('subclass must implement `matcher`'); } addView(bindingContext, overrideContext) { throw new Error('subclass must implement `addView`'); } insertView(index, bindingContext, overrideContext) { throw new Error('subclass must implement `insertView`'); } moveView(sourceIndex, targetIndex) { throw new Error('subclass must implement `moveView`'); } removeAllViews(returnToCache, skipAnimation) { throw new Error('subclass must implement `removeAllViews`'); } removeViews(viewsToRemove, returnToCache, skipAnimation) { throw new Error('subclass must implement `removeView`'); } removeView(index, returnToCache, skipAnimation) { throw new Error('subclass must implement `removeView`'); } updateBindings(view) { throw new Error('subclass must implement `updateBindings`'); } }; var _dec$8, _dec2$7, _class$8, _class2$6, _descriptor$2, _descriptor2$2, _descriptor3$1, _descriptor4$1; function _initDefineProp$2(target, property, descriptor, context) { if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 }); } function _applyDecoratedDescriptor$2(target, property, decorators, descriptor, context) { var desc = {}; Object['ke' + 'ys'](descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object['define' + 'Property'](target, property, desc); desc = null; } return desc; } let Repeat = (_dec$8 = customAttribute('repeat'), _dec2$7 = inject(BoundViewFactory, TargetInstruction, ViewSlot, ViewResources, ObserverLocator, RepeatStrategyLocator), _dec$8(_class$8 = templateController(_class$8 = _dec2$7(_class$8 = (_class2$6 = class Repeat extends AbstractRepeater { constructor(viewFactory, instruction, viewSlot, viewResources, observerLocator, strategyLocator) { super({ local: 'item', viewsRequireLifecycle: viewsRequireLifecycle(viewFactory) }); _initDefineProp$2(this, 'items', _descriptor$2, this); _initDefineProp$2(this, 'local', _descriptor2$2, this); _initDefineProp$2(this, 'key', _descriptor3$1, this); _initDefineProp$2(this, 'value', _descriptor4$1, this); this.viewFactory = viewFactory; this.instruction = instruction; this.viewSlot = viewSlot; this.lookupFunctions = viewResources.lookupFunctions; this.observerLocator = observerLocator; this.key = 'key'; this.value = 'value'; this.strategyLocator = strategyLocator; this.ignoreMutation = false; this.sourceExpression = getItemsSourceExpression(this.instruction, 'repeat.for'); this.isOneTime = isOneTime(this.sourceExpression); this.viewsRequireLifecycle = viewsRequireLifecycle(viewFactory); } call(context, changes) { this[context](this.items, changes); } bind(bindingContext, overrideContext) { this.scope = { bindingContext, overrideContext }; this.matcherBinding = this._captureAndRemoveMatcherBinding(); this.itemsChanged(); } unbind() { this.scope = null; this.items = null; this.matcherBinding = null; this.viewSlot.removeAll(true, true); this._unsubscribeCollection(); } _unsubscribeCollection() { if (this.collectionObserver) { this.collectionObserver.unsubscribe(this.callContext, this); this.collectionObserver = null; this.callContext = null; } } itemsChanged() { this._unsubscribeCollection(); if (!this.scope) { return; } let items = this.items; this.strategy = this.strategyLocator.getStrategy(items); if (!this.strategy) { throw new Error(`Value for '${this.sourceExpression}' is non-repeatable`); } if (!this.isOneTime && !this._observeInnerCollection()) { this._observeCollection(); } this.ignoreMutation = true; this.strategy.instanceChanged(this, items); this.observerLocator.taskQueue.queueMicroTask(() => { this.ignoreMutation = false; }); } _getInnerCollection() { let expression = unwrapExpression(this.sourceExpression); if (!expression) { return null; } return expression.evaluate(this.scope, null); } handleCollectionMutated(collection, changes) { if (!this.collectionObserver) { return; } if (this.ignoreMutation) { return; } this.strategy.instanceMutated(this, collection, changes); } handleInnerCollectionMutated(collection, changes) { if (!this.collectionObserver) { return; } if (this.ignoreMutation) { return; } this.ignoreMutation = true; let newItems = this.sourceExpression.evaluate(this.scope, this.lookupFunctions); this.observerLocator.taskQueue.queueMicroTask(() => this.ignoreMutation = false); if (newItems === this.items) { this.itemsChanged(); } else { this.items = newItems; } } _observeInnerCollection() { let items = this._getInnerCollection(); let strategy = this.strategyLocator.getStrategy(items); if (!strategy) { return false; } this.collectionObserver = strategy.getCollectionObserver(this.observerLocator, items); if (!this.collectionObserver) { return false; } this.callContext = 'handleInnerCollectionMutated'; this.collectionObserver.subscribe(this.callContext, this); return true; } _observeCollection() { let items = this.items; this.collectionObserver = this.strategy.getCollectionObserver(this.observerLocator, items); if (this.collectionObserver) { this.callContext = 'handleCollectionMutated'; this.collectionObserver.subscribe(this.callContext, this); } } _captureAndRemoveMatcherBinding() { if (this.viewFactory.viewFactory) { const instructions = this.viewFactory.viewFactory.instructions; const instructionIds = Object.keys(instructions); for (let i = 0; i < instructionIds.length; i++) { const expressions = instructions[instructionIds[i]].expressions; if (expressions) { for (let ii = 0; i < expressions.length; i++) { if (expressions[ii].targetProperty === 'matcher') { const matcherBinding = expressions[ii]; expressions.splice(ii, 1); return matcherBinding; } } } } } return undefined; } viewCount() { return this.viewSlot.children.length; } views() { return this.viewSlot.children; } view(index) { return this.viewSlot.children[index]; } matcher() { return this.matcherBinding ? this.matcherBinding.sourceExpression.evaluate(this.scope, this.matcherBinding.lookupFunctions) : null; } addView(bindingContext, overrideContext) { let view = this.viewFactory.create(); view.bind(bindingContext, overrideContext); this.viewSlot.add(view); } insertView(index, bindingContext, overrideContext) { let view = this.viewFactory.create(); view.bind(bindingContext, overrideContext); this.viewSlot.insert(index, view); } moveView(sourceIndex, targetIndex) { this.viewSlot.move(sourceIndex, targetIndex); } removeAllViews(returnToCache, skipAnimation) { return this.viewSlot.removeAll(returnToCache, skipAnimation); } removeViews(viewsToRemove, returnToCache, skipAnimation) { return this.viewSlot.removeMany(viewsToRemove, returnToCache, skipAnimation); } removeView(index, returnToCache, skipAnimation) { return this.viewSlot.removeAt(index, returnToCache, skipAnimation); } updateBindings(view) { let j = view.bindings.length; while (j--) { updateOneTimeBinding(view.bindings[j]); } j = view.controllers.length; while (j--) { let k = view.controllers[j].boundProperties.length; while (k--) { let binding = view.controllers[j].boundProperties[k].binding; updateOneTimeBinding(binding); } } } }, (_descriptor$2 = _applyDecoratedDescriptor$2(_class2$6.prototype, 'items', [bindable], { enumerable: true, initializer: null }), _descriptor2$2 = _applyDecoratedDescriptor$2(_class2$6.prototype, 'local', [bindable], { enumerable: true, initializer: null }), _descriptor3$1 = _applyDecoratedDescriptor$2(_class2$6.prototype, 'key', [bindable], { enumerable: true, initializer: null }), _descriptor4$1 = _applyDecoratedDescriptor$2(_class2$6.prototype, 'value', [bindable], { enumerable: true, initializer: null })), _class2$6)) || _class$8) || _class$8) || _class$8); const aureliaHideClassName = 'aurelia-hide'; const aureliaHideClass = `.${aureliaHideClassName} { display:none !important; }`; function injectAureliaHideStyleAtHead() { DOM.injectStyles(aureliaHideClass); } function injectAureliaHideStyleAtBoundary(domBoundary) { if (FEATURE.shadowDOM && domBoundary && !domBoundary.hasAureliaHideStyle) { domBoundary.hasAureliaHideStyle = true; DOM.injectStyles(aureliaHideClass, domBoundary); } } var _dec$9, _class$9; let Show = (_dec$9 = customAttribute('show'), _dec$9(_class$9 = class Show { static inject() { return [DOM.Element, Animator, Optional.of(DOM.boundary, true)]; } constructor(element, animator, domBoundary) { this.element = element; this.animator = animator; this.domBoundary = domBoundary; } created() { injectAureliaHideStyleAtBoundary(this.domBoundary); } valueChanged(newValue) { if (newValue) { this.animator.removeClass(this.element, aureliaHideClassName); } else { this.animator.addClass(this.element, aureliaHideClassName); } } bind(bindingContext) { this.valueChanged(this.value); } }) || _class$9); var _dec$a, _class$a; let Hide = (_dec$a = customAttribute('hide'), _dec$a(_class$a = class Hide { static inject() { return [DOM.Element, Animator, Optional.of(DOM.boundary, true)]; } constructor(element, animator, domBoundary) { this.element = element; this.animator = animator; this.domBoundary = domBoundary; } created() { injectAureliaHideStyleAtBoundary(this.domBoundary); } valueChanged(newValue) { if (newValue) { this.animator.addClass(this.element, aureliaHideClassName); } else { this.animator.removeClass(this.element, aureliaHideClassName); } } bind(bindingContext) { this.valueChanged(this.value); } }) || _class$a); const SCRIPT_REGEX = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi; let HTMLSanitizer = class HTMLSanitizer { sanitize(input) { return input.replace(SCRIPT_REGEX, ''); } }; var _dec$b, _dec2$8, _class$b; let SanitizeHTMLValueConverter = (_dec$b = valueConverter('sanitizeHTML'), _dec2$8 = inject(HTMLSanitizer), _dec$b(_class$b = _dec2$8(_class$b = class SanitizeHTMLValueConverter { constructor(sanitizer) { this.sanitizer = sanitizer; } toView(untrustedMarkup) { if (untrustedMarkup === null || untrustedMarkup === undefined) { return null; } return this.sanitizer.sanitize(untrustedMarkup); } }) || _class$b) || _class$b); var _dec$c, _dec2$9, _class$c; let Replaceable = (_dec$c = customAttribute('replaceable'), _dec2$9 = inject(BoundViewFactory, ViewSlot), _dec$c(_class$c = templateController(_class$c = _dec2$9(_class$c = class Replaceable { constructor(viewFactory, viewSlot) { this.viewFactory = viewFactory; this.viewSlot = viewSlot; this.view = null; } bind(bindingContext, overrideContext) { if (this.view === null) { this.view = this.viewFactory.create(); this.viewSlot.add(this.view); } this.view.bind(bindingContext, overrideContext); } unbind() { this.view.unbind(); } }) || _class$c) || _class$c) || _class$c); var _dec$d, _class$d; let Focus = (_dec$d = customAttribute('focus', bindingMode.twoWay), _dec$d(_class$d = class Focus { static inject() { return [DOM.Element, TaskQueue]; } constructor(element, taskQueue) { this.element = element; this.taskQueue = taskQueue; this.isAttached = false; this.needsApply = false; } valueChanged(newValue) { if (this.isAttached) { this._apply(); } else { this.needsApply = true; } } _apply() { if (this.value) { this.taskQueue.queueMicroTask(() => { if (this.value) { this.element.focus(); } }); } else { this.element.blur(); } } attached() { this.isAttached = true; if (this.needsApply) { this.needsApply = false; this._apply(); } this.element.addEventListener('focus', this); this.element.addEventListener('blur', this); } detached() { this.isAttached = false; this.element.removeEventListener('focus', this); this.element.removeEventListener('blur', this); } handleEvent(e) { if (e.type === 'focus') { this.value = true; } else if (DOM.activeElement !== this.element) { this.value = false; } } }) || _class$d); let cssUrlMatcher = /url\((?!['"]data)([^)]+)\)/gi; function fixupCSSUrls(address, css) { if (typeof css !== 'string') { throw new Error(`Failed loading required CSS file: ${address}`); } return css.replace(cssUrlMatcher, (match, p1) => { let quote = p1.charAt(0); if (quote === '\'' || quote === '"') { p1 = p1.substr(1, p1.length - 2); } return 'url(\'' + relativeToFile(p1, address) + '\')'; }); } let CSSResource = class CSSResource { constructor(address) { this.address = address; this._scoped = null; this._global = false; this._alreadyGloballyInjected = false; } initialize(container, target) { this._scoped = new target(this); } register(registry, name) { if (name === 'scoped') { registry.registerViewEngineHooks(this._scoped); } else { this._global = true; } } load(container) { return container.get(Loader).loadText(this.address).catch(err => null).then(text => { text = fixupCSSUrls(this.address, text); this._scoped.css = text; if (this._global) { this._alreadyGloballyInjected = true; DOM.injectStyles(text); } }); } }; let CSSViewEngineHooks = class CSSViewEngineHooks { constructor(owner) { this.owner = owner; this.css = null; } beforeCompile(content, resources, instruction) { if (instruction.targetShadowDOM) { DOM.injectStyles(this.css, content, true); } else if (FEATURE.scopedCSS) { let styleNode = DOM.injectStyles(this.css, content, true); styleNode.setAttribute('scoped', 'scoped'); } else if (this._global && !this.owner._alreadyGloballyInjected) { DOM.injectStyles(this.css); this.owner._alreadyGloballyInjected = true; } } }; function _createCSSResource(address) { var _dec, _class; let ViewCSS = (_dec = resource(new CSSResource(address)), _dec(_class = class ViewCSS extends CSSViewEngineHooks {}) || _class); return ViewCSS; } var _dec$e, _class$e; let AttrBindingBehavior = (_dec$e = bindingBehavior('attr'), _dec$e(_class$e = class AttrBindingBehavior { bind(binding, source) { binding.targetObserver = new DataAttributeObserver(binding.target, binding.targetProperty); } unbind(binding, source) {} }) || _class$e); var _dec$f, _dec2$a, _class$f, _dec3$4, _dec4$3, _class2$7, _dec5$3, _dec6$3, _class3$4, _dec7$3, _dec8$2, _class4$3, _dec9$2, _dec10$2, _class5$4; let modeBindingBehavior = { bind(binding, source, lookupFunctions) { binding.originalMode = binding.mode; binding.mode = this.mode; }, unbind(binding, source) { binding.mode = binding.originalMode; binding.originalMode = null; } }; let OneTimeBindingBehavior = (_dec$f = mixin(modeBindingBehavior), _dec2$a = bindingBehavior('oneTime'), _dec$f(_class$f = _dec2$a(_class$f = class OneTimeBindingBehavior { constructor() { this.mode = bindingMode.oneTime; } }) || _class$f) || _class$f); let OneWayBindingBehavior = (_dec3$4 = mixin(modeBindingBehavior), _dec4$3 = bindingBehavior('oneWay'), _dec3$4(_class2$7 = _dec4$3(_class2$7 = class OneWayBindingBehavior { constructor() { this.mode = bindingMode.toView; } }) || _class2$7) || _class2$7); let ToViewBindingBehavior = (_dec5$3 = mixin(modeBindingBehavior), _dec6$3 = bindingBehavior('toView'), _dec5$3(_class3$4 = _dec6$3(_class3$4 = class ToViewBindingBehavior { constructor() { this.mode = bindingMode.toView; } }) || _class3$4) || _class3$4); let FromViewBindingBehavior = (_dec7$3 = mixin(modeBindingBehavior), _dec8$2 = bindingBehavior('fromView'), _dec7$3(_class4$3 = _dec8$2(_class4$3 = class FromViewBindingBehavior { constructor() { this.mode = bindingMode.fromView; } }) || _class4$3) || _class4$3); let TwoWayBindingBehavior = (_dec9$2 = mixin(modeBindingBehavior), _dec10$2 = bindingBehavior('twoWay'), _dec9$2(_class5$4 = _dec10$2(_class5$4 = class TwoWayBindingBehavior { constructor() { this.mode = bindingMode.twoWay; } }) || _class5$4) || _class5$4); var _dec$g, _class$g; function throttle(newValue) { let state = this.throttleState; let elapsed = +new Date() - state.last; if (elapsed >= state.delay) { clearTimeout(state.timeoutId); state.timeoutId = null; state.last = +new Date(); this.throttledMethod(newValue); return; } state.newValue = newValue; if (state.timeoutId === null) { state.timeoutId = setTimeout(() => { state.timeoutId = null; state.last = +new Date(); this.throttledMethod(state.newValue); }, state.delay - elapsed); } } let ThrottleBindingBehavior = (_dec$g = bindingBehavior('throttle'), _dec$g(_class$g = class ThrottleBindingBehavior { bind(binding, source, delay = 200) { let methodToThrottle = 'updateTarget'; if (binding.callSource) { methodToThrottle = 'callSource'; } else if (binding.updateSource && binding.mode === bindingMode.twoWay) { methodToThrottle = 'updateSource'; } binding.throttledMethod = binding[methodToThrottle]; binding.throttledMethod.originalName = methodToThrottle; binding[methodToThrottle] = throttle; binding.throttleState = { delay: delay, last: 0, timeoutId: null }; } unbind(binding, source) { let methodToRestore = binding.throttledMethod.originalName; binding[methodToRestore] = binding.throttledMethod; binding.throttledMethod = null; clearTimeout(binding.throttleState.timeoutId); binding.throttleState = null; } }) || _class$g); var _dec$h, _class$h; const unset = {}; function debounceCallSource(event) { const state = this.debounceState; clearTimeout(state.timeoutId); state.timeoutId = setTimeout(() => this.debouncedMethod(event), state.delay); } function debounceCall(context, newValue, oldValue) { const state = this.debounceState; clearTimeout(state.timeoutId); if (context !== state.callContextToDebounce) { state.oldValue = unset; this.debouncedMethod(context, newValue, oldValue); return; } if (state.oldValue === unset) { state.oldValue = oldValue; } state.timeoutId = setTimeout(() => { const _oldValue = state.oldValue; state.oldValue = unset; this.debouncedMethod(context, newValue, _oldValue); }, state.delay); } let DebounceBindingBehavior = (_dec$h = bindingBehavior('debounce'), _dec$h(_class$h = class DebounceBindingBehavior { bind(binding, source, delay = 200) { const isCallSource = binding.callSource !== undefined; const methodToDebounce = isCallSource ? 'callSource' : 'call'; const debouncer = isCallSource ? debounceCallSource : debounceCall; const mode = binding.mode; const callContextToDebounce = mode === bindingMode.twoWay || mode === bindingMode.fromView ? targetContext : sourceContext; binding.debouncedMethod = binding[methodToDebounce]; binding.debouncedMethod.originalName = methodToDebounce; binding[methodToDebounce] = debouncer; binding.debounceState = { callContextToDebounce, delay, timeoutId: 0, oldValue: unset }; } unbind(binding, source) { const methodToRestore = binding.debouncedMethod.originalName; binding[methodToRestore] = binding.debouncedMethod; binding.debouncedMethod = null; clearTimeout(binding.debounceState.timeoutId); binding.debounceState = null; } }) || _class$h); var _dec$i, _class$i; function findOriginalEventTarget$1(event) { return event.path && event.path[0] || event.deepPath && event.deepPath[0] || event.target; } function handleSelfEvent(event) { let target = findOriginalEventTarget$1(event); if (this.target !== target) return; this.selfEventCallSource(event); } let SelfBindingBehavior = (_dec$i = bindingBehavior('self'), _dec$i(_class$i = class SelfBindingBehavior { bind(binding, source) { if (!binding.callSource || !binding.targetEvent) throw new Error('Self binding behavior only supports event.'); binding.selfEventCallSource = binding.callSource; binding.callSource = handleSelfEvent; } unbind(binding, source) { binding.callSource = binding.selfEventCallSource; binding.selfEventCallSource = null; } }) || _class$i); let BindingSignaler = class BindingSignaler { constructor() { this.signals = {}; } signal(name) { let bindings = this.signals[name]; if (!bindings) { return; } let i = bindings.length; while (i--) { bindings[i].call(sourceContext); } } }; var _dec$j, _class$j; let SignalBindingBehavior = (_dec$j = bindingBehavior('signal'), _dec$j(_class$j = class SignalBindingBehavior { static inject() { return [BindingSignaler]; } constructor(bindingSignaler) { this.signals = bindingSignaler.signals; } bind(binding, source) { if (!binding.updateTarget) { throw new Error('Only property bindings and string interpolation bindings can be signaled. Trigger, delegate and call bindings cannot be signaled.'); } if (arguments.length === 3) { let name = arguments[2]; let bindings = this.signals[name] || (this.signals[name] = []); bindings.push(binding); binding.signalName = name; } else if (arguments.length > 3) { let names = Array.prototype.slice.call(arguments, 2); let i = names.length; while (i--) { let name = names[i]; let bindings = this.signals[name] || (this.signals[name] = []); bindings.push(binding); } binding.signalName = names; } else { throw new Error('Signal name is required.'); } } unbind(binding, source) { let name = binding.signalName; binding.signalName = null; if (Array.isArray(name)) { let names = name; let i = names.length; while (i--) { let n = names[i]; let bindings = this.signals[n]; bindings.splice(bindings.indexOf(binding), 1); } } else { let bindings = this.signals[name]; bindings.splice(bindings.indexOf(binding), 1); } } }) || _class$j); var _dec$k, _class$k; const eventNamesRequired = 'The updateTrigger binding behavior requires at least one event name argument: eg <input value.bind="firstName & updateTrigger:\'blur\'">'; const notApplicableMessage = 'The updateTrigger binding behavior can only be applied to two-way/ from-view bindings on input/select elements.'; let UpdateTriggerBindingBehavior = (_dec$k = bindingBehavior('updateTrigger'), _dec$k(_class$k = class UpdateTriggerBindingBehavior { bind(binding, source, ...events) { if (events.length === 0) { throw new Error(eventNamesRequired); } if (binding.mode !== bindingMode.twoWay && binding.mode !== bindingMode.fromView) { throw new Error(notApplicableMessage); } let targetObserver = binding.observerLocator.getObserver(binding.target, binding.targetProperty); if (!targetObserver.handler) { throw new Error(notApplicableMessage); } binding.targetObserver = targetObserver; targetObserver.originalHandler = binding.targetObserver.handler; let handler = new EventSubscriber(events); targetObserver.handler = handler; } unbind(binding, source) { binding.targetObserver.handler.dispose(); binding.targetObserver.handler = binding.targetObserver.originalHandler; binding.targetObserver.originalHandler = null; } }) || _class$k); function _createDynamicElement(name, viewUrl, bindableNames) { var _dec, _dec2, _class; let DynamicElement = (_dec = customElement(name), _dec2 = useView(viewUrl), _dec(_class = _dec2(_class = class DynamicElement { bind(bindingContext) { this.$parent = bindingContext; } }) || _class) || _class); for (let i = 0, ii = bindableNames.length; i < ii; ++i) { bindable(bindableNames[i])(DynamicElement); } return DynamicElement; } function getElementName(address) { return (/([^\/^\?]+)\.html/i.exec(address)[1].toLowerCase() ); } function configure$1(config) { let viewEngine = config.container.get(ViewEngine); let loader = config.aurelia.loader; viewEngine.addResourcePlugin('.html', { 'fetch': function (address) { return loader.loadTemplate(address).then(registryEntry => { let bindable = registryEntry.template.getAttribute('bindable'); let elementName = getElementName(address); if (bindable) { bindable = bindable.split(',').map(x => x.trim()); registryEntry.template.removeAttribute('bindable'); } else { bindable = []; } return { [elementName]: _createDynamicElement(elementName, address, bindable) }; }); } }); } function configure$2(config) { injectAureliaHideStyleAtHead(); config.globalResources(Compose, If, Else, With, Repeat, Show, Hide, Replaceable, Focus, SanitizeHTMLValueConverter, OneTimeBindingBehavior, OneWayBindingBehavior, ToViewBindingBehavior, FromViewBindingBehavior, TwoWayBindingBehavior, ThrottleBindingBehavior, DebounceBindingBehavior, SelfBindingBehavior, SignalBindingBehavior, UpdateTriggerBindingBehavior, AttrBindingBehavior); configure$1(config); let viewEngine = config.container.get(ViewEngine); let styleResourcePlugin = { fetch(address) { return { [address]: _createCSSResource(address) }; } }; ['.css', '.less', '.sass', '.scss', '.styl'].forEach(ext => viewEngine.addResourcePlugin(ext, styleResourcePlugin)); } const logger$3 = getLogger('event-aggregator'); let Handler = class Handler { constructor(messageType, callback) { this.messageType = messageType; this.callback = callback; } handle(message) { if (message instanceof this.messageType) { this.callback.call(null, message); } } }; function invokeCallback(callback, data, event) { try { callback(data, event); } catch (e) { logger$3.error(e); } } function invokeHandler(handler, data) { try { handler.handle(data); } catch (e) { logger$3.error(e); } } let EventAggregator = class EventAggregator { constructor() { this.eventLookup = {}; this.messageHandlers = []; } publish(event, data) { let subscribers; let i; if (!event) { throw new Error('Event was invalid.'); } if (typeof event === 'string') { subscribers = this.eventLookup[event]; if (subscribers) { subscribers = subscribers.slice(); i = subscribers.length; while (i--) { invokeCallback(subscribers[i], data, event); } } } else { subscribers = this.messageHandlers.slice(); i = subscribers.length; while (i--) { invokeHandler(subscribers[i], event); } } } subscribe(event, callback) { let handler; let subscribers; if (!event) { throw new Error('Event channel/type was invalid.'); } if (typeof event === 'string') { handler = callback; subscribers = this.eventLookup[event] || (this.eventLookup[event] = []); } else { handler = new Handler(event, callback); subscribers = this.messageHandlers; } subscribers.push(handler); return { dispose() { let idx = subscribers.indexOf(handler); if (idx !== -1) { subscribers.splice(idx, 1); } } }; } subscribeOnce(event, callback) { let sub = this.subscribe(event, (a, b) => { sub.dispose(); return callback(a, b); }); return sub; } }; function includeEventsIn(obj) { let ea = new EventAggregator(); obj.subscribeOnce = function (event, callback) { return ea.subscribeOnce(event, callback); }; obj.subscribe = function (event, callback) { return ea.subscribe(event, callback); }; obj.publish = function (event, data) { ea.publish(event, data); }; return ea; } function configure$3(config) { config.instance(EventAggregator, includeEventsIn(config.aurelia)); } function mi$1(name) { throw new Error('History must implement ' + name + '().'); } var History = function () { function History() { } History.prototype.activate = function activate(options) { mi$1('activate'); }; History.prototype.deactivate = function deactivate() { mi$1('deactivate'); }; History.prototype.getAbsoluteRoot = function getAbsoluteRoot() { mi$1('getAbsoluteRoot'); }; History.prototype.navigate = function navigate(fragment, options) { mi$1('navigate'); }; History.prototype.navigateBack = function navigateBack() { mi$1('navigateBack'); }; History.prototype.setTitle = function setTitle(title) { mi$1('setTitle'); }; History.prototype.setState = function setState(key, value) { mi$1('setState'); }; History.prototype.getState = function getState(key) { mi$1('getState'); }; History.prototype.getHistoryIndex = function getHistoryIndex() { mi$1('getHistoryIndex'); }; History.prototype.go = function go(movement) { mi$1('go'); }; return History; }(); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. 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 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var LinkHandler = (function () { function LinkHandler() { } LinkHandler.prototype.activate = function (history) { }; LinkHandler.prototype.deactivate = function () { }; return LinkHandler; }()); var DefaultLinkHandler = (function (_super) { __extends(DefaultLinkHandler, _super); function DefaultLinkHandler() { var _this = _super.call(this) || this; _this.handler = function (e) { var _a = DefaultLinkHandler.getEventInfo(e), shouldHandleEvent = _a.shouldHandleEvent, href = _a.href; if (shouldHandleEvent) { e.preventDefault(); _this.history.navigate(href); } }; return _this; } DefaultLinkHandler.prototype.activate = function (history) { if (history._hasPushState) { this.history = history; DOM.addEventListener('click', this.handler, true); } }; DefaultLinkHandler.prototype.deactivate = function () { DOM.removeEventListener('click', this.handler, true); }; DefaultLinkHandler.getEventInfo = function (event) { var $event = event; var info = { shouldHandleEvent: false, href: null, anchor: null }; var target = DefaultLinkHandler.findClosestAnchor($event.target); if (!target || !DefaultLinkHandler.targetIsThisWindow(target)) { return info; } if (hasAttribute$1(target, 'download') || hasAttribute$1(target, 'router-ignore') || hasAttribute$1(target, 'data-router-ignore')) { return info; } if ($event.altKey || $event.ctrlKey || $event.metaKey || $event.shiftKey) { return info; } var href = target.getAttribute('href'); info.anchor = target; info.href = href; var leftButtonClicked = $event.which === 1; var isRelative = href && !(href.charAt(0) === '#' || (/^[a-z]+:/i).test(href)); info.shouldHandleEvent = leftButtonClicked && isRelative; return info; }; DefaultLinkHandler.findClosestAnchor = function (el) { while (el) { if (el.tagName === 'A') { return el; } el = el.parentNode; } }; DefaultLinkHandler.targetIsThisWindow = function (target) { var targetWindow = target.getAttribute('target'); var win = PLATFORM.global; return !targetWindow || targetWindow === win.name || targetWindow === '_self'; }; return DefaultLinkHandler; }(LinkHandler)); var hasAttribute$1 = function (el, attr) { return el.hasAttribute(attr); }; var BrowserHistory = (function (_super) { __extends(BrowserHistory, _super); function BrowserHistory(linkHandler) { var _this = _super.call(this) || this; _this._isActive = false; _this._checkUrlCallback = _this._checkUrl.bind(_this); _this.location = PLATFORM.location; _this.history = PLATFORM.history; _this.linkHandler = linkHandler; return _this; } BrowserHistory.prototype.activate = function (options) { if (this._isActive) { throw new Error('History has already been activated.'); } var $history = this.history; var wantsPushState = !!options.pushState; this._isActive = true; var normalizedOptions = this.options = Object.assign({}, { root: '/' }, this.options, options); var rootUrl = this.root = ('/' + normalizedOptions.root + '/').replace(rootStripper, '/'); var wantsHashChange = this._wantsHashChange = normalizedOptions.hashChange !== false; var hasPushState = this._hasPushState = !!(normalizedOptions.pushState && $history && $history.pushState); var eventName; if (hasPushState) { eventName = 'popstate'; } else if (wantsHashChange) { eventName = 'hashchange'; } PLATFORM.addEventListener(eventName, this._checkUrlCallback); if (wantsHashChange && wantsPushState) { var $location = this.location; var atRoot = $location.pathname.replace(/[^\/]$/, '$&/') === rootUrl; if (!hasPushState && !atRoot) { var fragment = this.fragment = this._getFragment(null, true); $location.replace(rootUrl + $location.search + '#' + fragment); return true; } else if (hasPushState && atRoot && $location.hash) { var fragment = this.fragment = this._getHash().replace(routeStripper, ''); $history.replaceState({}, DOM.title, rootUrl + fragment + $location.search); } } if (!this.fragment) { this.fragment = this._getFragment(''); } this.linkHandler.activate(this); if (!normalizedOptions.silent) { return this._loadUrl(''); } }; BrowserHistory.prototype.deactivate = function () { var handler = this._checkUrlCallback; PLATFORM.removeEventListener('popstate', handler); PLATFORM.removeEventListener('hashchange', handler); this._isActive = false; this.linkHandler.deactivate(); }; BrowserHistory.prototype.getAbsoluteRoot = function () { var $location = this.location; var origin = createOrigin($location.protocol, $location.hostname, $location.port); return "" + origin + this.root; }; BrowserHistory.prototype.navigate = function (fragment, _a) { var _b = _a === void 0 ? {} : _a, _c = _b.trigger, trigger = _c === void 0 ? true : _c, _d = _b.replace, replace = _d === void 0 ? false : _d; var location = this.location; if (fragment && absoluteUrl.test(fragment)) { location.href = fragment; return true; } if (!this._isActive) { return false; } fragment = this._getFragment(fragment || ''); if (this.fragment === fragment && !replace) { return false; } this.fragment = fragment; var url = this.root + fragment; if (fragment === '' && url !== '/') { url = url.slice(0, -1); } if (this._hasPushState) { url = url.replace('//', '/'); this.history[replace ? 'replaceState' : 'pushState']({}, DOM.title, url); } else if (this._wantsHashChange) { updateHash(location, fragment, replace); } else { location.assign(url); } if (trigger) { return this._loadUrl(fragment); } return true; }; BrowserHistory.prototype.navigateBack = function () { this.history.back(); }; BrowserHistory.prototype.setTitle = function (title) { DOM.title = title; }; BrowserHistory.prototype.setState = function (key, value) { var $history = this.history; var state = Object.assign({}, $history.state); var _a = this.location, pathname = _a.pathname, search = _a.search, hash = _a.hash; state[key] = value; $history.replaceState(state, null, "" + pathname + search + hash); }; BrowserHistory.prototype.getState = function (key) { var state = Object.assign({}, this.history.state); return state[key]; }; BrowserHistory.prototype.getHistoryIndex = function () { var historyIndex = this.getState('HistoryIndex'); if (historyIndex === undefined) { historyIndex = this.history.length - 1; this.setState('HistoryIndex', historyIndex); } return historyIndex; }; BrowserHistory.prototype.go = function (movement) { this.history.go(movement); }; BrowserHistory.prototype._getHash = function () { return this.location.hash.substr(1); }; BrowserHistory.prototype._getFragment = function (fragment, forcePushState) { var rootUrl; if (!fragment) { if (this._hasPushState || !this._wantsHashChange || forcePushState) { var location_1 = this.location; fragment = location_1.pathname + location_1.search; rootUrl = this.root.replace(trailingSlash, ''); if (!fragment.indexOf(rootUrl)) { fragment = fragment.substr(rootUrl.length); } } else { fragment = this._getHash(); } } return '/' + fragment.replace(routeStripper, ''); }; BrowserHistory.prototype._checkUrl = function () { var current = this._getFragment(''); if (current !== this.fragment) { this._loadUrl(''); } }; BrowserHistory.prototype._loadUrl = function (fragmentOverride) { var fragment = this.fragment = this._getFragment(fragmentOverride); return this.options.routeHandler ? this.options.routeHandler(fragment) : false; }; BrowserHistory.inject = [LinkHandler]; return BrowserHistory; }(History)); var routeStripper = /^#?\/*|\s+$/g; var rootStripper = /^\/+|\/+$/g; var trailingSlash = /\/$/; var absoluteUrl = /^([a-z][a-z0-9+\-.]*:)?\/\//i; function updateHash($location, fragment, replace) { if (replace) { var href = $location.href.replace(/(javascript:|#).*$/, ''); $location.replace(href + '#' + fragment); } else { $location.hash = '#' + fragment; } } function createOrigin(protocol, hostname, port) { return protocol + "//" + hostname + (port ? ':' + port : ''); } function configure$4(config) { var $config = config; $config.singleton(History, BrowserHistory); $config.transient(LinkHandler, DefaultLinkHandler); } let State = class State { constructor(charSpec) { this.charSpec = charSpec; this.nextStates = []; } get(charSpec) { for (let child of this.nextStates) { let isEqual = child.charSpec.validChars === charSpec.validChars && child.charSpec.invalidChars === charSpec.invalidChars; if (isEqual) { return child; } } return undefined; } put(charSpec) { let state = this.get(charSpec); if (state) { return state; } state = new State(charSpec); this.nextStates.push(state); if (charSpec.repeat) { state.nextStates.push(state); } return state; } match(ch) { let nextStates = this.nextStates; let results = []; for (let i = 0, l = nextStates.length; i < l; i++) { let child = nextStates[i]; let charSpec = child.charSpec; if (charSpec.validChars !== undefined) { if (charSpec.validChars.indexOf(ch) !== -1) { results.push(child); } } else if (charSpec.invalidChars !== undefined) { if (charSpec.invalidChars.indexOf(ch) === -1) { results.push(child); } } } return results; } }; const specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\']; const escapeRegex = new RegExp('(\\' + specials.join('|\\') + ')', 'g'); let StaticSegment = class StaticSegment { constructor(string, caseSensitive) { this.string = string; this.caseSensitive = caseSensitive; } eachChar(callback) { let s = this.string; for (let i = 0, ii = s.length; i < ii; ++i) { let ch = s[i]; callback({ validChars: this.caseSensitive ? ch : ch.toUpperCase() + ch.toLowerCase() }); } } regex() { return this.string.replace(escapeRegex, '\\$1'); } generate() { return this.string; } }; let DynamicSegment = class DynamicSegment { constructor(name, optional) { this.name = name; this.optional = optional; } eachChar(callback) { callback({ invalidChars: '/', repeat: true }); } regex() { return '([^/]+)'; } generate(params, consumed) { consumed[this.name] = true; return params[this.name]; } }; let StarSegment = class StarSegment { constructor(name) { this.name = name; } eachChar(callback) { callback({ invalidChars: '', repeat: true }); } regex() { return '(.+)'; } generate(params, consumed) { consumed[this.name] = true; return params[this.name]; } }; let EpsilonSegment = class EpsilonSegment { eachChar() {} regex() { return ''; } generate() { return ''; } }; let RouteRecognizer = class RouteRecognizer { constructor() { this.rootState = new State(); this.names = {}; this.routes = new Map(); } add(route) { if (Array.isArray(route)) { route.forEach(r => this.add(r)); return undefined; } let currentState = this.rootState; let skippableStates = []; let regex = '^'; let types = { statics: 0, dynamics: 0, stars: 0 }; let names = []; let routeName = route.handler.name; let isEmpty = true; let segments = parse(route.path, names, types, route.caseSensitive); for (let i = 0, ii = segments.length; i < ii; i++) { let segment = segments[i]; if (segment instanceof EpsilonSegment) { continue; } let [firstState, nextState] = addSegment(currentState, segment); for (let j = 0, jj = skippableStates.length; j < jj; j++) { skippableStates[j].nextStates.push(firstState); } if (segment.optional) { skippableStates.push(nextState); regex += `(?:/${segment.regex()})?`; } else { currentState = nextState; regex += `/${segment.regex()}`; skippableStates.length = 0; isEmpty = false; } } if (isEmpty) { currentState = currentState.put({ validChars: '/' }); regex += '/?'; } let handlers = [{ handler: route.handler, names: names }]; this.routes.set(route.handler, { segments, handlers }); if (routeName) { let routeNames = Array.isArray(routeName) ? routeName : [routeName]; for (let i = 0; i < routeNames.length; i++) { if (!(routeNames[i] in this.names)) { this.names[routeNames[i]] = { segments, handlers }; } } } for (let i = 0; i < skippableStates.length; i++) { let state = skippableStates[i]; state.handlers = handlers; state.regex = new RegExp(regex + '$', route.caseSensitive ? '' : 'i'); state.types = types; } currentState.handlers = handlers; currentState.regex = new RegExp(regex + '$', route.caseSensitive ? '' : 'i'); currentState.types = types; return currentState; } getRoute(nameOrRoute) { return typeof nameOrRoute === 'string' ? this.names[nameOrRoute] : this.routes.get(nameOrRoute); } handlersFor(nameOrRoute) { let route = this.getRoute(nameOrRoute); if (!route) { throw new Error(`There is no route named ${nameOrRoute}`); } return [...route.handlers]; } hasRoute(nameOrRoute) { return !!this.getRoute(nameOrRoute); } generate(nameOrRoute, params) { let route = this.getRoute(nameOrRoute); if (!route) { throw new Error(`There is no route named ${nameOrRoute}`); } let handler = route.handlers[0].handler; if (handler.generationUsesHref) { return handler.href; } let routeParams = Object.assign({}, params); let segments = route.segments; let consumed = {}; let output = ''; for (let i = 0, l = segments.length; i < l; i++) { let segment = segments[i]; if (segment instanceof EpsilonSegment) { continue; } let segmentValue = segment.generate(routeParams, consumed); if (segmentValue === null || segmentValue === undefined) { if (!segment.optional) { throw new Error(`A value is required for route parameter '${segment.name}' in route '${nameOrRoute}'.`); } } else { output += '/'; output += segmentValue; } } if (output.charAt(0) !== '/') { output = '/' + output; } for (let param in consumed) { delete routeParams[param]; } let queryString = buildQueryString(routeParams); output += queryString ? `?${queryString}` : ''; return output; } recognize(path) { let states = [this.rootState]; let queryParams = {}; let isSlashDropped = false; let normalizedPath = path; let queryStart = normalizedPath.indexOf('?'); if (queryStart !== -1) { let queryString = normalizedPath.substr(queryStart + 1, normalizedPath.length); normalizedPath = normalizedPath.substr(0, queryStart); queryParams = parseQueryString(queryString); } normalizedPath = decodeURI(normalizedPath); if (normalizedPath.charAt(0) !== '/') { normalizedPath = '/' + normalizedPath; } let pathLen = normalizedPath.length; if (pathLen > 1 && normalizedPath.charAt(pathLen - 1) === '/') { normalizedPath = normalizedPath.substr(0, pathLen - 1); isSlashDropped = true; } for (let i = 0, l = normalizedPath.length; i < l; i++) { states = recognizeChar(states, normalizedPath.charAt(i)); if (!states.length) { break; } } let solutions = []; for (let i = 0, l = states.length; i < l; i++) { if (states[i].handlers) { solutions.push(states[i]); } } states = sortSolutions(solutions); let state = solutions[0]; if (state && state.handlers) { if (isSlashDropped && state.regex.source.slice(-5) === '(.+)$') { normalizedPath = normalizedPath + '/'; } return findHandler(state, normalizedPath, queryParams); } } }; let RecognizeResults = class RecognizeResults { constructor(queryParams) { this.splice = Array.prototype.splice; this.slice = Array.prototype.slice; this.push = Array.prototype.push; this.length = 0; this.queryParams = queryParams || {}; } }; function parse(route, names, types, caseSensitive) { let normalizedRoute = route; if (route.charAt(0) === '/') { normalizedRoute = route.substr(1); } let results = []; let splitRoute = normalizedRoute.split('/'); for (let i = 0, ii = splitRoute.length; i < ii; ++i) { let segment = splitRoute[i]; let match = segment.match(/^:([^?]+)(\?)?$/); if (match) { let [, name, optional] = match; if (name.indexOf('=') !== -1) { throw new Error(`Parameter ${name} in route ${route} has a default value, which is not supported.`); } results.push(new DynamicSegment(name, !!optional)); names.push(name); types.dynamics++; continue; } match = segment.match(/^\*(.+)$/); if (match) { results.push(new StarSegment(match[1])); names.push(match[1]); types.stars++; } else if (segment === '') { results.push(new EpsilonSegment()); } else { results.push(new StaticSegment(segment, caseSensitive)); types.statics++; } } return results; } function sortSolutions(states) { return states.sort((a, b) => { if (a.types.stars !== b.types.stars) { return a.types.stars - b.types.stars; } if (a.types.stars) { if (a.types.statics !== b.types.statics) { return b.types.statics - a.types.statics; } if (a.types.dynamics !== b.types.dynamics) { return b.types.dynamics - a.types.dynamics; } } if (a.types.dynamics !== b.types.dynamics) { return a.types.dynamics - b.types.dynamics; } if (a.types.statics !== b.types.statics) { return b.types.statics - a.types.statics; } return 0; }); } function recognizeChar(states, ch) { let nextStates = []; for (let i = 0, l = states.length; i < l; i++) { let state = states[i]; nextStates.push(...state.match(ch)); } return nextStates; } function findHandler(state, path, queryParams) { let handlers = state.handlers; let regex = state.regex; let captures = path.match(regex); let currentCapture = 1; let result = new RecognizeResults(queryParams); for (let i = 0, l = handlers.length; i < l; i++) { let handler = handlers[i]; let names = handler.names; let params = {}; for (let j = 0, m = names.length; j < m; j++) { params[names[j]] = captures[currentCapture++]; } result.push({ handler: handler.handler, params: params, isDynamic: !!names.length }); } return result; } function addSegment(currentState, segment) { let firstState = currentState.put({ validChars: '/' }); let nextState = firstState; segment.eachChar(ch => { nextState = nextState.put(ch); }); return [firstState, nextState]; } /** * Class used to represent an instruction during a navigation. */ class NavigationInstruction { constructor(init) { /** * Current built viewport plan of this nav instruction */ this.plan = null; this.options = {}; Object.assign(this, init); this.params = this.params || {}; this.viewPortInstructions = {}; let ancestorParams = []; let current = this; do { let currentParams = Object.assign({}, current.params); if (current.config && current.config.hasChildRouter) { // remove the param for the injected child route segment delete currentParams[current.getWildCardName()]; } ancestorParams.unshift(currentParams); current = current.parentInstruction; } while (current); let allParams = Object.assign({}, this.queryParams, ...ancestorParams); this.lifecycleArgs = [allParams, this.config, this]; } /** * Gets an array containing this instruction and all child instructions for the current navigation. */ getAllInstructions() { let instructions = [this]; let viewPortInstructions = this.viewPortInstructions; for (let key in viewPortInstructions) { let childInstruction = viewPortInstructions[key].childNavigationInstruction; if (childInstruction) { instructions.push(...childInstruction.getAllInstructions()); } } return instructions; } /** * Gets an array containing the instruction and all child instructions for the previous navigation. * Previous instructions are no longer available after navigation completes. */ getAllPreviousInstructions() { return this.getAllInstructions().map(c => c.previousInstruction).filter(c => c); } addViewPortInstruction(nameOrInitOptions, strategy, moduleId, component) { let viewPortInstruction; let viewPortName = typeof nameOrInitOptions === 'string' ? nameOrInitOptions : nameOrInitOptions.name; const lifecycleArgs = this.lifecycleArgs; const config = Object.assign({}, lifecycleArgs[1], { currentViewPort: viewPortName }); if (typeof nameOrInitOptions === 'string') { viewPortInstruction = { name: nameOrInitOptions, strategy: strategy, moduleId: moduleId, component: component, childRouter: component.childRouter, lifecycleArgs: [lifecycleArgs[0], config, lifecycleArgs[2]] }; } else { viewPortInstruction = { name: viewPortName, strategy: nameOrInitOptions.strategy, component: nameOrInitOptions.component, moduleId: nameOrInitOptions.moduleId, childRouter: nameOrInitOptions.component.childRouter, lifecycleArgs: [lifecycleArgs[0], config, lifecycleArgs[2]] }; } return this.viewPortInstructions[viewPortName] = viewPortInstruction; } /** * Gets the name of the route pattern's wildcard parameter, if applicable. */ getWildCardName() { // todo: potential issue, or at least unsafe typings let configRoute = this.config.route; let wildcardIndex = configRoute.lastIndexOf('*'); return configRoute.substr(wildcardIndex + 1); } /** * Gets the path and query string created by filling the route * pattern's wildcard parameter with the matching param. */ getWildcardPath() { let wildcardName = this.getWildCardName(); let path = this.params[wildcardName] || ''; let queryString = this.queryString; if (queryString) { path += '?' + queryString; } return path; } /** * Gets the instruction's base URL, accounting for wildcard route parameters. */ getBaseUrl() { let $encodeURI = encodeURI; let fragment = decodeURI(this.fragment); if (fragment === '') { let nonEmptyRoute = this.router.routes.find(route => { return route.name === this.config.name && route.route !== ''; }); if (nonEmptyRoute) { fragment = nonEmptyRoute.route; } } if (!this.params) { return $encodeURI(fragment); } let wildcardName = this.getWildCardName(); let path = this.params[wildcardName] || ''; if (!path) { return $encodeURI(fragment); } return $encodeURI(fragment.substr(0, fragment.lastIndexOf(path))); } /** * Finalize a viewport instruction * @internal */ _commitChanges(waitToSwap) { let router = this.router; router.currentInstruction = this; const previousInstruction = this.previousInstruction; if (previousInstruction) { previousInstruction.config.navModel.isActive = false; } this.config.navModel.isActive = true; router.refreshNavigation(); let loads = []; let delaySwaps = []; let viewPortInstructions = this.viewPortInstructions; for (let viewPortName in viewPortInstructions) { let viewPortInstruction = viewPortInstructions[viewPortName]; let viewPort = router.viewPorts[viewPortName]; if (!viewPort) { throw new Error(`There was no router-view found in the view for ${viewPortInstruction.moduleId}.`); } let childNavInstruction = viewPortInstruction.childNavigationInstruction; if (viewPortInstruction.strategy === "replace" /* Replace */) { if (childNavInstruction && childNavInstruction.parentCatchHandler) { loads.push(childNavInstruction._commitChanges(waitToSwap)); } else { if (waitToSwap) { delaySwaps.push({ viewPort, viewPortInstruction }); } loads.push(viewPort .process(viewPortInstruction, waitToSwap) .then(() => childNavInstruction ? childNavInstruction._commitChanges(waitToSwap) : Promise.resolve())); } } else { if (childNavInstruction) { loads.push(childNavInstruction._commitChanges(waitToSwap)); } } } return Promise .all(loads) .then(() => { delaySwaps.forEach(x => x.viewPort.swap(x.viewPortInstruction)); return null; }) .then(() => prune(this)); } /**@internal */ _updateTitle() { let router = this.router; let title = this._buildTitle(router.titleSeparator); if (title) { router.history.setTitle(title); } } /**@internal */ _buildTitle(separator = ' | ') { let title = ''; let childTitles = []; let navModelTitle = this.config.navModel.title; let instructionRouter = this.router; let viewPortInstructions = this.viewPortInstructions; if (navModelTitle) { title = instructionRouter.transformTitle(navModelTitle); } for (let viewPortName in viewPortInstructions) { let viewPortInstruction = viewPortInstructions[viewPortName]; let child_nav_instruction = viewPortInstruction.childNavigationInstruction; if (child_nav_instruction) { let childTitle = child_nav_instruction._buildTitle(separator); if (childTitle) { childTitles.push(childTitle); } } } if (childTitles.length) { title = childTitles.join(separator) + (title ? separator : '') + title; } if (instructionRouter.title) { title += (title ? separator : '') + instructionRouter.transformTitle(instructionRouter.title); } return title; } } const prune = (instruction) => { instruction.previousInstruction = null; instruction.plan = null; }; /** * Class for storing and interacting with a route's navigation settings. */ class NavModel { constructor(router, relativeHref) { /** * True if this nav item is currently active. */ this.isActive = false; /** * The title. */ this.title = null; /** * This nav item's absolute href. */ this.href = null; /** * This nav item's relative href. */ this.relativeHref = null; /** * Data attached to the route at configuration time. */ this.settings = {}; /** * The route config. */ this.config = null; this.router = router; this.relativeHref = relativeHref; } /** * Sets the route's title and updates document.title. * If the a navigation is in progress, the change will be applied * to document.title when the navigation completes. * * @param title The new title. */ setTitle(title) { this.title = title; if (this.isActive) { this.router.updateTitle(); } } } function _normalizeAbsolutePath(path, hasPushState, absolute = false) { if (!hasPushState && path[0] !== '#') { path = '#' + path; } if (hasPushState && absolute) { path = path.substring(1, path.length); } return path; } function _createRootedPath(fragment, baseUrl, hasPushState, absolute) { if (isAbsoluteUrl.test(fragment)) { return fragment; } let path = ''; if (baseUrl.length && baseUrl[0] !== '/') { path += '/'; } path += baseUrl; if ((!path.length || path[path.length - 1] !== '/') && fragment[0] !== '/') { path += '/'; } if (path.length && path[path.length - 1] === '/' && fragment[0] === '/') { path = path.substring(0, path.length - 1); } return _normalizeAbsolutePath(path + fragment, hasPushState, absolute); } function _resolveUrl(fragment, baseUrl, hasPushState) { if (isRootedPath.test(fragment)) { return _normalizeAbsolutePath(fragment, hasPushState); } return _createRootedPath(fragment, baseUrl, hasPushState); } function _ensureArrayWithSingleRoutePerConfig(config) { let routeConfigs = []; if (Array.isArray(config.route)) { for (let i = 0, ii = config.route.length; i < ii; ++i) { let current = Object.assign({}, config); current.route = config.route[i]; routeConfigs.push(current); } } else { routeConfigs.push(Object.assign({}, config)); } return routeConfigs; } const isRootedPath = /^#?\//; const isAbsoluteUrl = /^([a-z][a-z0-9+\-.]*:)?\/\//i; /** * Class used to configure a [[Router]] instance. * * @constructor */ class RouterConfiguration { constructor() { this.instructions = []; this.options = {}; this.pipelineSteps = []; } /** * Adds a step to be run during the [[Router]]'s navigation pipeline. * * @param name The name of the pipeline slot to insert the step into. * @param step The pipeline step. * @chainable */ addPipelineStep(name, step) { if (step === null || step === undefined) { throw new Error('Pipeline step cannot be null or undefined.'); } this.pipelineSteps.push({ name, step }); return this; } /** * Adds a step to be run during the [[Router]]'s authorize pipeline slot. * * @param step The pipeline step. * @chainable */ addAuthorizeStep(step) { return this.addPipelineStep("authorize" /* Authorize */, step); } /** * Adds a step to be run during the [[Router]]'s preActivate pipeline slot. * * @param step The pipeline step. * @chainable */ addPreActivateStep(step) { return this.addPipelineStep("preActivate" /* PreActivate */, step); } /** * Adds a step to be run during the [[Router]]'s preRender pipeline slot. * * @param step The pipeline step. * @chainable */ addPreRenderStep(step) { return this.addPipelineStep("preRender" /* PreRender */, step); } /** * Adds a step to be run during the [[Router]]'s postRender pipeline slot. * * @param step The pipeline step. * @chainable */ addPostRenderStep(step) { return this.addPipelineStep("postRender" /* PostRender */, step); } /** * Configures a route that will be used if there is no previous location available on navigation cancellation. * * @param fragment The URL fragment to use as the navigation destination. * @chainable */ fallbackRoute(fragment) { this._fallbackRoute = fragment; return this; } /** * Maps one or more routes to be registered with the router. * * @param route The [[RouteConfig]] to map, or an array of [[RouteConfig]] to map. * @chainable */ map(route) { if (Array.isArray(route)) { route.forEach(r => this.map(r)); return this; } return this.mapRoute(route); } /** * Configures defaults to use for any view ports. * * @param viewPortConfig a view port configuration object to use as a * default, of the form { viewPortName: { moduleId } }. * @chainable */ useViewPortDefaults(viewPortConfig) { this.viewPortDefaults = viewPortConfig; return this; } /** * Maps a single route to be registered with the router. * * @param route The [[RouteConfig]] to map. * @chainable */ mapRoute(config) { this.instructions.push(router => { let routeConfigs = _ensureArrayWithSingleRoutePerConfig(config); let navModel; for (let i = 0, ii = routeConfigs.length; i < ii; ++i) { let routeConfig = routeConfigs[i]; routeConfig.settings = routeConfig.settings || {}; if (!navModel) { navModel = router.createNavModel(routeConfig); } router.addRoute(routeConfig, navModel); } }); return this; } /** * Registers an unknown route handler to be run when the URL fragment doesn't match any registered routes. * * @param config A string containing a moduleId to load, or a [[RouteConfig]], or a function that takes the * [[NavigationInstruction]] and selects a moduleId to load. * @chainable */ mapUnknownRoutes(config) { this.unknownRouteConfig = config; return this; } /** * Applies the current configuration to the specified [[Router]]. * * @param router The [[Router]] to apply the configuration to. */ exportToRouter(router) { let instructions = this.instructions; for (let i = 0, ii = instructions.length; i < ii; ++i) { instructions[i](router); } let { title, titleSeparator, unknownRouteConfig, _fallbackRoute, viewPortDefaults } = this; if (title) { router.title = title; } if (titleSeparator) { router.titleSeparator = titleSeparator; } if (unknownRouteConfig) { router.handleUnknownRoutes(unknownRouteConfig); } if (_fallbackRoute) { router.fallbackRoute = _fallbackRoute; } if (viewPortDefaults) { router.useViewPortDefaults(viewPortDefaults); } Object.assign(router.options, this.options); let pipelineSteps = this.pipelineSteps; let pipelineStepCount = pipelineSteps.length; if (pipelineStepCount) { if (!router.isRoot) { throw new Error('Pipeline steps can only be added to the root router'); } let pipelineProvider = router.pipelineProvider; for (let i = 0, ii = pipelineStepCount; i < ii; ++i) { let { name, step } = pipelineSteps[i]; pipelineProvider.addStep(name, step); } } } } /** * The primary class responsible for handling routing and navigation. */ class Router { /** * @param container The [[Container]] to use when child routers. * @param history The [[History]] implementation to delegate navigation requests to. */ constructor(container, history) { /** * The parent router, or null if this instance is not a child router. */ this.parent = null; this.options = {}; /** * The defaults used when a viewport lacks specified content */ this.viewPortDefaults = {}; /** * Extension point to transform the document title before it is built and displayed. * By default, child routers delegate to the parent router, and the app router * returns the title unchanged. */ this.transformTitle = (title) => { if (this.parent) { return this.parent.transformTitle(title); } return title; }; this.container = container; this.history = history; this.reset(); } /** * Fully resets the router's internal state. Primarily used internally by the framework when multiple calls to setRoot are made. * Use with caution (actually, avoid using this). Do not use this to simply change your navigation model. */ reset() { this.viewPorts = {}; this.routes = []; this.baseUrl = ''; this.isConfigured = false; this.isNavigating = false; this.isExplicitNavigation = false; this.isExplicitNavigationBack = false; this.isNavigatingFirst = false; this.isNavigatingNew = false; this.isNavigatingRefresh = false; this.isNavigatingForward = false; this.isNavigatingBack = false; this.couldDeactivate = false; this.navigation = []; this.currentInstruction = null; this.viewPortDefaults = {}; this._fallbackOrder = 100; this._recognizer = new RouteRecognizer(); this._childRecognizer = new RouteRecognizer(); this._configuredPromise = new Promise(resolve => { this._resolveConfiguredPromise = resolve; }); } /** * Gets a value indicating whether or not this [[Router]] is the root in the router tree. I.e., it has no parent. */ get isRoot() { return !this.parent; } /** * Registers a viewPort to be used as a rendering target for activated routes. * * @param viewPort The viewPort. * @param name The name of the viewPort. 'default' if unspecified. */ registerViewPort(viewPort, name) { name = name || 'default'; this.viewPorts[name] = viewPort; } /** * Returns a Promise that resolves when the router is configured. */ ensureConfigured() { return this._configuredPromise; } /** * Configures the router. * * @param callbackOrConfig The [[RouterConfiguration]] or a callback that takes a [[RouterConfiguration]]. */ configure(callbackOrConfig) { this.isConfigured = true; let result = callbackOrConfig; let config; if (typeof callbackOrConfig === 'function') { config = new RouterConfiguration(); result = callbackOrConfig(config); } return Promise .resolve(result) .then((c) => { if (c && c.exportToRouter) { config = c; } config.exportToRouter(this); this.isConfigured = true; this._resolveConfiguredPromise(); }); } /** * Navigates to a new location. * * @param fragment The URL fragment to use as the navigation destination. * @param options The navigation options. */ navigate(fragment, options) { if (!this.isConfigured && this.parent) { return this.parent.navigate(fragment, options); } this.isExplicitNavigation = true; return this.history.navigate(_resolveUrl(fragment, this.baseUrl, this.history._hasPushState), options); } /** * Navigates to a new location corresponding to the route and params specified. Equivallent to [[Router.generate]] followed * by [[Router.navigate]]. * * @param route The name of the route to use when generating the navigation location. * @param params The route parameters to be used when populating the route pattern. * @param options The navigation options. */ navigateToRoute(route, params, options) { let path = this.generate(route, params); return this.navigate(path, options); } /** * Navigates back to the most recent location in history. */ navigateBack() { this.isExplicitNavigationBack = true; this.history.navigateBack(); } /** * Creates a child router of the current router. * * @param container The [[Container]] to provide to the child router. Uses the current [[Router]]'s [[Container]] if unspecified. * @returns {Router} The new child Router. */ createChild(container) { let childRouter = new Router(container || this.container.createChild(), this.history); childRouter.parent = this; return childRouter; } /** * Generates a URL fragment matching the specified route pattern. * * @param name The name of the route whose pattern should be used to generate the fragment. * @param params The route params to be used to populate the route pattern. * @param options If options.absolute = true, then absolute url will be generated; otherwise, it will be relative url. * @returns {string} A string containing the generated URL fragment. */ generate(nameOrRoute, params = {}, options = {}) { // A child recognizer generates routes for potential child routes. Any potential child route is added // to the childRoute property of params for the childRouter to recognize. When generating routes, we // use the childRecognizer when childRoute params are available to generate a child router enabled route. let recognizer = 'childRoute' in params ? this._childRecognizer : this._recognizer; let hasRoute = recognizer.hasRoute(nameOrRoute); if (!hasRoute) { if (this.parent) { return this.parent.generate(nameOrRoute, params, options); } throw new Error(`A route with name '${nameOrRoute}' could not be found. Check that \`name: '${nameOrRoute}'\` was specified in the route's config.`); } let path = recognizer.generate(nameOrRoute, params); let rootedPath = _createRootedPath(path, this.baseUrl, this.history._hasPushState, options.absolute); return options.absolute ? `${this.history.getAbsoluteRoot()}${rootedPath}` : rootedPath; } /** * Creates a [[NavModel]] for the specified route config. * * @param config The route config. */ createNavModel(config) { let navModel = new NavModel(this, 'href' in config ? config.href // potential error when config.route is a string[] ? : config.route); navModel.title = config.title; navModel.order = config.nav; navModel.href = config.href; navModel.settings = config.settings; navModel.config = config; return navModel; } /** * Registers a new route with the router. * * @param config The [[RouteConfig]]. * @param navModel The [[NavModel]] to use for the route. May be omitted for single-pattern routes. */ addRoute(config, navModel) { if (Array.isArray(config.route)) { let routeConfigs = _ensureArrayWithSingleRoutePerConfig(config); // the following is wrong. todo: fix this after TS refactoring release routeConfigs.forEach(this.addRoute.bind(this)); return; } validateRouteConfig(config); if (!('viewPorts' in config) && !config.navigationStrategy) { config.viewPorts = { 'default': { moduleId: config.moduleId, view: config.view } }; } if (!navModel) { navModel = this.createNavModel(config); } this.routes.push(config); let path = config.route; if (path.charAt(0) === '/') { path = path.substr(1); } let caseSensitive = config.caseSensitive === true; let state = this._recognizer.add({ path: path, handler: config, caseSensitive: caseSensitive }); if (path) { let settings = config.settings; delete config.settings; let withChild = JSON.parse(JSON.stringify(config)); config.settings = settings; withChild.route = `${path}/*childRoute`; withChild.hasChildRouter = true; this._childRecognizer.add({ path: withChild.route, handler: withChild, caseSensitive: caseSensitive }); withChild.navModel = navModel; withChild.settings = config.settings; withChild.navigationStrategy = config.navigationStrategy; } config.navModel = navModel; let navigation = this.navigation; if ((navModel.order || navModel.order === 0) && navigation.indexOf(navModel) === -1) { if ((!navModel.href && navModel.href !== '') && (state.types.dynamics || state.types.stars)) { throw new Error('Invalid route config for "' + config.route + '" : dynamic routes must specify an "href:" to be included in the navigation model.'); } if (typeof navModel.order !== 'number') { navModel.order = ++this._fallbackOrder; } navigation.push(navModel); // this is a potential error / inconsistency between browsers // // MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort // If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, // but sorted with respect to all different elements. // Note: the ECMAscript standard does not guarantee this behaviour, // and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this. navigation.sort((a, b) => a.order - b.order); } } /** * Gets a value indicating whether or not this [[Router]] or one of its ancestors has a route registered with the specified name. * * @param name The name of the route to check. */ hasRoute(name) { return !!(this._recognizer.hasRoute(name) || this.parent && this.parent.hasRoute(name)); } /** * Gets a value indicating whether or not this [[Router]] has a route registered with the specified name. * * @param name The name of the route to check. */ hasOwnRoute(name) { return this._recognizer.hasRoute(name); } /** * Register a handler to use when the incoming URL fragment doesn't match any registered routes. * * @param config The moduleId, or a function that selects the moduleId, or a [[RouteConfig]]. */ handleUnknownRoutes(config) { if (!config) { throw new Error('Invalid unknown route handler'); } this.catchAllHandler = instruction => { return this ._createRouteConfig(config, instruction) .then(c => { instruction.config = c; return instruction; }); }; } /** * Updates the document title using the current navigation instruction. */ updateTitle() { let parentRouter = this.parent; if (parentRouter) { return parentRouter.updateTitle(); } let currentInstruction = this.currentInstruction; if (currentInstruction) { currentInstruction._updateTitle(); } return undefined; } /** * Updates the navigation routes with hrefs relative to the current location. * Note: This method will likely move to a plugin in a future release. */ refreshNavigation() { let nav = this.navigation; for (let i = 0, length = nav.length; i < length; i++) { let current = nav[i]; if (!current.config.href) { current.href = _createRootedPath(current.relativeHref, this.baseUrl, this.history._hasPushState); } else { current.href = _normalizeAbsolutePath(current.config.href, this.history._hasPushState); } } } /** * Sets the default configuration for the view ports. This specifies how to * populate a view port for which no module is specified. The default is * an empty view/view-model pair. */ useViewPortDefaults($viewPortDefaults) { // a workaround to have strong typings while not requiring to expose interface ViewPortInstruction let viewPortDefaults = $viewPortDefaults; for (let viewPortName in viewPortDefaults) { let viewPortConfig = viewPortDefaults[viewPortName]; this.viewPortDefaults[viewPortName] = { moduleId: viewPortConfig.moduleId }; } } /**@internal */ _refreshBaseUrl() { let parentRouter = this.parent; if (parentRouter) { this.baseUrl = generateBaseUrl(parentRouter, parentRouter.currentInstruction); } } /**@internal */ _createNavigationInstruction(url = '', parentInstruction = null) { let fragment = url; let queryString = ''; let queryIndex = url.indexOf('?'); if (queryIndex !== -1) { fragment = url.substr(0, queryIndex); queryString = url.substr(queryIndex + 1); } let urlRecognizationResults = this._recognizer.recognize(url); if (!urlRecognizationResults || !urlRecognizationResults.length) { urlRecognizationResults = this._childRecognizer.recognize(url); } let instructionInit = { fragment, queryString, config: null, parentInstruction, previousInstruction: this.currentInstruction, router: this, options: { compareQueryParams: this.options.compareQueryParams } }; let result; if (urlRecognizationResults && urlRecognizationResults.length) { let first = urlRecognizationResults[0]; let instruction = new NavigationInstruction(Object.assign({}, instructionInit, { params: first.params, queryParams: first.queryParams || urlRecognizationResults.queryParams, config: first.config || first.handler })); if (typeof first.handler === 'function') { result = evaluateNavigationStrategy(instruction, first.handler, first); } else if (first.handler && typeof first.handler.navigationStrategy === 'function') { result = evaluateNavigationStrategy(instruction, first.handler.navigationStrategy, first.handler); } else { result = Promise.resolve(instruction); } } else if (this.catchAllHandler) { let instruction = new NavigationInstruction(Object.assign({}, instructionInit, { params: { path: fragment }, queryParams: urlRecognizationResults ? urlRecognizationResults.queryParams : {}, config: null // config will be created by the catchAllHandler })); result = evaluateNavigationStrategy(instruction, this.catchAllHandler); } else if (this.parent) { let router = this._parentCatchAllHandler(this.parent); if (router) { let newParentInstruction = this._findParentInstructionFromRouter(router, parentInstruction); let instruction = new NavigationInstruction(Object.assign({}, instructionInit, { params: { path: fragment }, queryParams: urlRecognizationResults ? urlRecognizationResults.queryParams : {}, router: router, parentInstruction: newParentInstruction, parentCatchHandler: true, config: null // config will be created by the chained parent catchAllHandler })); result = evaluateNavigationStrategy(instruction, router.catchAllHandler); } } if (result && parentInstruction) { this.baseUrl = generateBaseUrl(this.parent, parentInstruction); } return result || Promise.reject(new Error(`Route not found: ${url}`)); } /**@internal */ _findParentInstructionFromRouter(router, instruction) { if (instruction.router === router) { instruction.fragment = router.baseUrl; // need to change the fragment in case of a redirect instead of moduleId return instruction; } else if (instruction.parentInstruction) { return this._findParentInstructionFromRouter(router, instruction.parentInstruction); } return undefined; } /**@internal */ _parentCatchAllHandler(router) { if (router.catchAllHandler) { return router; } else if (router.parent) { return this._parentCatchAllHandler(router.parent); } return false; } /** * @internal */ _createRouteConfig(config, instruction) { return Promise .resolve(config) .then((c) => { if (typeof c === 'string') { return { moduleId: c }; } else if (typeof c === 'function') { return c(instruction); } return c; }) // typing here could be either RouteConfig or RedirectConfig // but temporarily treat both as RouteConfig // todo: improve typings precision .then((c) => typeof c === 'string' ? { moduleId: c } : c) .then((c) => { c.route = instruction.params.path; validateRouteConfig(c); if (!c.navModel) { c.navModel = this.createNavModel(c); } return c; }); } } /* @internal exported for unit testing */ const generateBaseUrl = (router, instruction) => { return `${router.baseUrl || ''}${instruction.getBaseUrl() || ''}`; }; /* @internal exported for unit testing */ const validateRouteConfig = (config) => { if (typeof config !== 'object') { throw new Error('Invalid Route Config'); } if (typeof config.route !== 'string') { let name = config.name || '(no name)'; throw new Error('Invalid Route Config for "' + name + '": You must specify a "route:" pattern.'); } if (!('redirect' in config || config.moduleId || config.navigationStrategy || config.viewPorts)) { throw new Error('Invalid Route Config for "' + config.route + '": You must specify a "moduleId:", "redirect:", "navigationStrategy:", or "viewPorts:".'); } }; /* @internal exported for unit testing */ const evaluateNavigationStrategy = (instruction, evaluator, context) => { return Promise .resolve(evaluator.call(context, instruction)) .then(() => { if (!('viewPorts' in instruction.config)) { instruction.config.viewPorts = { 'default': { moduleId: instruction.config.moduleId } }; } return instruction; }); }; /**@internal exported for unit testing */ const createNextFn = (instruction, steps) => { let index = -1; const next = function () { index++; if (index < steps.length) { let currentStep = steps[index]; try { return currentStep(instruction, next); } catch (e) { return next.reject(e); } } else { return next.complete(); } }; next.complete = createCompletionHandler(next, "completed" /* Completed */); next.cancel = createCompletionHandler(next, "canceled" /* Canceled */); next.reject = createCompletionHandler(next, "rejected" /* Rejected */); return next; }; /**@internal exported for unit testing */ const createCompletionHandler = (next, status) => { return (output) => Promise .resolve({ status, output, completed: status === "completed" /* Completed */ }); }; /** * The class responsible for managing and processing the navigation pipeline. */ class Pipeline { constructor() { /** * The pipeline steps. And steps added via addStep will be converted to a function * The actualy running functions with correct step contexts of this pipeline */ this.steps = []; } /** * Adds a step to the pipeline. * * @param step The pipeline step. */ addStep(step) { let run; if (typeof step === 'function') { run = step; } else if (typeof step.getSteps === 'function') { // getSteps is to enable support open slots // where devs can add multiple steps into the same slot name let steps = step.getSteps(); for (let i = 0, l = steps.length; i < l; i++) { this.addStep(steps[i]); } return this; } else { run = step.run.bind(step); } this.steps.push(run); return this; } /** * Runs the pipeline. * * @param instruction The navigation instruction to process. */ run(instruction) { const nextFn = createNextFn(instruction, this.steps); return nextFn(); } } /** * Determines if the provided object is a navigation command. * A navigation command is anything with a navigate method. * * @param obj The object to check. */ function isNavigationCommand(obj) { return obj && typeof obj.navigate === 'function'; } /** * Used during the activation lifecycle to cause a redirect. */ class Redirect { /** * @param url The URL fragment to use as the navigation destination. * @param options The navigation options. */ constructor(url, options = {}) { this.url = url; this.options = Object.assign({ trigger: true, replace: true }, options); this.shouldContinueProcessing = false; } /** * Called by the activation system to set the child router. * * @param router The router. */ setRouter(router) { this.router = router; } /** * Called by the navigation pipeline to navigate. * * @param appRouter The router to be redirected. */ navigate(appRouter) { let navigatingRouter = this.options.useAppRouter ? appRouter : (this.router || appRouter); navigatingRouter.navigate(this.url, this.options); } } /** * Used during the activation lifecycle to cause a redirect to a named route. */ class RedirectToRoute { /** * @param route The name of the route. * @param params The parameters to be sent to the activation method. * @param options The options to use for navigation. */ constructor(route, params = {}, options = {}) { this.route = route; this.params = params; this.options = Object.assign({ trigger: true, replace: true }, options); this.shouldContinueProcessing = false; } /** * Called by the activation system to set the child router. * * @param router The router. */ setRouter(router) { this.router = router; } /** * Called by the navigation pipeline to navigate. * * @param appRouter The router to be redirected. */ navigate(appRouter) { let navigatingRouter = this.options.useAppRouter ? appRouter : (this.router || appRouter); navigatingRouter.navigateToRoute(this.route, this.params, this.options); } } /** * @internal exported for unit testing */ function _buildNavigationPlan(instruction, forceLifecycleMinimum) { let config = instruction.config; if ('redirect' in config) { return buildRedirectPlan(instruction); } const prevInstruction = instruction.previousInstruction; const defaultViewPortConfigs = instruction.router.viewPortDefaults; if (prevInstruction) { return buildTransitionPlans(instruction, prevInstruction, defaultViewPortConfigs, forceLifecycleMinimum); } // first navigation, only need to prepare a few information for each viewport plan const viewPortPlans = {}; let viewPortConfigs = config.viewPorts; for (let viewPortName in viewPortConfigs) { let viewPortConfig = viewPortConfigs[viewPortName]; if (viewPortConfig.moduleId === null && viewPortName in defaultViewPortConfigs) { viewPortConfig = defaultViewPortConfigs[viewPortName]; } viewPortPlans[viewPortName] = { name: viewPortName, strategy: "replace" /* Replace */, config: viewPortConfig }; } return Promise.resolve(viewPortPlans); } /** * Build redirect plan based on config of a navigation instruction * @internal exported for unit testing */ const buildRedirectPlan = (instruction) => { const config = instruction.config; const router = instruction.router; return router ._createNavigationInstruction(config.redirect) .then(redirectInstruction => { const params = {}; const originalInstructionParams = instruction.params; const redirectInstructionParams = redirectInstruction.params; for (let key in redirectInstructionParams) { // If the param on the redirect points to another param, e.g. { route: first/:this, redirect: second/:this } let val = redirectInstructionParams[key]; if (typeof val === 'string' && val[0] === ':') { val = val.slice(1); // And if that param is found on the original instruction then use it if (val in originalInstructionParams) { params[key] = originalInstructionParams[val]; } } else { params[key] = redirectInstructionParams[key]; } } let redirectLocation = router.generate(redirectInstruction.config, params, instruction.options); // Special handling for child routes for (let key in originalInstructionParams) { redirectLocation = redirectLocation.replace(`:${key}`, originalInstructionParams[key]); } let queryString = instruction.queryString; if (queryString) { redirectLocation += '?' + queryString; } return Promise.resolve(new Redirect(redirectLocation)); }); }; /** * @param viewPortPlans the Plan record that holds information about built plans * @internal exported for unit testing */ const buildTransitionPlans = (currentInstruction, previousInstruction, defaultViewPortConfigs, forceLifecycleMinimum) => { let viewPortPlans = {}; let newInstructionConfig = currentInstruction.config; let hasNewParams = hasDifferentParameterValues(previousInstruction, currentInstruction); let pending = []; let previousViewPortInstructions = previousInstruction.viewPortInstructions; for (let viewPortName in previousViewPortInstructions) { const prevViewPortInstruction = previousViewPortInstructions[viewPortName]; const prevViewPortComponent = prevViewPortInstruction.component; const newInstructionViewPortConfigs = newInstructionConfig.viewPorts; // if this is invoked on a viewport without any changes, based on new url, // newViewPortConfig will be the existing viewport instruction let nextViewPortConfig = viewPortName in newInstructionViewPortConfigs ? newInstructionViewPortConfigs[viewPortName] : prevViewPortInstruction; if (nextViewPortConfig.moduleId === null && viewPortName in defaultViewPortConfigs) { nextViewPortConfig = defaultViewPortConfigs[viewPortName]; } const viewPortActivationStrategy = determineActivationStrategy(currentInstruction, prevViewPortInstruction, nextViewPortConfig, hasNewParams, forceLifecycleMinimum); const viewPortPlan = viewPortPlans[viewPortName] = { name: viewPortName, // ViewPortInstruction can quack like a RouteConfig config: nextViewPortConfig, prevComponent: prevViewPortComponent, prevModuleId: prevViewPortInstruction.moduleId, strategy: viewPortActivationStrategy }; // recursively build nav plans for all existing child routers/viewports of this viewport // this is possible because existing child viewports and routers already have necessary information // to process the wildcard path from parent instruction if (viewPortActivationStrategy !== "replace" /* Replace */ && prevViewPortInstruction.childRouter) { const path = currentInstruction.getWildcardPath(); const task = prevViewPortInstruction .childRouter ._createNavigationInstruction(path, currentInstruction) .then((childInstruction) => { viewPortPlan.childNavigationInstruction = childInstruction; return _buildNavigationPlan(childInstruction, // is it safe to assume viewPortPlan has not been changed from previous assignment? // if so, can just use local variable viewPortPlanStrategy // there could be user code modifying viewport plan during _createNavigationInstruction? viewPortPlan.strategy === "invoke-lifecycle" /* InvokeLifecycle */) .then(childPlan => { if (childPlan instanceof Redirect) { return Promise.reject(childPlan); } childInstruction.plan = childPlan; // for bluebird ? return null; }); }); pending.push(task); } } return Promise.all(pending).then(() => viewPortPlans); }; /** * @param newViewPortConfig if this is invoked on a viewport without any changes, based on new url, newViewPortConfig will be the existing viewport instruction * @internal exported for unit testing */ const determineActivationStrategy = (currentNavInstruction, prevViewPortInstruction, newViewPortConfig, // indicates whether there is difference between old and new url params hasNewParams, forceLifecycleMinimum) => { let newInstructionConfig = currentNavInstruction.config; let prevViewPortViewModel = prevViewPortInstruction.component.viewModel; let viewPortPlanStrategy; if (prevViewPortInstruction.moduleId !== newViewPortConfig.moduleId) { viewPortPlanStrategy = "replace" /* Replace */; } else if ('determineActivationStrategy' in prevViewPortViewModel) { viewPortPlanStrategy = prevViewPortViewModel.determineActivationStrategy(...currentNavInstruction.lifecycleArgs); } else if (newInstructionConfig.activationStrategy) { viewPortPlanStrategy = newInstructionConfig.activationStrategy; } else if (hasNewParams || forceLifecycleMinimum) { viewPortPlanStrategy = "invoke-lifecycle" /* InvokeLifecycle */; } else { viewPortPlanStrategy = "no-change" /* NoChange */; } return viewPortPlanStrategy; }; /**@internal exported for unit testing */ const hasDifferentParameterValues = (prev, next) => { let prevParams = prev.params; let nextParams = next.params; let nextWildCardName = next.config.hasChildRouter ? next.getWildCardName() : null; for (let key in nextParams) { if (key === nextWildCardName) { continue; } if (prevParams[key] !== nextParams[key]) { return true; } } for (let key in prevParams) { if (key === nextWildCardName) { continue; } if (prevParams[key] !== nextParams[key]) { return true; } } if (!next.options.compareQueryParams) { return false; } let prevQueryParams = prev.queryParams; let nextQueryParams = next.queryParams; for (let key in nextQueryParams) { if (prevQueryParams[key] !== nextQueryParams[key]) { return true; } } for (let key in prevQueryParams) { if (prevQueryParams[key] !== nextQueryParams[key]) { return true; } } return false; }; /** * Transform a navigation instruction into viewport plan record object, * or a redirect request if user viewmodel demands */ class BuildNavigationPlanStep { run(navigationInstruction, next) { return _buildNavigationPlan(navigationInstruction) .then(plan => { if (plan instanceof Redirect) { return next.cancel(plan); } navigationInstruction.plan = plan; return next(); }) .catch(next.cancel); } } /** * @internal Exported for unit testing */ const loadNewRoute = (routeLoader, navigationInstruction) => { let loadingPlans = determineLoadingPlans(navigationInstruction); let loadPromises = loadingPlans.map((loadingPlan) => loadRoute(routeLoader, loadingPlan.navigationInstruction, loadingPlan.viewPortPlan)); return Promise.all(loadPromises); }; /** * @internal Exported for unit testing */ const determineLoadingPlans = (navigationInstruction, loadingPlans = []) => { let viewPortPlans = navigationInstruction.plan; for (let viewPortName in viewPortPlans) { let viewPortPlan = viewPortPlans[viewPortName]; let childNavInstruction = viewPortPlan.childNavigationInstruction; if (viewPortPlan.strategy === "replace" /* Replace */) { loadingPlans.push({ viewPortPlan, navigationInstruction }); if (childNavInstruction) { determineLoadingPlans(childNavInstruction, loadingPlans); } } else { let viewPortInstruction = navigationInstruction.addViewPortInstruction({ name: viewPortName, strategy: viewPortPlan.strategy, moduleId: viewPortPlan.prevModuleId, component: viewPortPlan.prevComponent }); if (childNavInstruction) { viewPortInstruction.childNavigationInstruction = childNavInstruction; determineLoadingPlans(childNavInstruction, loadingPlans); } } } return loadingPlans; }; /** * @internal Exported for unit testing */ const loadRoute = (routeLoader, navigationInstruction, viewPortPlan) => { let planConfig = viewPortPlan.config; let moduleId = planConfig ? planConfig.moduleId : null; return loadComponent(routeLoader, navigationInstruction, planConfig) .then((component) => { let viewPortInstruction = navigationInstruction.addViewPortInstruction({ name: viewPortPlan.name, strategy: viewPortPlan.strategy, moduleId: moduleId, component: component }); let childRouter = component.childRouter; if (childRouter) { let path = navigationInstruction.getWildcardPath(); return childRouter ._createNavigationInstruction(path, navigationInstruction) .then((childInstruction) => { viewPortPlan.childNavigationInstruction = childInstruction; return _buildNavigationPlan(childInstruction) .then((childPlan) => { if (childPlan instanceof Redirect) { return Promise.reject(childPlan); } childInstruction.plan = childPlan; viewPortInstruction.childNavigationInstruction = childInstruction; return loadNewRoute(routeLoader, childInstruction); }); }); } // ts complains without this, though they are same return void 0; }); }; /** * Load a routed-component based on navigation instruction and route config * @internal exported for unit testing only */ const loadComponent = (routeLoader, navigationInstruction, config) => { let router = navigationInstruction.router; let lifecycleArgs = navigationInstruction.lifecycleArgs; return Promise.resolve() .then(() => routeLoader.loadRoute(router, config, navigationInstruction)) .then( /** * @param component an object carrying information about loaded route * typically contains information about view model, childContainer, view and router */ (component) => { let { viewModel, childContainer } = component; component.router = router; component.config = config; if ('configureRouter' in viewModel) { let childRouter = childContainer.getChildRouter(); component.childRouter = childRouter; return childRouter .configure(c => viewModel.configureRouter(c, childRouter, lifecycleArgs[0], lifecycleArgs[1], lifecycleArgs[2])) .then(() => component); } return component; }); }; /** * Abstract class that is responsible for loading view / view model from a route config * The default implementation can be found in `aurelia-templating-router` */ class RouteLoader { /** * Load a route config based on its viewmodel / view configuration */ // return typing: return typings used to be never // as it was a throw. Changing it to Promise<any> should not cause any issues loadRoute(router, config, navigationInstruction) { throw new Error('Route loaders must implement "loadRoute(router, config, navigationInstruction)".'); } } /** * A pipeline step responsible for loading a route config of a navigation instruction */ class LoadRouteStep { /**@internal */ static inject() { return [RouteLoader]; } constructor(routeLoader) { this.routeLoader = routeLoader; } /** * Run the internal to load route config of a navigation instruction to prepare for next steps in the pipeline */ run(navigationInstruction, next) { return loadNewRoute(this.routeLoader, navigationInstruction) .then(next, next.cancel); } } /** * A pipeline step for instructing a piepline to commit changes on a navigation instruction */ class CommitChangesStep { run(navigationInstruction, next) { return navigationInstruction ._commitChanges(/*wait to swap?*/ true) .then(() => { navigationInstruction._updateTitle(); return next(); }); } } /** * An optional interface describing the available activation strategies. * @internal Used internally. */ var InternalActivationStrategy; (function (InternalActivationStrategy) { /** * Reuse the existing view model, without invoking Router lifecycle hooks. */ InternalActivationStrategy["NoChange"] = "no-change"; /** * Reuse the existing view model, invoking Router lifecycle hooks. */ InternalActivationStrategy["InvokeLifecycle"] = "invoke-lifecycle"; /** * Replace the existing view model, invoking Router lifecycle hooks. */ InternalActivationStrategy["Replace"] = "replace"; })(InternalActivationStrategy || (InternalActivationStrategy = {})); /** * The strategy to use when activating modules during navigation. */ // kept for compat reason const activationStrategy = { noChange: "no-change" /* NoChange */, invokeLifecycle: "invoke-lifecycle" /* InvokeLifecycle */, replace: "replace" /* Replace */ }; /** * Recursively find list of deactivate-able view models * and invoke the either 'canDeactivate' or 'deactivate' on each * @internal exported for unit testing */ const processDeactivatable = (navigationInstruction, callbackName, next, ignoreResult) => { let plan = navigationInstruction.plan; let infos = findDeactivatable(plan, callbackName); let i = infos.length; // query from inside out function inspect(val) { if (ignoreResult || shouldContinue(val)) { return iterate(); } return next.cancel(val); } function iterate() { if (i--) { try { let viewModel = infos[i]; let result = viewModel[callbackName](navigationInstruction); return processPotential(result, inspect, next.cancel); } catch (error) { return next.cancel(error); } } navigationInstruction.router.couldDeactivate = true; return next(); } return iterate(); }; /** * Recursively find and returns a list of deactivate-able view models * @internal exported for unit testing */ const findDeactivatable = (plan, callbackName, list = []) => { for (let viewPortName in plan) { let viewPortPlan = plan[viewPortName]; let prevComponent = viewPortPlan.prevComponent; if ((viewPortPlan.strategy === activationStrategy.invokeLifecycle || viewPortPlan.strategy === activationStrategy.replace) && prevComponent) { let viewModel = prevComponent.viewModel; if (callbackName in viewModel) { list.push(viewModel); } } if (viewPortPlan.strategy === activationStrategy.replace && prevComponent) { addPreviousDeactivatable(prevComponent, callbackName, list); } else if (viewPortPlan.childNavigationInstruction) { findDeactivatable(viewPortPlan.childNavigationInstruction.plan, callbackName, list); } } return list; }; /** * @internal exported for unit testing */ const addPreviousDeactivatable = (component, callbackName, list) => { let childRouter = component.childRouter; if (childRouter && childRouter.currentInstruction) { let viewPortInstructions = childRouter.currentInstruction.viewPortInstructions; for (let viewPortName in viewPortInstructions) { let viewPortInstruction = viewPortInstructions[viewPortName]; let prevComponent = viewPortInstruction.component; let prevViewModel = prevComponent.viewModel; if (callbackName in prevViewModel) { list.push(prevViewModel); } addPreviousDeactivatable(prevComponent, callbackName, list); } } }; /** * @internal exported for unit testing */ const processActivatable = (navigationInstruction, callbackName, next, ignoreResult) => { let infos = findActivatable(navigationInstruction, callbackName); let length = infos.length; let i = -1; // query from top down function inspect(val, router) { if (ignoreResult || shouldContinue(val, router)) { return iterate(); } return next.cancel(val); } function iterate() { i++; if (i < length) { try { let current = infos[i]; let result = current.viewModel[callbackName](...current.lifecycleArgs); return processPotential(result, (val) => inspect(val, current.router), next.cancel); } catch (error) { return next.cancel(error); } } return next(); } return iterate(); }; /** * Find list of activatable view model and add to list (3rd parameter) * @internal exported for unit testing */ const findActivatable = (navigationInstruction, callbackName, list = [], router) => { let plan = navigationInstruction.plan; Object .keys(plan) .forEach((viewPortName) => { let viewPortPlan = plan[viewPortName]; let viewPortInstruction = navigationInstruction.viewPortInstructions[viewPortName]; let viewPortComponent = viewPortInstruction.component; let viewModel = viewPortComponent.viewModel; if ((viewPortPlan.strategy === activationStrategy.invokeLifecycle || viewPortPlan.strategy === activationStrategy.replace) && callbackName in viewModel) { list.push({ viewModel, lifecycleArgs: viewPortInstruction.lifecycleArgs, router }); } let childNavInstruction = viewPortPlan.childNavigationInstruction; if (childNavInstruction) { findActivatable(childNavInstruction, callbackName, list, viewPortComponent.childRouter || router); } }); return list; }; const shouldContinue = (output, router) => { if (output instanceof Error) { return false; } if (isNavigationCommand(output)) { if (typeof output.setRouter === 'function') { output.setRouter(router); } return !!output.shouldContinueProcessing; } if (output === undefined) { return true; } return output; }; /** * wraps a subscription, allowing unsubscribe calls even if * the first value comes synchronously */ class SafeSubscription { constructor(subscriptionFunc) { this._subscribed = true; this._subscription = subscriptionFunc(this); if (!this._subscribed) { this.unsubscribe(); } } get subscribed() { return this._subscribed; } unsubscribe() { if (this._subscribed && this._subscription) { this._subscription.unsubscribe(); } this._subscribed = false; } } /** * A function to process return value from `activate`/`canActivate` steps * Supports observable/promise * * For observable, resolve at first next() or on complete() */ const processPotential = (obj, resolve, reject) => { // if promise like if (obj && typeof obj.then === 'function') { return Promise.resolve(obj).then(resolve).catch(reject); } // if observable if (obj && typeof obj.subscribe === 'function') { let obs = obj; return new SafeSubscription(sub => obs.subscribe({ next() { if (sub.subscribed) { sub.unsubscribe(); resolve(obj); } }, error(error) { if (sub.subscribed) { sub.unsubscribe(); reject(error); } }, complete() { if (sub.subscribed) { sub.unsubscribe(); resolve(obj); } } })); } // else just resolve try { return resolve(obj); } catch (error) { return reject(error); } }; /** * A pipeline step responsible for finding and activating method `canDeactivate` on a view model of a route */ class CanDeactivatePreviousStep { run(navigationInstruction, next) { return processDeactivatable(navigationInstruction, 'canDeactivate', next); } } /** * A pipeline step responsible for finding and activating method `canActivate` on a view model of a route */ class CanActivateNextStep { run(navigationInstruction, next) { return processActivatable(navigationInstruction, 'canActivate', next); } } /** * A pipeline step responsible for finding and activating method `deactivate` on a view model of a route */ class DeactivatePreviousStep { run(navigationInstruction, next) { return processDeactivatable(navigationInstruction, 'deactivate', next, true); } } /** * A pipeline step responsible for finding and activating method `activate` on a view model of a route */ class ActivateNextStep { run(navigationInstruction, next) { return processActivatable(navigationInstruction, 'activate', next, true); } } /** * A multi-slots Pipeline Placeholder Step for hooking into a pipeline execution */ class PipelineSlot { constructor(container, name, alias) { this.steps = []; this.container = container; this.slotName = name; this.slotAlias = alias; } getSteps() { return this.steps.map(x => this.container.get(x)); } } /** * Class responsible for creating the navigation pipeline. */ class PipelineProvider { /**@internal */ static inject() { return [Container]; } constructor(container) { this.container = container; this.steps = [ BuildNavigationPlanStep, CanDeactivatePreviousStep, LoadRouteStep, createPipelineSlot(container, "authorize" /* Authorize */), CanActivateNextStep, createPipelineSlot(container, "preActivate" /* PreActivate */, 'modelbind'), // NOTE: app state changes start below - point of no return DeactivatePreviousStep, ActivateNextStep, createPipelineSlot(container, "preRender" /* PreRender */, 'precommit'), CommitChangesStep, createPipelineSlot(container, "postRender" /* PostRender */, 'postcomplete') ]; } /** * Create the navigation pipeline. */ createPipeline(useCanDeactivateStep = true) { let pipeline = new Pipeline(); this.steps.forEach(step => { if (useCanDeactivateStep || step !== CanDeactivatePreviousStep) { pipeline.addStep(this.container.get(step)); } }); return pipeline; } /**@internal */ _findStep(name) { // Steps that are not PipelineSlots are constructor functions, and they will automatically fail. Probably. return this.steps.find(x => x.slotName === name || x.slotAlias === name); } /** * Adds a step into the pipeline at a known slot location. */ addStep(name, step) { let found = this._findStep(name); if (found) { let slotSteps = found.steps; // prevent duplicates if (!slotSteps.includes(step)) { slotSteps.push(step); } } else { throw new Error(`Invalid pipeline slot name: ${name}.`); } } /** * Removes a step from a slot in the pipeline */ removeStep(name, step) { let slot = this._findStep(name); if (slot) { let slotSteps = slot.steps; slotSteps.splice(slotSteps.indexOf(step), 1); } } /** * Clears all steps from a slot in the pipeline * @internal */ _clearSteps(name = '') { let slot = this._findStep(name); if (slot) { slot.steps = []; } } /** * Resets all pipeline slots */ reset() { this._clearSteps("authorize" /* Authorize */); this._clearSteps("preActivate" /* PreActivate */); this._clearSteps("preRender" /* PreRender */); this._clearSteps("postRender" /* PostRender */); } } /**@internal */ const createPipelineSlot = (container, name, alias) => { return new PipelineSlot(container, name, alias); }; const logger$4 = getLogger('app-router'); /** * The main application router. */ class AppRouter extends Router { /**@internal */ static inject() { return [Container, History, PipelineProvider, EventAggregator]; } constructor(container, history, pipelineProvider, events) { super(container, history); // Note the super will call reset internally. this.pipelineProvider = pipelineProvider; this.events = events; } /** * Fully resets the router's internal state. Primarily used internally by the framework when multiple calls to setRoot are made. * Use with caution (actually, avoid using this). Do not use this to simply change your navigation model. */ reset() { super.reset(); this.maxInstructionCount = 10; if (!this._queue) { this._queue = []; } else { this._queue.length = 0; } } /** * Loads the specified URL. * * @param url The URL fragment to load. */ loadUrl(url) { return this ._createNavigationInstruction(url) .then(instruction => this._queueInstruction(instruction)) .catch(error => { logger$4.error(error); restorePreviousLocation(this); }); } /** * Registers a viewPort to be used as a rendering target for activated routes. * * @param viewPort The viewPort. This is typically a <router-view/> element in Aurelia default impl * @param name The name of the viewPort. 'default' if unspecified. */ registerViewPort(viewPort, name) { // having strong typing without changing public API const $viewPort = viewPort; super.registerViewPort($viewPort, name); // beside adding viewport to the registry of this instance // AppRouter also configure routing/history to start routing functionality // There are situation where there are more than 1 <router-view/> element at root view // in that case, still only activate once via the following guard if (!this.isActive) { const viewModel = this._findViewModel($viewPort); if ('configureRouter' in viewModel) { // If there are more than one <router-view/> element at root view // use this flag to guard against configure method being invoked multiple times // this flag is set inside method configure if (!this.isConfigured) { // replace the real resolve with a noop to guarantee that any action in base class Router // won't resolve the configurePromise prematurely const resolveConfiguredPromise = this._resolveConfiguredPromise; this._resolveConfiguredPromise = () => { }; return this .configure(config => Promise .resolve(viewModel.configureRouter(config, this)) // an issue with configure interface. Should be fixed there // todo: fix this via configure interface in router .then(() => config)) .then(() => { this.activate(); resolveConfiguredPromise(); }); } } else { this.activate(); } } // when a viewport is added dynamically to a root view that is already activated // just process the navigation instruction else { this._dequeueInstruction(); } return Promise.resolve(); } /** * Activates the router. This instructs the router to begin listening for history changes and processing instructions. * * @params options The set of options to activate the router with. */ activate(options) { if (this.isActive) { return; } this.isActive = true; // route handler property is responsible for handling url change // the interface of aurelia-history isn't clear on this perspective this.options = Object.assign({ routeHandler: this.loadUrl.bind(this) }, this.options, options); this.history.activate(this.options); this._dequeueInstruction(); } /** * Deactivates the router. */ deactivate() { this.isActive = false; this.history.deactivate(); } /**@internal */ _queueInstruction(instruction) { return new Promise((resolve) => { instruction.resolve = resolve; this._queue.unshift(instruction); this._dequeueInstruction(); }); } /**@internal */ _dequeueInstruction(instructionCount = 0) { return Promise.resolve().then(() => { if (this.isNavigating && !instructionCount) { // ts complains about inconsistent returns without void 0 return void 0; } let instruction = this._queue.shift(); this._queue.length = 0; if (!instruction) { // ts complains about inconsistent returns without void 0 return void 0; } this.isNavigating = true; let navtracker = this.history.getState('NavigationTracker'); let currentNavTracker = this.currentNavigationTracker; if (!navtracker && !currentNavTracker) { this.isNavigatingFirst = true; this.isNavigatingNew = true; } else if (!navtracker) { this.isNavigatingNew = true; } else if (!currentNavTracker) { this.isNavigatingRefresh = true; } else if (currentNavTracker < navtracker) { this.isNavigatingForward = true; } else if (currentNavTracker > navtracker) { this.isNavigatingBack = true; } if (!navtracker) { navtracker = Date.now(); this.history.setState('NavigationTracker', navtracker); } this.currentNavigationTracker = navtracker; instruction.previousInstruction = this.currentInstruction; let maxInstructionCount = this.maxInstructionCount; if (!instructionCount) { this.events.publish("router:navigation:processing" /* Processing */, { instruction }); } else if (instructionCount === maxInstructionCount - 1) { logger$4.error(`${instructionCount + 1} navigation instructions have been attempted without success. Restoring last known good location.`); restorePreviousLocation(this); return this._dequeueInstruction(instructionCount + 1); } else if (instructionCount > maxInstructionCount) { throw new Error('Maximum navigation attempts exceeded. Giving up.'); } let pipeline = this.pipelineProvider.createPipeline(!this.couldDeactivate); return pipeline .run(instruction) .then(result => processResult(instruction, result, instructionCount, this)) .catch(error => { return { output: error instanceof Error ? error : new Error(error) }; }) .then(result => resolveInstruction(instruction, result, !!instructionCount, this)); }); } /**@internal */ _findViewModel(viewPort) { if (this.container.viewModel) { return this.container.viewModel; } if (viewPort.container) { let container = viewPort.container; while (container) { if (container.viewModel) { this.container.viewModel = container.viewModel; return container.viewModel; } container = container.parent; } } return undefined; } } const processResult = (instruction, result, instructionCount, router) => { if (!(result && 'completed' in result && 'output' in result)) { result = result || {}; result.output = new Error(`Expected router pipeline to return a navigation result, but got [${JSON.stringify(result)}] instead.`); } let finalResult = null; let navigationCommandResult = null; if (isNavigationCommand(result.output)) { navigationCommandResult = result.output.navigate(router); } else { finalResult = result; if (!result.completed) { if (result.output instanceof Error) { logger$4.error(result.output.toString()); } restorePreviousLocation(router); } } return Promise.resolve(navigationCommandResult) .then(_ => router._dequeueInstruction(instructionCount + 1)) .then(innerResult => finalResult || innerResult || result); }; const resolveInstruction = (instruction, result, isInnerInstruction, router) => { instruction.resolve(result); let eventAggregator = router.events; let eventArgs = { instruction, result }; if (!isInnerInstruction) { router.isNavigating = false; router.isExplicitNavigation = false; router.isExplicitNavigationBack = false; router.isNavigatingFirst = false; router.isNavigatingNew = false; router.isNavigatingRefresh = false; router.isNavigatingForward = false; router.isNavigatingBack = false; router.couldDeactivate = false; let eventName; if (result.output instanceof Error) { eventName = "router:navigation:error" /* Error */; } else if (!result.completed) { eventName = "router:navigation:canceled" /* Canceled */; } else { let queryString = instruction.queryString ? ('?' + instruction.queryString) : ''; router.history.previousLocation = instruction.fragment + queryString; eventName = "router:navigation:success" /* Success */; } eventAggregator.publish(eventName, eventArgs); eventAggregator.publish("router:navigation:complete" /* Complete */, eventArgs); } else { eventAggregator.publish("router:navigation:child:complete" /* ChildComplete */, eventArgs); } return result; }; const restorePreviousLocation = (router) => { let previousLocation = router.history.previousLocation; if (previousLocation) { router.navigate(previousLocation, { trigger: false, replace: true }); } else if (router.fallbackRoute) { router.navigate(router.fallbackRoute, { trigger: true, replace: true }); } else { logger$4.error('Router navigation failed, and no previous location or fallbackRoute could be restored.'); } }; /** * The status of a Pipeline. */ (function (PipelineStatus) { PipelineStatus["Completed"] = "completed"; PipelineStatus["Canceled"] = "canceled"; PipelineStatus["Rejected"] = "rejected"; PipelineStatus["Running"] = "running"; })(exports.PipelineStatus || (exports.PipelineStatus = {})); /** * A list of known router events used by the Aurelia router * to signal the pipeline has come to a certain state */ // const enum is preserved in tsconfig var RouterEvent; (function (RouterEvent) { RouterEvent["Processing"] = "router:navigation:processing"; RouterEvent["Error"] = "router:navigation:error"; RouterEvent["Canceled"] = "router:navigation:canceled"; RouterEvent["Complete"] = "router:navigation:complete"; RouterEvent["Success"] = "router:navigation:success"; RouterEvent["ChildComplete"] = "router:navigation:child:complete"; })(RouterEvent || (RouterEvent = {})); /** * Available pipeline slot names to insert interceptor into router pipeline */ // const enum is preserved in tsconfig var PipelineSlotName; (function (PipelineSlotName) { /** * Authorization slot. Invoked early in the pipeline, * before `canActivate` hook of incoming route */ PipelineSlotName["Authorize"] = "authorize"; /** * Pre-activation slot. Invoked early in the pipeline, * Invoked timing: * - after Authorization slot * - after canActivate hook on new view model * - before deactivate hook on old view model * - before activate hook on new view model */ PipelineSlotName["PreActivate"] = "preActivate"; /** * Pre-render slot. Invoked later in the pipeline * Invokcation timing: * - after activate hook on new view model * - before commit step on new navigation instruction */ PipelineSlotName["PreRender"] = "preRender"; /** * Post-render slot. Invoked last in the pipeline */ PipelineSlotName["PostRender"] = "postRender"; })(PipelineSlotName || (PipelineSlotName = {})); class EmptyLayoutViewModel { } /** * Implementation of Aurelia Router ViewPort. Responsible for loading route, composing and swapping routes views */ class RouterView { constructor(element, container, viewSlot, router, viewLocator, compositionTransaction, compositionEngine) { this.element = element; this.container = container; this.viewSlot = viewSlot; this.router = router; this.viewLocator = viewLocator; this.compositionTransaction = compositionTransaction; this.compositionEngine = compositionEngine; // add this <router-view/> to router view ports lookup based on name attribute // when this router is the root router-view // also trigger AppRouter registerViewPort extra flow this.router.registerViewPort(this, this.element.getAttribute('name')); // Each <router-view/> process its instruction as a composition transaction // there are differences between intial composition and subsequent compositions // also there are differences between root composition and child <router-view/> composition // mark the first composition transaction with a property initialComposition to distinguish it // when the root <router-view/> gets new instruction for the first time if (!('initialComposition' in compositionTransaction)) { compositionTransaction.initialComposition = true; this.compositionTransactionNotifier = compositionTransaction.enlist(); } } /**@internal */ static inject() { return [DOM.Element, Container, ViewSlot, Router, ViewLocator, CompositionTransaction, CompositionEngine]; } created(owningView) { this.owningView = owningView; } bind(bindingContext, overrideContext) { // router needs to get access to view model of current route parent // doing it in generic way via viewModel property on container this.container.viewModel = bindingContext; this.overrideContext = overrideContext; } /** * Implementation of `aurelia-router` ViewPort interface, responsible for templating related part in routing Pipeline */ process($viewPortInstruction, waitToSwap) { // have strong typings without exposing it in public typings, this is to ensure maximum backward compat const viewPortInstruction = $viewPortInstruction; const component = viewPortInstruction.component; const childContainer = component.childContainer; const viewModel = component.viewModel; const viewModelResource = component.viewModelResource; const metadata = viewModelResource.metadata; const config = component.router.currentInstruction.config; const viewPortConfig = config.viewPorts ? (config.viewPorts[viewPortInstruction.name] || {}) : {}; childContainer.get(RouterViewLocator)._notify(this); // layoutInstruction is our layout viewModel const layoutInstruction = { viewModel: viewPortConfig.layoutViewModel || config.layoutViewModel || this.layoutViewModel, view: viewPortConfig.layoutView || config.layoutView || this.layoutView, model: viewPortConfig.layoutModel || config.layoutModel || this.layoutModel, router: viewPortInstruction.component.router, childContainer: childContainer, viewSlot: this.viewSlot }; // viewport will be a thin wrapper around composition engine // to process instruction/configuration from users // preparing all information related to a composition process // first by getting view strategy of a ViewPortComponent View const viewStrategy = this.viewLocator.getViewStrategy(component.view || viewModel); if (viewStrategy && component.view) { viewStrategy.makeRelativeTo(Origin.get(component.router.container.viewModel.constructor).moduleId); } // using metadata of a custom element view model to load appropriate view-factory instance return metadata .load(childContainer, viewModelResource.value, null, viewStrategy, true) // for custom element, viewFactory typing is always ViewFactory // for custom attribute, it will be HtmlBehaviorResource .then((viewFactory) => { // if this is not the first time that this <router-view/> is composing its instruction // try to capture ownership of the composition transaction // child <router-view/> will not be able to capture, since root <router-view/> typically captures // the ownership token if (!this.compositionTransactionNotifier) { this.compositionTransactionOwnershipToken = this.compositionTransaction.tryCapture(); } if (layoutInstruction.viewModel || layoutInstruction.view) { viewPortInstruction.layoutInstruction = layoutInstruction; } const viewPortComponentBehaviorInstruction = BehaviorInstruction.dynamic(this.element, viewModel, viewFactory); viewPortInstruction.controller = metadata.create(childContainer, viewPortComponentBehaviorInstruction); if (waitToSwap) { return null; } this.swap(viewPortInstruction); }); } swap($viewPortInstruction) { // have strong typings without exposing it in public typings, this is to ensure maximum backward compat const viewPortInstruction = $viewPortInstruction; const viewPortController = viewPortInstruction.controller; const layoutInstruction = viewPortInstruction.layoutInstruction; const previousView = this.view; // Final step of swapping a <router-view/> ViewPortComponent const work = () => { const swapStrategy = SwapStrategies[this.swapOrder] || SwapStrategies.after; const viewSlot = this.viewSlot; swapStrategy(viewSlot, previousView, () => Promise.resolve(viewSlot.add(this.view))).then(() => { this._notify(); }); }; // Ensure all users setups have been completed const ready = (owningView_or_layoutView) => { viewPortController.automate(this.overrideContext, owningView_or_layoutView); const transactionOwnerShipToken = this.compositionTransactionOwnershipToken; // if this router-view is the root <router-view/> of a normal startup via aurelia.setRoot // attemp to take control of the transaction // if ownership can be taken // wait for transaction to complete before swapping if (transactionOwnerShipToken) { return transactionOwnerShipToken .waitForCompositionComplete() .then(() => { this.compositionTransactionOwnershipToken = null; return work(); }); } // otherwise, just swap return work(); }; // If there is layout instruction, new to compose layout before processing ViewPortComponent // layout controller/view/view-model is composed using composition engine APIs if (layoutInstruction) { if (!layoutInstruction.viewModel) { // createController chokes if there's no viewmodel, so create a dummy one // but avoid using a POJO as it creates unwanted metadata in Object constructor layoutInstruction.viewModel = new EmptyLayoutViewModel(); } // using composition engine to create compose layout return this.compositionEngine // first create controller from layoutInstruction // and treat it as CompositionContext // then emulate slot projection with ViewPortComponent view .createController(layoutInstruction) .then((layoutController) => { const layoutView = layoutController.view; ShadowDOM.distributeView(viewPortController.view, layoutController.slots || layoutView.slots); // when there is a layout // view hierarchy is: <router-view/> owner view -> layout view -> ViewPortComponent view layoutController.automate(createOverrideContext(layoutInstruction.viewModel), this.owningView); layoutView.children.push(viewPortController.view); return layoutView || layoutController; }) .then((newView) => { this.view = newView; return ready(newView); }); } // if there is no layout, then get ViewPortComponent view ready as view property // and process controller/swapping // when there is no layout // view hierarchy is: <router-view/> owner view -> ViewPortComponent view this.view = viewPortController.view; return ready(this.owningView); } /** * Notify composition transaction that this router has finished processing * Happens when this <router-view/> is the root router-view * @internal */ _notify() { const notifier = this.compositionTransactionNotifier; if (notifier) { notifier.done(); this.compositionTransactionNotifier = null; } } } /** * @internal Actively avoid using decorator to reduce the amount of code generated * * There is no view to compose by default in a router view * This custom element is responsible for composing its own view, based on current config */ RouterView.$view = null; /** * @internal Actively avoid using decorator to reduce the amount of code generated */ RouterView.$resource = { name: 'router-view', bindables: ['swapOrder', 'layoutView', 'layoutViewModel', 'layoutModel', 'inherit-binding-context'] }; /** * Locator which finds the nearest RouterView, relative to the current dependency injection container. */ class RouterViewLocator { /** * Creates an instance of the RouterViewLocator class. */ constructor() { this.promise = new Promise((resolve) => this.resolve = resolve); } /** * Finds the nearest RouterView instance. * @returns A promise that will be resolved with the located RouterView instance. */ findNearest() { return this.promise; } /**@internal */ _notify(routerView) { this.resolve(routerView); } } /**@internal exported for unit testing */ class EmptyClass { } inlineView('<template></template>')(EmptyClass); /** * Default implementation of `RouteLoader` used for loading component based on a route config */ class TemplatingRouteLoader extends RouteLoader { constructor(compositionEngine) { super(); this.compositionEngine = compositionEngine; } /** * Resolve a view model from a RouteConfig * Throws when there is neither "moduleId" nor "viewModel" property * @internal */ resolveViewModel(router, config) { return new Promise((resolve, reject) => { let viewModel; if ('moduleId' in config) { let moduleId = config.moduleId; if (moduleId === null) { viewModel = EmptyClass; } else { // this requires container of router has passes a certain point // where a view model has been setup on the container // it will fail in enhance scenario because no viewport has been registered moduleId = relativeToFile(moduleId, Origin.get(router.container.viewModel.constructor).moduleId); if (/\.html/i.test(moduleId)) { viewModel = createDynamicClass(moduleId); } else { viewModel = moduleId; } } return resolve(viewModel); } // todo: add if ('viewModel' in config) to support static view model resolution reject(new Error('Invalid route config. No "moduleId" found.')); }); } /** * Create child container based on a router container * Also ensures that child router are properly constructed in the newly created child container * @internal */ createChildContainer(router) { const childContainer = router.container.createChild(); childContainer.registerSingleton(RouterViewLocator); childContainer.getChildRouter = function () { let childRouter; childContainer.registerHandler(Router, () => childRouter || (childRouter = router.createChild(childContainer))); return childContainer.get(Router); }; return childContainer; } /** * Load corresponding component of a route config of a navigation instruction */ loadRoute(router, config, _navInstruction) { return this .resolveViewModel(router, config) .then(viewModel => this.compositionEngine.ensureViewModel({ viewModel: viewModel, childContainer: this.createChildContainer(router), view: config.view || config.viewStrategy, router: router })); } } /**@internal */ TemplatingRouteLoader.inject = [CompositionEngine]; /**@internal exported for unit testing */ function createDynamicClass(moduleId) { const name = /([^\/^\?]+)\.html/i.exec(moduleId)[1]; class DynamicClass { bind(bindingContext) { this.$parent = bindingContext; } } customElement(name)(DynamicClass); useView(moduleId)(DynamicClass); return DynamicClass; } const logger$5 = getLogger('route-href'); /** * Helper custom attribute to help associate an element with a route by name */ class RouteHref { constructor(router, element) { this.router = router; this.element = element; this.attribute = 'href'; } /*@internal */ static inject() { return [Router, DOM.Element]; } bind() { this.isActive = true; this.processChange(); } unbind() { this.isActive = false; } attributeChanged(value, previous) { if (previous) { this.element.removeAttribute(previous); } return this.processChange(); } processChange() { return this.router .ensureConfigured() .then(() => { if (!this.isActive) { // returning null to avoid Bluebird warning return null; } const element = this.element; const href = this.router.generate(this.route, this.params); if (element.au.controller) { element.au.controller.viewModel[this.attribute] = href; } else { element.setAttribute(this.attribute, href); } // returning null to avoid Bluebird warning return null; }) .catch((reason) => { logger$5.error(reason); }); } } /** * @internal Actively avoid using decorator to reduce the amount of code generated */ RouteHref.$resource = { type: 'attribute', name: 'route-href', bindables: [ { name: 'route', changeHandler: 'processChange', primaryProperty: true }, { name: 'params', changeHandler: 'processChange' }, 'attribute' ] // type definition of Aurelia templating is wrong }; function configure$5(config) { config .singleton(RouteLoader, TemplatingRouteLoader) .singleton(Router, AppRouter) .globalResources(RouterView, RouteHref); config.container.registerAlias(Router, AppRouter); } let ConsoleAppender = class ConsoleAppender { debug(logger, ...rest) { console.debug(`DEBUG [${logger.id}]`, ...rest); } info(logger, ...rest) { console.info(`INFO [${logger.id}]`, ...rest); } warn(logger, ...rest) { console.warn(`WARN [${logger.id}]`, ...rest); } error(logger, ...rest) { console.error(`ERROR [${logger.id}]`, ...rest); } }; /** * Bootstrap a new Aurelia instance and start an application * @param {QuickStartOptions} options * @returns {Aurelia} the running Aurelia instance */ const createAndStart = (options = {}) => { const aurelia = new Aurelia(); const use = aurelia.use; use.standardConfiguration(); if (options.debug) { use.developmentLogging(); } if (Array.isArray(options.plugins)) { options.plugins.forEach((plgCfg) => { if (Array.isArray(plgCfg)) { use.plugin(plgCfg[0], plgCfg[1]); } else { use.plugin(plgCfg); } }); } if (Array.isArray(options.resources)) { use.globalResources(options.resources); } return aurelia.start(); }; /** * Bootstrap a new Aurelia instance and start an application * @param {QuickStartOptions} options * @returns {Aurelia} the running Aurelia instance */ function start(options = {}) { return createAndStart(options) .then(aurelia => aurelia.setRoot(options.root || 'app.js', options.host || document.body)); } /** * Bootstrap a new Aurelia instance and start an application by enhancing a DOM tree * @param {QuickEnhanceOptions} options Configuration for enhancing a DOM tree * @returns {View} the enhanced View by selected options */ function enhance(options = {}) { return createAndStart(options) .then(aurelia => { if (typeof options.root === 'function') { options.root = aurelia.container.get(options.root); } return aurelia.enhance(options.root || {}, options.host || document.body); }); } /** @typed ConfigureFn * @param {FrameworkConfiguration} frameWorkConfig * @param {any} plugigConfig */ /** @typedef QuickStartOptions * @property {string | Function} [root] application root. Either string or a class, which will be instantiated with DI * @property {string | Element} [host] application host, element or a string, which will be used to query the element * @property {Array<string | Function>} [resources] global resources for the application * @property {Array<string | {(fwCfg: FrameworkConfiguration) => any} | [(fwCfg: FrameworkConfiguration, cfg: {}) => any, {}]>} [plugins] * @property {boolean} [debug] true to use development console logging */ /** @typedef QuickEnhanceOptions * @property {{} | Function} [root] binding context for enhancement, can be either object or a class, which will be instantiated with DI * @property {string | Element} [host] host node of to be enhanced tree * @property {Array<string | Function>} [resources] global resources for the application * @property {Array<string | {(fwCfg: FrameworkConfiguration) => any} | [(fwCfg: FrameworkConfiguration, cfg: {}) => any, {}]>} [plugins] * @property {boolean} [debug] true to use development console logging */ initialize(); // Using static convention to avoid having to fetch / load module dynamically (frameworkCfgProto => { frameworkCfgProto.developmentLogging = function() { LogManager.addAppender(new ConsoleAppender()); LogManager.setLevel(LogManager.logLevel.debug); return this; }; frameworkCfgProto.defaultBindingLanguage = function() { return this.plugin(configure); }; frameworkCfgProto.defaultResources = function() { return this.plugin(configure$2); }; frameworkCfgProto.eventAggregator = function() { return this.plugin(configure$3); }; frameworkCfgProto.history = function() { return this.plugin(configure$4); }; frameworkCfgProto.router = function() { return this.plugin(configure$5); }; })(FrameworkConfiguration.prototype); exports.AbstractRepeater = AbstractRepeater; exports.AccessKeyed = AccessKeyed; exports.AccessMember = AccessMember; exports.AccessScope = AccessScope; exports.AccessThis = AccessThis; exports.ActivateNextStep = ActivateNextStep; exports.AggregateError = AggregateError; exports.All = All; exports.Animator = Animator; exports.AppRouter = AppRouter; exports.ArrayRepeatStrategy = ArrayRepeatStrategy; exports.Assign = Assign; exports.AttrBindingBehavior = AttrBindingBehavior; exports.Aurelia = Aurelia; exports.BehaviorInstruction = BehaviorInstruction; exports.BehaviorPropertyObserver = BehaviorPropertyObserver; exports.Binary = Binary; exports.BindableProperty = BindableProperty; exports.Binding = Binding; exports.BindingBehavior = BindingBehavior; exports.BindingBehaviorResource = BindingBehaviorResource; exports.BindingEngine = BindingEngine; exports.BindingExpression = BindingExpression; exports.BindingLanguage = BindingLanguage; exports.BindingSignaler = BindingSignaler; exports.BoundViewFactory = BoundViewFactory; exports.BuildNavigationPlanStep = BuildNavigationPlanStep; exports.Call = Call; exports.CallExpression = CallExpression; exports.CallFunction = CallFunction; exports.CallMember = CallMember; exports.CallScope = CallScope; exports.CanActivateNextStep = CanActivateNextStep; exports.CanDeactivatePreviousStep = CanDeactivatePreviousStep; exports.CheckedObserver = CheckedObserver; exports.ClassObserver = ClassObserver; exports.CollectionLengthObserver = CollectionLengthObserver; exports.CommitChangesStep = CommitChangesStep; exports.Compose = Compose; exports.CompositionEngine = CompositionEngine; exports.CompositionTransaction = CompositionTransaction; exports.CompositionTransactionNotifier = CompositionTransactionNotifier; exports.CompositionTransactionOwnershipToken = CompositionTransactionOwnershipToken; exports.ComputedExpression = ComputedExpression; exports.Conditional = Conditional; exports.Container = Container; exports.Controller = Controller; exports.ConventionalViewStrategy = ConventionalViewStrategy; exports.DOM = DOM; exports.DataAttributeObserver = DataAttributeObserver; exports.DeactivatePreviousStep = DeactivatePreviousStep; exports.DebounceBindingBehavior = DebounceBindingBehavior; exports.DirtyCheckProperty = DirtyCheckProperty; exports.DirtyChecker = DirtyChecker; exports.ElementConfigResource = ElementConfigResource; exports.ElementEvents = ElementEvents; exports.Else = Else; exports.EventAggregator = EventAggregator; exports.EventManager = EventManager; exports.EventSubscriber = EventSubscriber; exports.Expression = Expression; exports.ExpressionCloner = ExpressionCloner; exports.ExpressionObserver = ExpressionObserver; exports.FEATURE = FEATURE; exports.Factory = Factory; exports.FactoryInvoker = FactoryInvoker; exports.Focus = Focus; exports.FrameworkConfiguration = FrameworkConfiguration; exports.FromViewBindingBehavior = FromViewBindingBehavior; exports.HTMLSanitizer = HTMLSanitizer; exports.Hide = Hide; exports.HtmlBehaviorResource = HtmlBehaviorResource; exports.If = If; exports.InlineViewStrategy = InlineViewStrategy; exports.InvocationHandler = InvocationHandler; exports.Lazy = Lazy; exports.Listener = Listener; exports.ListenerExpression = ListenerExpression; exports.LiteralArray = LiteralArray; exports.LiteralObject = LiteralObject; exports.LiteralPrimitive = LiteralPrimitive; exports.LiteralString = LiteralString; exports.LiteralTemplate = LiteralTemplate; exports.LoadRouteStep = LoadRouteStep; exports.Loader = Loader; exports.LogManager = LogManager; exports.MapRepeatStrategy = MapRepeatStrategy; exports.ModifyCollectionObserver = ModifyCollectionObserver; exports.ModuleAnalyzer = ModuleAnalyzer; exports.NameExpression = NameExpression; exports.NavModel = NavModel; exports.NavigationInstruction = NavigationInstruction; exports.NewInstance = NewInstance; exports.NoViewStrategy = NoViewStrategy; exports.NullRepeatStrategy = NullRepeatStrategy; exports.NumberRepeatStrategy = NumberRepeatStrategy; exports.ObjectObservationAdapter = ObjectObservationAdapter; exports.ObserverLocator = ObserverLocator; exports.OneTimeBindingBehavior = OneTimeBindingBehavior; exports.OneWayBindingBehavior = OneWayBindingBehavior; exports.Optional = Optional; exports.Origin = Origin; exports.PLATFORM = PLATFORM; exports.Parent = Parent; exports.Parser = Parser; exports.ParserImplementation = ParserImplementation; exports.PassThroughSlot = PassThroughSlot; exports.Pipeline = Pipeline; exports.PipelineProvider = PipelineProvider; exports.PrimitiveObserver = PrimitiveObserver; exports.Redirect = Redirect; exports.RedirectToRoute = RedirectToRoute; exports.RelativeViewStrategy = RelativeViewStrategy; exports.Repeat = Repeat; exports.RepeatStrategyLocator = RepeatStrategyLocator; exports.Replaceable = Replaceable; exports.ResourceDescription = ResourceDescription; exports.ResourceLoadContext = ResourceLoadContext; exports.ResourceModule = ResourceModule; exports.RouteLoader = RouteLoader; exports.Router = Router; exports.RouterConfiguration = RouterConfiguration; exports.SVGAnalyzer = SVGAnalyzer; exports.SanitizeHTMLValueConverter = SanitizeHTMLValueConverter; exports.SelectValueObserver = SelectValueObserver; exports.SelfBindingBehavior = SelfBindingBehavior; exports.SetRepeatStrategy = SetRepeatStrategy; exports.SetterObserver = SetterObserver; exports.ShadowDOM = ShadowDOM; exports.ShadowSlot = ShadowSlot; exports.Show = Show; exports.SignalBindingBehavior = SignalBindingBehavior; exports.SingletonRegistration = SingletonRegistration; exports.SlotCustomAttribute = SlotCustomAttribute; exports.StaticViewStrategy = StaticViewStrategy; exports.StrategyResolver = StrategyResolver; exports.StyleObserver = StyleObserver; exports.SwapStrategies = SwapStrategies; exports.TargetInstruction = TargetInstruction; exports.TaskQueue = TaskQueue; exports.TemplateDependency = TemplateDependency; exports.TemplateRegistryEntry = TemplateRegistryEntry; exports.TemplateRegistryViewStrategy = TemplateRegistryViewStrategy; exports.TemplatingEngine = TemplatingEngine; exports.ThrottleBindingBehavior = ThrottleBindingBehavior; exports.ToViewBindingBehavior = ToViewBindingBehavior; exports.TransientRegistration = TransientRegistration; exports.TwoWayBindingBehavior = TwoWayBindingBehavior; exports.Unary = Unary; exports.UpdateTriggerBindingBehavior = UpdateTriggerBindingBehavior; exports.ValueAttributeObserver = ValueAttributeObserver; exports.ValueConverter = ValueConverter; exports.ValueConverterResource = ValueConverterResource; exports.View = View; exports.ViewCompileInstruction = ViewCompileInstruction; exports.ViewCompiler = ViewCompiler; exports.ViewEngine = ViewEngine; exports.ViewEngineHooksResource = ViewEngineHooksResource; exports.ViewFactory = ViewFactory; exports.ViewLocator = ViewLocator; exports.ViewResources = ViewResources; exports.ViewSlot = ViewSlot; exports.With = With; exports.XLinkAttributeObserver = XLinkAttributeObserver; exports._emptyParameters = _emptyParameters; exports._hyphenate = _hyphenate; exports._isAllWhitespace = _isAllWhitespace; exports.activationStrategy = activationStrategy; exports.all = all; exports.animationEvent = animationEvent; exports.autoinject = autoinject; exports.behavior = behavior; exports.bindable = bindable; exports.bindingBehavior = bindingBehavior; exports.bindingMode = bindingMode; exports.buildQueryString = buildQueryString; exports.calcSplices = calcSplices; exports.camelCase = camelCase; exports.child = child; exports.children = children; exports.cloneExpression = cloneExpression; exports.computedFrom = computedFrom; exports.connectBindingToSignal = connectBindingToSignal; exports.connectable = connectable; exports.containerless = containerless; exports.createComputedObserver = createComputedObserver; exports.createFullOverrideContext = createFullOverrideContext; exports.createOverrideContext = createOverrideContext; exports.createScopeForTest = createScopeForTest; exports.customAttribute = customAttribute; exports.customElement = customElement; exports.dataAttributeAccessor = dataAttributeAccessor; exports.declarePropertyDependencies = declarePropertyDependencies; exports.decorators = decorators; exports.delegationStrategy = delegationStrategy; exports.deprecated = deprecated; exports.disableConnectQueue = disableConnectQueue; exports.dynamicOptions = dynamicOptions; exports.elementConfig = elementConfig; exports.elements = elements; exports.enableConnectQueue = enableConnectQueue; exports.enhance = enhance; exports.enqueueBindingConnect = enqueueBindingConnect; exports.factory = factory; exports.getArrayObserver = getArrayObserver; exports.getChangeRecords = getChangeRecords; exports.getConnectQueueSize = getConnectQueueSize; exports.getContextFor = getContextFor; exports.getDecoratorDependencies = getDecoratorDependencies; exports.getItemsSourceExpression = getItemsSourceExpression; exports.getMapObserver = getMapObserver; exports.getSetObserver = getSetObserver; exports.hasDeclaredDependencies = hasDeclaredDependencies; exports.includeEventsIn = includeEventsIn; exports.initializePAL = initializePAL; exports.inject = inject; exports.inlineView = inlineView; exports.invokeAsFactory = invokeAsFactory; exports.invoker = invoker; exports.isNavigationCommand = isNavigationCommand; exports.isOneTime = isOneTime; exports.join = join; exports.lazy = lazy; exports.mergeSplice = mergeSplice; exports.metadata = metadata; exports.mixin = mixin; exports.newInstance = newInstance; exports.noView = noView; exports.observable = observable; exports.optional = optional; exports.parent = parent; exports.parseQueryString = parseQueryString; exports.presentationAttributes = presentationAttributes; exports.presentationElements = presentationElements; exports.processAttributes = processAttributes; exports.processContent = processContent; exports.projectArraySplices = projectArraySplices; exports.propertyAccessor = propertyAccessor; exports.protocol = protocol; exports.registration = registration; exports.relativeToFile = relativeToFile; exports.reset = reset; exports.resolver = resolver; exports.resource = resource; exports.setConnectQueueThreshold = setConnectQueueThreshold; exports.signalBindings = signalBindings; exports.singleton = singleton; exports.sourceContext = sourceContext; exports.start = start; exports.subscriberCollection = subscriberCollection; exports.targetContext = targetContext; exports.templateController = templateController; exports.transient = transient; exports.unwrapExpression = unwrapExpression; exports.updateOneTimeBinding = updateOneTimeBinding; exports.updateOverrideContext = updateOverrideContext; exports.useShadowDOM = useShadowDOM; exports.useView = useView; exports.useViewStrategy = useViewStrategy; exports.validateBehaviorName = validateBehaviorName; exports.valueConverter = valueConverter; exports.view = view; exports.viewEngineHooks = viewEngineHooks; exports.viewResources = viewResources; exports.viewStrategy = viewStrategy; exports.viewsRequireLifecycle = viewsRequireLifecycle; Object.defineProperty(exports, '__esModule', { value: true }); }));
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2019 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ /** * The Matter Physics Drag Start Event. * * This event is dispatched by a Matter Physics World instance when a Pointer Constraint * starts dragging a body. * * Listen to it from a Scene using: `this.matter.world.on('dragstart', listener)`. * * @event Phaser.Physics.Matter.Events#DRAG_START * @since 3.16.2 * * @param {MatterJS.Body} body - The Body that has started being dragged. This is a Matter Body, not a Phaser Game Object. * @param {MatterJS.Body} part - The part of the body that was clicked on. * @param {Phaser.Physics.Matter.PointerConstraint} constraint - The Pointer Constraint that is dragging the body. */ module.exports = 'dragstart';
'use strict'; var Mongoose = require('mongoose'); /** * Each connection object represents a user connected through a unique socket. * Each connection object composed of {userId + socketId}. Both of them together are unique. * */ var RoomSchema = new Mongoose.Schema({ title: { type: String, required: true }, connections: { type: [{ userId: String, socketId: String }]} }); var roomModel = Mongoose.model('room', RoomSchema); module.exports = roomModel;