code
stringlengths
2
1.05M
'use strict'; var _ = require('lodash'); var webpack = require('webpack'); var mergeWebpackConfig = function (config) { // Load webpackConfig only when using `grunt:webpack` // load of grunt tasks is faster var webpackConfig = require('./webpack.config'); return _.merge({}, webpackConfig, config, function (a, b) { if (_.isArray(a)) { return a.concat(b); } }); }; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), sass: { min: { files: { 'dist/react-datepicker.css': 'src/stylesheets/datepicker.scss' }, options: { sourcemap: 'none', style: 'expanded' } }, unmin: { files: { 'dist/react-datepicker.min.css': 'src/stylesheets/datepicker.scss' }, options: { sourcemap: 'none', style: 'compressed' } } }, watch: { jshint: { files: ['src/**/*.js', 'src/**/*.jsx'], tasks: ['jshint'] }, jest: { files: ['src/**/*.jsx', 'src/**/*.js', 'test/**/*.js'], tasks: ['jest'] }, css: { files: '**/*.scss', tasks: ['sass'] }, webpack: { files: ['src/**/*.js', 'src/**/*.jsx'], tasks: ['webpack'] } }, scsslint: { files: 'src/stylesheets/*.scss', options: { config: '.scss-lint.yml', colorizeOutput: true } }, jshint: { all: ['src/**/*.jsx', 'src/**/*.js'], options: { eqnull: true } }, webpack: { example: { entry: './example/boot', output: { filename: 'example.js', library: 'ExampleApp', path: './example/' }, resolve: { extensions: ['', '.js', '.jsx'] }, module: { loaders: [ {test: /\.js/, loaders: ['babel-loader'], exclude: /node_modules/} ] }, node: {Buffer: false}, plugins: [ new webpack.optimize.DedupePlugin(), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) }) ] }, unmin: mergeWebpackConfig({ output: { filename: 'react-datepicker.js' } }), min: mergeWebpackConfig({ output: { filename: 'react-datepicker.min.js' }, plugins: [ new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }) ] }) } }); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-scss-lint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-jsxhint'); grunt.loadNpmTasks('grunt-webpack'); grunt.registerTask('default', ['watch', 'scsslint']); grunt.registerTask('travis', ['jshint', 'jest', 'scsslint']); grunt.registerTask('build', ['jshint', 'scsslint', 'webpack', 'sass']); grunt.registerTask('jest', require('./grunt/tasks/jest')); };
var ArrayProto = Array.prototype; var ObjProto = Object.prototype; var escapeMap = { '&': '&amp;', '"': '&quot;', "'": '&#39;', "<": '&lt;', ">": '&gt;' }; var escapeRegex = /[&"'<>]/g; var lookupEscape = function(ch) { return escapeMap[ch]; }; var exports = module.exports = {}; exports.withPrettyErrors = function(path, withInternals, func) { try { return func(); } catch (e) { if (!e.Update) { // not one of ours, cast it e = new exports.TemplateError(e); } e.Update(path); // Unless they marked the dev flag, show them a trace from here if (!withInternals) { var old = e; e = new Error(old.message); e.name = old.name; } throw e; } }; exports.TemplateError = function(message, lineno, colno) { var err = this; if (message instanceof Error) { // for casting regular js errors err = message; message = message.name + ": " + message.message; } else { if(Error.captureStackTrace) { Error.captureStackTrace(err); } } err.name = 'Template render error'; err.message = message; err.lineno = lineno; err.colno = colno; err.firstUpdate = true; err.Update = function(path) { var message = "(" + (path || "unknown path") + ")"; // only show lineno + colno next to path of template // where error occurred if (this.firstUpdate) { if(this.lineno && this.colno) { message += ' [Line ' + this.lineno + ', Column ' + this.colno + ']'; } else if(this.lineno) { message += ' [Line ' + this.lineno + ']'; } } message += '\n '; if (this.firstUpdate) { message += ' '; } this.message = message + (this.message || ''); this.firstUpdate = false; return this; }; return err; }; exports.TemplateError.prototype = Error.prototype; exports.escape = function(val) { return val.replace(escapeRegex, lookupEscape); }; exports.isFunction = function(obj) { return ObjProto.toString.call(obj) == '[object Function]'; }; exports.isArray = Array.isArray || function(obj) { return ObjProto.toString.call(obj) == '[object Array]'; }; exports.isString = function(obj) { return ObjProto.toString.call(obj) == '[object String]'; }; exports.isObject = function(obj) { return ObjProto.toString.call(obj) == '[object Object]'; }; exports.groupBy = function(obj, val) { var result = {}; var iterator = exports.isFunction(val) ? val : function(obj) { return obj[val]; }; for(var i=0; i<obj.length; i++) { var value = obj[i]; var key = iterator(value, i); (result[key] || (result[key] = [])).push(value); } return result; }; exports.toArray = function(obj) { return Array.prototype.slice.call(obj); }; exports.without = function(array) { var result = []; if (!array) { return result; } var index = -1, length = array.length, contains = exports.toArray(arguments).slice(1); while(++index < length) { if(exports.indexOf(contains, array[index]) === -1) { result.push(array[index]); } } return result; }; exports.extend = function(obj, obj2) { for(var k in obj2) { obj[k] = obj2[k]; } return obj; }; exports.repeat = function(char_, n) { var str = ''; for(var i=0; i<n; i++) { str += char_; } return str; }; exports.each = function(obj, func, context) { if(obj == null) { return; } if(ArrayProto.each && obj.each == ArrayProto.each) { obj.forEach(func, context); } else if(obj.length === +obj.length) { for(var i=0, l=obj.length; i<l; i++) { func.call(context, obj[i], i, obj); } } }; exports.map = function(obj, func) { var results = []; if(obj == null) { return results; } if(ArrayProto.map && obj.map === ArrayProto.map) { return obj.map(func); } for(var i=0; i<obj.length; i++) { results[results.length] = func(obj[i], i); } if(obj.length === +obj.length) { results.length = obj.length; } return results; }; exports.asyncIter = function(arr, iter, cb) { var i = -1; function next() { i++; if(i < arr.length) { iter(arr[i], i, next, cb); } else { cb(); } } next(); }; exports.asyncFor = function(obj, iter, cb) { var keys = exports.keys(obj); var len = keys.length; var i = -1; function next() { i++; var k = keys[i]; if(i < len) { iter(k, obj[k], i, len, next); } else { cb(); } } next(); }; // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Polyfill exports.indexOf = Array.prototype.indexOf ? function (arr, searchElement, fromIndex) { return Array.prototype.indexOf.call(arr, searchElement, fromIndex); } : function (arr, searchElement, fromIndex) { var length = this.length >>> 0; // Hack to convert object.length to a UInt32 fromIndex = +fromIndex || 0; if(Math.abs(fromIndex) === Infinity) { fromIndex = 0; } if(fromIndex < 0) { fromIndex += length; if (fromIndex < 0) { fromIndex = 0; } } for(;fromIndex < length; fromIndex++) { if (arr[fromIndex] === searchElement) { return fromIndex; } } return -1; }; if(!Array.prototype.map) { Array.prototype.map = function() { throw new Error("map is unimplemented for this js engine"); }; } exports.keys = function(obj) { if(Object.prototype.keys) { return obj.keys(); } else { var keys = []; for(var k in obj) { if(obj.hasOwnProperty(k)) { keys.push(k); } } return keys; } }
$.widget("metro.slider", { version: "3.0.0", options: { position: 0, accuracy: 0, color: 'default', completeColor: 'default', markerColor: 'default', colors: false, showHint: false, permanentHint: false, hintPosition: 'top', vertical: false, min: 0, max: 100, animate: true, minValue: 0, maxValue: 100, currValue: 0, returnType: 'value', target: false, onChange: function(value, slider){}, _slider : { vertical: false, offset: 0, length: 0, marker: 0, ppp: 0, start: 0, stop: 0 } }, _create: function(){ var that = this, element = this.element; var o = this.options, s = o._slider; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = $.parseJSON(value); } catch (e) { o[key] = value; } } }); o.accuracy = o.accuracy < 0 ? 0 : o.accuracy; o.min = o.min < 0 ? 0 : o.min; o.min = o.min > o.max ? o.max : o.min; o.max = o.max > 100 ? 100 : o.max; o.max = o.max < o.min ? o.min : o.max; o.position = this._correctValue(element.data('position') > o.min ? (element.data('position') > o.max ? o.max : element.data('position')) : o.min); o.colors = o.colors ? o.colors.split(",") : false; s.vertical = o.vertical; if (o.vertical && !element.hasClass('vertical')) { element.addClass('vertical'); } if (o.permanentHint && !element.hasClass('permanent-hint')) { element.addClass('permanent-hint'); } if (!o.vertical && o.hintPosition === 'bottom') { element.addClass('hint-bottom'); } if (o.vertical && o.hintPosition === 'left') { element.addClass('hint-left'); } this._createSlider(); this._initPoints(); this._placeMarker(o.position); var event_down = isTouchDevice() ? 'touchstart' : 'mousedown'; element.children('.marker').on(event_down, function (e) { e.preventDefault(); that._startMoveMarker(e); }); element.on(event_down, function (e) { e.preventDefault(); that._startMoveMarker(e); }); element.data('slider', this); }, _startMoveMarker: function(e){ var element = this.element, o = this.options, that = this, hint = element.children('.slider-hint'); var returnedValue; var event_move = isTouchDevice() ? 'touchmove' : 'mousemove'; var event_up = isTouchDevice() ? 'touchend' : 'mouseup mouseleave'; $(element).on(event_move, function (event) { that._movingMarker(event); if (!element.hasClass('permanent-hint')) { hint.css('display', 'block'); } }); $(element).on(event_up, function () { $(element).off('mousemove'); $(element).off('mouseup'); element.data('value', o.position); element.trigger('changed', o.position); returnedValue = o.returnType === 'value' ? that._valueToRealValue(o.position) : o.position; if (!element.hasClass('permanent-hint')) { hint.css('display', 'none'); } }); this._initPoints(); this._movingMarker(e); }, _movingMarker: function (ev) { var element = this.element, o = this.options; var cursorPos, percents, valuePix, vertical = o._slider.vertical, sliderOffset = o._slider.offset, sliderStart = o._slider.start, sliderEnd = o._slider.stop, sliderLength = o._slider.length, markerSize = o._slider.marker; var event = !isTouchDevice() ? ev.originalEvent : ev.originalEvent.touches[0]; //console.log(event); if (vertical) { cursorPos = event.pageY - sliderOffset; } else { cursorPos = event.pageX - sliderOffset; } if (cursorPos < sliderStart) { cursorPos = sliderStart; } else if (cursorPos > sliderEnd) { cursorPos = sliderEnd; } if (vertical) { valuePix = sliderLength - cursorPos - markerSize / 2; } else { valuePix = cursorPos - markerSize / 2; } percents = this._pixToPerc(valuePix); this._placeMarker(percents); o.currValue = this._valueToRealValue(percents); o.position = percents; var returnedValue = o.returnType === 'value' ? this._valueToRealValue(o.position) : o.position; if (o.target) { $(o.target).val(returnedValue); } if (typeof o.onChange === 'function') { o.onChange(returnedValue, element); } else { if (typeof window[o.onChange] === 'function') { window[o.onChange](returnedValue, element); } else { var result = eval("(function(){"+o.onChange+"})"); result.call(returnedValue, element); } } }, _placeMarker: function (value) { var size, size2, o = this.options, colorParts, colorIndex = 0, colorDelta, element = this.element, marker = this.element.children('.marker'), complete = this.element.children('.complete'), hint = this.element.children('.slider-hint'), hintValue, oldPos = this._percToPix(o.position); colorParts = o.colors.length; colorDelta = o._slider.length / colorParts; if (o._slider.vertical) { var oldSize = this._percToPix(o.position) + o._slider.marker, oldSize2 = o._slider.length - oldSize; size = this._percToPix(value) + o._slider.marker; size2 = o._slider.length - size; this._animate(marker.css('top', oldSize2),{top: size2}); this._animate(complete.css('height', oldSize),{height: size}); if (colorParts) { colorIndex = Math.round(size / colorDelta)-1; complete.css('background-color', o.colors[colorIndex<0?0:colorIndex]); } if (o.showHint) { hintValue = this._valueToRealValue(value); hint.html(hintValue).css('top', size2 - hint.height()/2 + (element.hasClass('large') ? 8 : 0)); } } else { size = this._percToPix(value); this._animate(marker.css('left', oldPos),{left: size}); this._animate(complete.css('width', oldPos),{width: size}); if (colorParts) { colorIndex = Math.round(size / colorDelta)-1; complete.css('background-color', o.colors[colorIndex<0?0:colorIndex]); } if (o.showHint) { hintValue = this._valueToRealValue(value); hint.html(hintValue).css({left: size - hint.width() / 2 + (element.hasClass('large') ? 6 : 0)}); } } }, _valueToRealValue: function(value){ var o = this.options; var real_value; var percent_value = (o.maxValue - o.minValue) / 100; real_value = value * percent_value + o.minValue; return Math.round(real_value); }, _animate: function (obj, val) { var o = this.options; if(o.animate) { obj.stop(true).animate(val); } else { obj.css(val); } }, _pixToPerc: function (valuePix) { var valuePerc; valuePerc = valuePix * this.options._slider.ppp; return Math.round(this._correctValue(valuePerc)); }, _percToPix: function (value) { if (this.options._slider.ppp === 0) { return 0; } return Math.round(value / this.options._slider.ppp); }, _correctValue: function (value) { var o = this.options; var accuracy = o.accuracy; var max = o.max; var min = o.min; if (accuracy === 0) { return value; } if (value === max) { return max; } if (value === min) { return min; } value = Math.floor(value / accuracy) * accuracy + Math.round(value % accuracy / accuracy) * accuracy; if (value > max) { return max; } if (value < min) { return min; } return value; }, _initPoints: function(){ var o = this.options, s = o._slider, element = this.element; if (s.vertical) { s.offset = element.offset().top; s.length = element.height(); s.marker = element.children('.marker').height(); } else { s.offset = element.offset().left; s.length = element.width(); s.marker = element.children('.marker').width(); } s.ppp = o.max / (s.length - s.marker); s.start = s.marker / 2; s.stop = s.length - s.marker / 2; }, _createSlider: function(){ var element = this.element, o = this.options, complete, marker, hint; element.html(''); complete = $("<div/>").addClass("complete").appendTo(element); marker = $("<a/>").addClass("marker").appendTo(element); if (o.showHint) { hint = $("<span/>").addClass("slider-hint").appendTo(element); } if (o.color !== 'default') { if (o.color.isColor()) { element.css('background-color', o.color); } else { element.addClass(o.color); } } if (o.completeColor !== 'default') { if (o.completeColor.isColor()) { complete.css('background-color', o.completeColor); } else { complete.addClass(o.completeColor); } } if (o.markerColor !== 'default') { if (o.markerColor.isColor()) { marker.css('background-color', o.markerColor); } else { marker.addClass(o.markerColor); } } }, value: function (value) { var element = this.element, o = this.options, returnedValue; if (typeof value !== 'undefined') { value = value > o.max ? o.max : value; value = value < o.min ? o.min : value; this._placeMarker(parseInt(value)); o.position = parseInt(value); returnedValue = o.returnType === 'value' ? this._valueToRealValue(o.position) : o.position; if (typeof o.onChange === 'function') { o.onChange(returnedValue, element); } else { if (typeof window[o.onChange] === 'function') { window[o.onChange](returnedValue, element); } else { var result = eval("(function(){"+o.onChange+"})"); result.call(returnedValue, element); } } return this; } else { returnedValue = o.returnType === 'value' ? this._valueToRealValue(o.position) : o.position; return returnedValue; } }, _destroy: function(){}, _setOption: function(key, value){ this._super('_setOption', key, value); } });
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import ReactDOM from 'react-dom'; import Col from '../src/Col'; describe('Col', () => { it('Should set Offset of zero', () => { let instance = ReactTestUtils.renderIntoDocument( <Col xsOffset={0} smOffset={0} mdOffset={0} lgOffset={0} /> ); let instanceClassName = ReactDOM.findDOMNode(instance).className; assert.ok(instanceClassName.match(/\bcol-xs-offset-0\b/)); assert.ok(instanceClassName.match(/\bcol-sm-offset-0\b/)); assert.ok(instanceClassName.match(/\bcol-md-offset-0\b/)); assert.ok(instanceClassName.match(/\bcol-lg-offset-0\b/)); }); it('Should set Pull of zero', () => { let instance = ReactTestUtils.renderIntoDocument( <Col xsPull={0} smPull={0} mdPull={0} lgPull={0} /> ); let instanceClassName = ReactDOM.findDOMNode(instance).className; assert.ok(instanceClassName.match(/\bcol-xs-pull-0\b/)); assert.ok(instanceClassName.match(/\bcol-sm-pull-0\b/)); assert.ok(instanceClassName.match(/\bcol-md-pull-0\b/)); assert.ok(instanceClassName.match(/\bcol-lg-pull-0\b/)); }); it('Should set Push of zero', () => { let instance = ReactTestUtils.renderIntoDocument( <Col xsPush={0} smPush={0} mdPush={0} lgPush={0} /> ); let instanceClassName = ReactDOM.findDOMNode(instance).className; assert.ok(instanceClassName.match(/\bcol-xs-push-0\b/)); assert.ok(instanceClassName.match(/\bcol-sm-push-0\b/)); assert.ok(instanceClassName.match(/\bcol-md-push-0\b/)); assert.ok(instanceClassName.match(/\bcol-lg-push-0\b/)); }); it('Should set Hidden to true', () => { let instance = ReactTestUtils.renderIntoDocument( <Col xsHidden smHidden mdHidden lgHidden /> ); let instanceClassName = ReactDOM.findDOMNode(instance).className; assert.ok(instanceClassName.match(/\bhidden-xs\b/)); assert.ok(instanceClassName.match(/\bhidden-sm\b/)); assert.ok(instanceClassName.match(/\bhidden-md\b/)); assert.ok(instanceClassName.match(/\bhidden-lg\b/)); }); });
import _extends from"@babel/runtime/helpers/extends";import _objectWithoutProperties from"@babel/runtime/helpers/objectWithoutProperties";var _excluded=["value","getRootRef"];import{createScopedElement}from"../../lib/jsxRuntime";import{getClassName}from"../../helpers/getClassName";import{usePlatform}from"../../hooks/usePlatform";var Progress=function(e){var r=e.value,t=e.getRootRef,o=_objectWithoutProperties(e,_excluded),e=usePlatform();return createScopedElement("div",_extends({"aria-valuenow":r},o,{role:"progressbar","aria-valuemin":0,"aria-valuemax":100,ref:t,vkuiClass:getClassName("Progress",e)}),createScopedElement("div",{vkuiClass:"Progress__bg","aria-hidden":"true"}),createScopedElement("div",{vkuiClass:"Progress__in",style:{width:"".concat(r,"%")},"aria-hidden":"true"}))};Progress.defaultProps={value:0};export default Progress;
/* * * * (c) 2010-2018 Torstein Honsi * * License: www.highcharts.com/license * * */ /** * Options to align the element relative to the chart or another box. * * @interface Highcharts.AlignObject *//** * Horizontal alignment. Can be one of `left`, `center` and `right`. * * @name Highcharts.AlignObject#align * @type {string|undefined} * * @default left *//** * Vertical alignment. Can be one of `top`, `middle` and `bottom`. * * @name Highcharts.AlignObject#verticalAlign * @type {string|undefined} * * @default top *//** * Horizontal pixel offset from alignment. * * @name Highcharts.AlignObject#x * @type {number|undefined} * * @default 0 *//** * Vertical pixel offset from alignment. * * @name Highcharts.AlignObject#y * @type {number|undefined} * * @default 0 *//** * Use the `transform` attribute with translateX and translateY custom * attributes to align this elements rather than `x` and `y` attributes. * * @name Highcharts.AlignObject#alignByTranslate * @type {boolean|undefined} * * @default false */ /** * Bounding box of an element. * * @interface Highcharts.BBoxObject *//** * Height of the bounding box. * * @name Highcharts.BBoxObject#height * @type {number} *//** * Width of the bounding box. * * @name Highcharts.BBoxObject#width * @type {number} *//** * Horizontal position of the bounding box. * * @name Highcharts.BBoxObject#x * @type {number} *//** * Vertical position of the bounding box. * * @name Highcharts.BBoxObject#y * @type {number} */ /** * A clipping rectangle that can be applied to one or more {@link SVGElement} * instances. It is instanciated with the {@link SVGRenderer#clipRect} function * and applied with the {@link SVGElement#clip} function. * * @example * var circle = renderer.circle(100, 100, 100) * .attr({ fill: 'red' }) * .add(); * var clipRect = renderer.clipRect(100, 100, 100, 100); * * // Leave only the lower right quarter visible * circle.clip(clipRect); * * @typedef {Highcharts.SVGElement} Highcharts.ClipRectElement */ /** * The font metrics. * * @interface Highcharts.FontMetricsObject *//** * The baseline relative to the top of the box. * * @name Highcharts.FontMetricsObject#b * @type {number} *//** * The line height. * * @name Highcharts.FontMetricsObject#h * @type {number} *//** * The font size. * * @name Highcharts.FontMetricsObject#f * @type {number} */ /** * Gradient options instead of a solid color. * * @example * // Linear gradient used as a color option * color: { * linearGradient: { x1: 0, x2: 0, y1: 0, y2: 1 }, * stops: [ * [0, '#003399'], // start * [0.5, '#ffffff'], // middle * [1, '#3366AA'] // end * ] * } * } * * @interface Highcharts.GradientColorObject *//** * Holds an object that defines the start position and the end position relative * to the shape. * * @name Highcharts.GradientColorObject#linearGradient * @type {Highcharts.LinearGradientColorObject|undefined} *//** * Holds an object that defines the center position and the radius. * * @name Highcharts.GradientColorObject#radialGradient * @type {Highcharts.RadialGradientColorObject|undefined} *//** * The first item in each tuple is the position in the gradient, where 0 is the * start of the gradient and 1 is the end of the gradient. Multiple stops can be * applied. The second item is the color for each stop. This color can also be * given in the rgba format. * * @name Highcharts.GradientColorObject#stops * @type {Array<Array<number,Highcharts.ColorString>>|undefined} */ /** * Defines the start position and the end position for a gradient relative * to the shape. Start position (x1, y1) and end position (x2, y2) are relative * to the shape, where 0 means top/left and 1 is bottom/right. * * @interface Highcharts.LinearGradientColorObject *//** * Start horizontal position of the gradient. Float ranges 0-1. * * @name Highcharts.LinearGradientColorObject#x1 * @type {number} *//** * End horizontal position of the gradient. Float ranges 0-1. * * @name Highcharts.LinearGradientColorObject#x2 * @type {number} *//** * Start vertical position of the gradient. Float ranges 0-1. * * @name Highcharts.LinearGradientColorObject#y1 * @type {number} *//** * End vertical position of the gradient. Float ranges 0-1. * * @name Highcharts.LinearGradientColorObject#y2 * @type {number} */ /** * Defines the center position and the radius for a gradient. * * @interface Highcharts.RadialGradientColorObject *//** * Center horizontal position relative to the shape. Float ranges 0-1. * * @name Highcharts.RadialGradientColorObject#cx * @type {number} *//** * Center vertical position relative to the shape. Float ranges 0-1. * * @name Highcharts.RadialGradientColorObject#cy * @type {number} *//** * Radius relative to the shape. Float ranges 0-1. * * @name Highcharts.RadialGradientColorObject#r * @type {number} */ /** * A rectangle. * * @interface Highcharts.RectangleObject *//** * Height of the rectangle. * * @name Highcharts.RectangleObject#height * @type {number} *//** * Width of the rectangle. * * @name Highcharts.RectangleObject#width * @type {number} *//** * Horizontal position of the rectangle. * * @name Highcharts.RectangleObject#x * @type {number} *//** * Vertical position of the rectangle. * * @name Highcharts.RectangleObject#y * @type {number} */ /** * The shadow options. * * @interface Highcharts.ShadowOptionsObject *//** * The shadow color. * * @name Highcharts.ShadowOptionsObject#color * @type {string|undefined} * * @default #000000 *//** * The horizontal offset from the element. * * @name Highcharts.ShadowOptionsObject#offsetX * @type {number|undefined} * * @default 1 *//** * The vertical offset from the element. * * @name Highcharts.ShadowOptionsObject#offsetY * @type {number|undefined} * * @default 1 *//** * The shadow opacity. * * @name Highcharts.ShadowOptionsObject#opacity * @type {number|undefined} * * @default 0.15 *//** * The shadow width or distance from the element. * * @name Highcharts.ShadowOptionsObject#width * @type {number|undefined} * * @default 3 */ /** * Serialized form of an SVG definition, including children. Some key * property names are reserved: tagName, textContent, and children. * * @interface Highcharts.SVGDefinitionObject *//** * @name Highcharts.SVGDefinitionObject#[key:string] * @type {number|string|Array<Highcharts.SVGDefinitionObject>|undefined} *//** * @name Highcharts.SVGDefinitionObject#children * @type {Array<Highcharts.SVGDefinitionObject>|undefined} *//** * @name Highcharts.SVGDefinitionObject#tagName * @type {string|undefined} *//** * @name Highcharts.SVGDefinitionObject#textContent * @type {string|undefined} */ /** * An extendable collection of functions for defining symbol paths. * * @typedef Highcharts.SymbolDictionary * * @property {Function|undefined} [key:Highcharts.SymbolKey] */ /** * Can be one of `arc`, `callout`, `circle`, `diamond`, `square`, * `triangle`, `triangle-down`. Symbols are used internally for point * markers, button and label borders and backgrounds, or custom shapes. * Extendable by adding to {@link SVGRenderer#symbols}. * * @typedef {string} Highcharts.SymbolKey * @validvalue ["arc", "callout", "circle", "diamond", "square", "triangle", * "triangle-down"] */ /** * Additional options, depending on the actual symbol drawn. * * @interface Highcharts.SymbolOptionsObject *//** * The anchor X position for the `callout` symbol. This is where the chevron * points to. * * @name Highcharts.SymbolOptionsObject#anchorX * @type {number} *//** * The anchor Y position for the `callout` symbol. This is where the chevron * points to. * * @name Highcharts.SymbolOptionsObject#anchorY * @type {number} *//** * The end angle of an `arc` symbol. * * @name Highcharts.SymbolOptionsObject#end * @type {number} *//** * Whether to draw `arc` symbol open or closed. * * @name Highcharts.SymbolOptionsObject#open * @type {boolean} *//** * The radius of an `arc` symbol, or the border radius for the `callout` symbol. * * @name Highcharts.SymbolOptionsObject#r * @type {number} *//** * The start angle of an `arc` symbol. * * @name Highcharts.SymbolOptionsObject#start * @type {number} */ 'use strict'; import H from './Globals.js'; import './Utilities.js'; import './Color.js'; var SVGElement, SVGRenderer, addEvent = H.addEvent, animate = H.animate, attr = H.attr, charts = H.charts, color = H.color, css = H.css, createElement = H.createElement, defined = H.defined, deg2rad = H.deg2rad, destroyObjectProperties = H.destroyObjectProperties, doc = H.doc, extend = H.extend, erase = H.erase, hasTouch = H.hasTouch, isArray = H.isArray, isFirefox = H.isFirefox, isMS = H.isMS, isObject = H.isObject, isString = H.isString, isWebKit = H.isWebKit, merge = H.merge, noop = H.noop, objectEach = H.objectEach, pick = H.pick, pInt = H.pInt, removeEvent = H.removeEvent, splat = H.splat, stop = H.stop, svg = H.svg, SVG_NS = H.SVG_NS, symbolSizes = H.symbolSizes, win = H.win; /** * The SVGElement prototype is a JavaScript wrapper for SVG elements used in the * rendering layer of Highcharts. Combined with the {@link * Highcharts.SVGRenderer} object, these prototypes allow freeform annotation * in the charts or even in HTML pages without instanciating a chart. The * SVGElement can also wrap HTML labels, when `text` or `label` elements are * created with the `useHTML` parameter. * * The SVGElement instances are created through factory functions on the {@link * Highcharts.SVGRenderer} object, like {@link Highcharts.SVGRenderer#rect| * rect}, {@link Highcharts.SVGRenderer#path|path}, {@link * Highcharts.SVGRenderer#text|text}, {@link Highcharts.SVGRenderer#label| * label}, {@link Highcharts.SVGRenderer#g|g} and more. * * @class * @name Highcharts.SVGElement */ SVGElement = H.SVGElement = function () { return this; }; extend(SVGElement.prototype, /** @lends Highcharts.SVGElement.prototype */ { // Default base for animation opacity: 1, SVG_NS: SVG_NS, /** * For labels, these CSS properties are applied to the `text` node directly. * * @private * @name Highcharts.SVGElement#textProps * @type {Array<string>} */ textProps: ['direction', 'fontSize', 'fontWeight', 'fontFamily', 'fontStyle', 'color', 'lineHeight', 'width', 'textAlign', 'textDecoration', 'textOverflow', 'textOutline', 'cursor'], /** * Initialize the SVG element. This function only exists to make the * initiation process overridable. It should not be called directly. * * @function Highcharts.SVGElement#init * * @param {Highcharts.SVGRenderer} renderer * The SVGRenderer instance to initialize to. * * @param {string} nodeName * The SVG node name. */ init: function (renderer, nodeName) { /** * The primary DOM node. Each `SVGElement` instance wraps a main DOM * node, but may also represent more nodes. * * @name Highcharts.SVGElement#element * @type {Highcharts.SVGDOMElement|Highcharts.HTMLDOMElement} */ this.element = nodeName === 'span' ? createElement(nodeName) : doc.createElementNS(this.SVG_NS, nodeName); /** * The renderer that the SVGElement belongs to. * * @name Highcharts.SVGElement#renderer * @type {Highcharts.SVGRenderer} */ this.renderer = renderer; }, /** * Animate to given attributes or CSS properties. * * @sample highcharts/members/element-on/ * Setting some attributes by animation * * @function Highcharts.SVGElement#animate * * @param {Highcharts.SVGAttributes} params * SVG attributes or CSS to animate. * * @param {Highcharts.AnimationOptionsObject} [options] * Animation options. * * @param {Function} [complete] * Function to perform at the end of animation. * * @return {Highcharts.SVGElement} * Returns the SVGElement for chaining. */ animate: function (params, options, complete) { var animOptions = H.animObject( pick(options, this.renderer.globalAnimation, true) ); if (animOptions.duration !== 0) { // allows using a callback with the global animation without // overwriting it if (complete) { animOptions.complete = complete; } animate(this, params, animOptions); } else { this.attr(params, null, complete); if (animOptions.step) { animOptions.step.call(this); } } return this; }, /** * Build and apply an SVG gradient out of a common JavaScript configuration * object. This function is called from the attribute setters. An event * hook is added for supporting other complex color types. * * @private * @function Highcharts.SVGElement#complexColor * * @param {Highcharts.GradientColorObject} color * The gradient options structure. * * @param {string} prop * The property to apply, can either be `fill` or `stroke`. * * @param {Highcharts.SVGDOMElement} elem * SVG DOM element to apply the gradient on. */ complexColor: function (color, prop, elem) { var renderer = this.renderer, colorObject, gradName, gradAttr, radAttr, gradients, gradientObject, stops, stopColor, stopOpacity, radialReference, id, key = [], value; H.fireEvent(this.renderer, 'complexColor', { args: arguments }, function () { // Apply linear or radial gradients if (color.radialGradient) { gradName = 'radialGradient'; } else if (color.linearGradient) { gradName = 'linearGradient'; } if (gradName) { gradAttr = color[gradName]; gradients = renderer.gradients; stops = color.stops; radialReference = elem.radialReference; // Keep < 2.2 kompatibility if (isArray(gradAttr)) { color[gradName] = gradAttr = { x1: gradAttr[0], y1: gradAttr[1], x2: gradAttr[2], y2: gradAttr[3], gradientUnits: 'userSpaceOnUse' }; } // Correct the radial gradient for the radial reference system if ( gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits) ) { // Save the radial attributes for updating radAttr = gradAttr; gradAttr = merge( gradAttr, renderer.getRadialAttr(radialReference, radAttr), { gradientUnits: 'userSpaceOnUse' } ); } // Build the unique key to detect whether we need to create a // new element (#1282) objectEach(gradAttr, function (val, n) { if (n !== 'id') { key.push(n, val); } }); objectEach(stops, function (val) { key.push(val); }); key = key.join(','); // Check if a gradient object with the same config object is // created within this renderer if (gradients[key]) { id = gradients[key].attr('id'); } else { // Set the id and create the element gradAttr.id = id = H.uniqueKey(); gradients[key] = gradientObject = renderer.createElement(gradName) .attr(gradAttr) .add(renderer.defs); gradientObject.radAttr = radAttr; // The gradient needs to keep a list of stops to be able to // destroy them gradientObject.stops = []; stops.forEach(function (stop) { var stopObject; if (stop[1].indexOf('rgba') === 0) { colorObject = H.color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } stopObject = renderer.createElement('stop').attr({ offset: stop[0], 'stop-color': stopColor, 'stop-opacity': stopOpacity }).add(gradientObject); // Add the stop element to the gradient gradientObject.stops.push(stopObject); }); } // Set the reference to the gradient object value = 'url(' + renderer.url + '#' + id + ')'; elem.setAttribute(prop, value); elem.gradient = key; // Allow the color to be concatenated into tooltips formatters // etc. (#2995) color.toString = function () { return value; }; } }); }, /** * Apply a text outline through a custom CSS property, by copying the text * element and apply stroke to the copy. Used internally. Contrast checks at * [example](https://jsfiddle.net/highcharts/43soe9m1/2/). * * @example * // Specific color * text.css({ * textOutline: '1px black' * }); * // Automatic contrast * text.css({ * color: '#000000', // black text * textOutline: '1px contrast' // => white outline * }); * * @private * @function Highcharts.SVGElement#applyTextOutline * * @param {string} textOutline * A custom CSS `text-outline` setting, defined by `width color`. */ applyTextOutline: function (textOutline) { var elem = this.element, tspans, tspan, hasContrast = textOutline.indexOf('contrast') !== -1, styles = {}, color, strokeWidth, firstRealChild, i; // When the text shadow is set to contrast, use dark stroke for light // text and vice versa. if (hasContrast) { styles.textOutline = textOutline = textOutline.replace( /contrast/g, this.renderer.getContrast(elem.style.fill) ); } // Extract the stroke width and color textOutline = textOutline.split(' '); color = textOutline[textOutline.length - 1]; strokeWidth = textOutline[0]; if (strokeWidth && strokeWidth !== 'none' && H.svg) { this.fakeTS = true; // Fake text shadow tspans = [].slice.call(elem.getElementsByTagName('tspan')); // In order to get the right y position of the clone, // copy over the y setter this.ySetter = this.xSetter; // Since the stroke is applied on center of the actual outline, we // need to double it to get the correct stroke-width outside the // glyphs. strokeWidth = strokeWidth.replace( /(^[\d\.]+)(.*?)$/g, function (match, digit, unit) { return (2 * digit) + unit; } ); // Remove shadows from previous runs. Iterate from the end to // support removing items inside the cycle (#6472). i = tspans.length; while (i--) { tspan = tspans[i]; if (tspan.getAttribute('class') === 'highcharts-text-outline') { // Remove then erase erase(tspans, elem.removeChild(tspan)); } } // For each of the tspans, create a stroked copy behind it. firstRealChild = elem.firstChild; tspans.forEach(function (tspan, y) { var clone; // Let the first line start at the correct X position if (y === 0) { tspan.setAttribute('x', elem.getAttribute('x')); y = elem.getAttribute('y'); tspan.setAttribute('y', y || 0); if (y === null) { elem.setAttribute('y', 0); } } // Create the clone and apply outline properties clone = tspan.cloneNode(1); attr(clone, { 'class': 'highcharts-text-outline', 'fill': color, 'stroke': color, 'stroke-width': strokeWidth, 'stroke-linejoin': 'round' }); elem.insertBefore(clone, firstRealChild); }); } }, // Custom attributes used for symbols, these should be filtered out when // setting SVGElement attributes (#9375). symbolCustomAttribs: [ 'x', 'y', 'width', 'height', 'r', 'start', 'end', 'innerR', 'anchorX', 'anchorY', 'rounded' ], /** * Apply native and custom attributes to the SVG elements. * * In order to set the rotation center for rotation, set x and y to 0 and * use `translateX` and `translateY` attributes to position the element * instead. * * Attributes frequently used in Highcharts are `fill`, `stroke`, * `stroke-width`. * * @sample highcharts/members/renderer-rect/ * Setting some attributes * * @example * // Set multiple attributes * element.attr({ * stroke: 'red', * fill: 'blue', * x: 10, * y: 10 * }); * * // Set a single attribute * element.attr('stroke', 'red'); * * // Get an attribute * element.attr('stroke'); // => 'red' * * @function Highcharts.SVGElement#attr * * @param {string|Highcharts.SVGAttributes} [hash] * The native and custom SVG attributes. * * @param {string} [val] * If the type of the first argument is `string`, the second can be a * value, which will serve as a single attribute setter. If the first * argument is a string and the second is undefined, the function * serves as a getter and the current value of the property is * returned. * * @param {Function} [complete] * A callback function to execute after setting the attributes. This * makes the function compliant and interchangeable with the * {@link SVGElement#animate} function. * * @param {boolean} [continueAnimation=true] * Used internally when `.attr` is called as part of an animation * step. Otherwise, calling `.attr` for an attribute will stop * animation for that attribute. * * @return {number|string|Highcharts.SVGElement} * If used as a setter, it returns the current * {@link Highcharts.SVGElement} so the calls can be chained. If * used as a getter, the current value of the attribute is returned. */ attr: function (hash, val, complete, continueAnimation) { var key, element = this.element, hasSetSymbolSize, ret = this, skipAttr, setter, symbolCustomAttribs = this.symbolCustomAttribs; // single key-value pair if (typeof hash === 'string' && val !== undefined) { key = hash; hash = {}; hash[key] = val; } // used as a getter: first argument is a string, second is undefined if (typeof hash === 'string') { ret = (this[hash + 'Getter'] || this._defaultGetter).call( this, hash, element ); // setter } else { objectEach(hash, function eachAttribute(val, key) { skipAttr = false; // Unless .attr is from the animator update, stop current // running animation of this property if (!continueAnimation) { stop(this, key); } // Special handling of symbol attributes if ( this.symbolName && H.inArray(key, symbolCustomAttribs) !== -1 ) { if (!hasSetSymbolSize) { this.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } if (this.rotation && (key === 'x' || key === 'y')) { this.doTransform = true; } if (!skipAttr) { setter = this[key + 'Setter'] || this._defaultSetter; setter.call(this, val, key, element); // Let the shadow follow the main element if ( !this.styledMode && this.shadows && /^(width|height|visibility|x|y|d|transform|cx|cy|r)$/ .test(key) ) { this.updateShadows(key, val, setter); } } }, this); this.afterSetters(); } // In accordance with animate, run a complete callback if (complete) { complete.call(this); } return ret; }, /** * This method is executed in the end of `attr()`, after setting all * attributes in the hash. In can be used to efficiently consolidate * multiple attributes in one SVG property -- e.g., translate, rotate and * scale are merged in one "transform" attribute in the SVG node. * * @private * @function Highcharts.SVGElement#afterSetters */ afterSetters: function () { // Update transform. Do this outside the loop to prevent redundant // updating for batch setting of attributes. if (this.doTransform) { this.updateTransform(); this.doTransform = false; } }, /** * Update the shadow elements with new attributes. * * @private * @function Highcharts.SVGElement#updateShadows * * @param {string} key * The attribute name. * * @param {string|number} value * The value of the attribute. * * @param {Function} setter * The setter function, inherited from the parent wrapper. */ updateShadows: function (key, value, setter) { var shadows = this.shadows, i = shadows.length; while (i--) { setter.call( shadows[i], key === 'height' ? Math.max(value - (shadows[i].cutHeight || 0), 0) : key === 'd' ? this.d : value, key, shadows[i] ); } }, /** * Add a class name to an element. * * @function Highcharts.SVGElement#addClass * * @param {string} className * The new class name to add. * * @param {boolean} [replace=false] * When true, the existing class name(s) will be overwritten with * the new one. When false, the new one is added. * * @return {Highcharts.SVGElement} * Return the SVG element for chainability. */ addClass: function (className, replace) { var currentClassName = this.attr('class') || ''; if (currentClassName.indexOf(className) === -1) { if (!replace) { className = (currentClassName + (currentClassName ? ' ' : '') + className).replace(' ', ' '); } this.attr('class', className); } return this; }, /** * Check if an element has the given class name. * * @function Highcharts.SVGElement#hasClass * * @param {string} className * The class name to check for. * * @return {boolean} * Whether the class name is found. */ hasClass: function (className) { return (this.attr('class') || '').split(' ').indexOf(className) !== -1; }, /** * Remove a class name from the element. * * @function Highcharts.SVGElement#removeClass * * @param {string|RegExp} className * The class name to remove. * * @return {Highcharts.SVGElement} Returns the SVG element for chainability. */ removeClass: function (className) { return this.attr( 'class', (this.attr('class') || '').replace(className, '') ); }, /** * If one of the symbol size affecting parameters are changed, * check all the others only once for each call to an element's * .attr() method * * @private * @function Highcharts.SVGElement#symbolAttr * * @param {Highcharts.Dictionary<number|string>} hash * The attributes to set. */ symbolAttr: function (hash) { var wrapper = this; [ 'x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY' ].forEach(function (key) { wrapper[key] = pick(hash[key], wrapper[key]); }); wrapper.attr({ d: wrapper.renderer.symbols[wrapper.symbolName]( wrapper.x, wrapper.y, wrapper.width, wrapper.height, wrapper ) }); }, /** * Apply a clipping rectangle to this element. * * @function Highcharts.SVGElement#clip * * @param {Highcharts.ClipRectElement} [clipRect] * The clipping rectangle. If skipped, the current clip is removed. * * @return {Highcharts.SVGElement} * Returns the SVG element to allow chaining. */ clip: function (clipRect) { return this.attr( 'clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : 'none' ); }, /** * Calculate the coordinates needed for drawing a rectangle crisply and * return the calculated attributes. * * @function Highcharts.SVGElement#crisp * * @param {Highcharts.RectangleObject} rect * Rectangle to crisp. * * @param {number} [strokeWidth] * The stroke width to consider when computing crisp positioning. It * can also be set directly on the rect parameter. * * @return {Highcharts.RectangleObject} * The modified rectangle arguments. */ crisp: function (rect, strokeWidth) { var wrapper = this, normalizer; strokeWidth = strokeWidth || rect.strokeWidth || 0; // Math.round because strokeWidth can sometimes have roundoff errors normalizer = Math.round(strokeWidth) % 2 / 2; // normalize for crisp edges rect.x = Math.floor(rect.x || wrapper.x || 0) + normalizer; rect.y = Math.floor(rect.y || wrapper.y || 0) + normalizer; rect.width = Math.floor( (rect.width || wrapper.width || 0) - 2 * normalizer ); rect.height = Math.floor( (rect.height || wrapper.height || 0) - 2 * normalizer ); if (defined(rect.strokeWidth)) { rect.strokeWidth = strokeWidth; } return rect; }, /** * Set styles for the element. In addition to CSS styles supported by * native SVG and HTML elements, there are also some custom made for * Highcharts, like `width`, `ellipsis` and `textOverflow` for SVG text * elements. * * @sample highcharts/members/renderer-text-on-chart/ * Styled text * * @function Highcharts.SVGElement#css * * @param {Highcharts.CSSObject} styles * The new CSS styles. * * @return {Highcharts.SVGElement} * Return the SVG element for chaining. */ css: function (styles) { var oldStyles = this.styles, newStyles = {}, elem = this.element, textWidth, serializedCss = '', hyphenate, hasNew = !oldStyles, // These CSS properties are interpreted internally by the SVG // renderer, but are not supported by SVG and should not be added to // the DOM. In styled mode, no CSS should find its way to the DOM // whatsoever (#6173, #6474). svgPseudoProps = ['textOutline', 'textOverflow', 'width']; // convert legacy if (styles && styles.color) { styles.fill = styles.color; } // Filter out existing styles to increase performance (#2640) if (oldStyles) { objectEach(styles, function (style, n) { if (style !== oldStyles[n]) { newStyles[n] = style; hasNew = true; } }); } if (hasNew) { // Merge the new styles with the old ones if (oldStyles) { styles = extend( oldStyles, newStyles ); } // Get the text width from style if (styles) { // Previously set, unset it (#8234) if (styles.width === null || styles.width === 'auto') { delete this.textWidth; // Apply new } else if ( elem.nodeName.toLowerCase() === 'text' && styles.width ) { textWidth = this.textWidth = pInt(styles.width); } } // store object this.styles = styles; if (textWidth && (!svg && this.renderer.forExport)) { delete styles.width; } // Serialize and set style attribute if (elem.namespaceURI === this.SVG_NS) { // #7633 hyphenate = function (a, b) { return '-' + b.toLowerCase(); }; objectEach(styles, function (style, n) { if (svgPseudoProps.indexOf(n) === -1) { serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + style + ';'; } }); if (serializedCss) { attr(elem, 'style', serializedCss); // #1881 } } else { css(elem, styles); } if (this.added) { // Rebuild text after added. Cache mechanisms in the buildText // will prevent building if there are no significant changes. if (this.element.nodeName === 'text') { this.renderer.buildText(this); } // Apply text outline after added if (styles && styles.textOutline) { this.applyTextOutline(styles.textOutline); } } } return this; }, /** * Get the computed style. Only in styled mode. * * @example * chart.series[0].points[0].graphic.getStyle('stroke-width'); // => '1px' * * @function Highcharts.SVGElement#getStyle * * @param {string} prop * The property name to check for. * * @return {string} * The current computed value. */ getStyle: function (prop) { return win.getComputedStyle(this.element || this, '') .getPropertyValue(prop); }, /** * Get the computed stroke width in pixel values. This is used extensively * when drawing shapes to ensure the shapes are rendered crisp and * positioned correctly relative to each other. Using * `shape-rendering: crispEdges` leaves us less control over positioning, * for example when we want to stack columns next to each other, or position * things pixel-perfectly within the plot box. * * The common pattern when placing a shape is: * - Create the SVGElement and add it to the DOM. In styled mode, it will * now receive a stroke width from the style sheet. In classic mode we * will add the `stroke-width` attribute. * - Read the computed `elem.strokeWidth()`. * - Place it based on the stroke width. * * @function Highcharts.SVGElement#strokeWidth * * @return {number} * The stroke width in pixels. Even if the given stroke widtch (in * CSS or by attributes) is based on `em` or other units, the pixel * size is returned. */ strokeWidth: function () { // In non-styled mode, read the stroke width as set by .attr if (!this.renderer.styledMode) { return this['stroke-width'] || 0; } // In styled mode, read computed stroke width var val = this.getStyle('stroke-width'), ret, dummy; // Read pixel values directly if (val.indexOf('px') === val.length - 2) { ret = pInt(val); // Other values like em, pt etc need to be measured } else { dummy = doc.createElementNS(SVG_NS, 'rect'); attr(dummy, { 'width': val, 'stroke-width': 0 }); this.element.parentNode.appendChild(dummy); ret = dummy.getBBox().width; dummy.parentNode.removeChild(dummy); } return ret; }, /** * Add an event listener. This is a simple setter that replaces all other * events of the same type, opposed to the {@link Highcharts#addEvent} * function. * * @sample highcharts/members/element-on/ * A clickable rectangle * * @function Highcharts.SVGElement#on * * @param {string} eventType * The event type. If the type is `click`, Highcharts will internally * translate it to a `touchstart` event on touch devices, to prevent * the browser from waiting for a click event from firing. * * @param {Function} handler * The handler callback. * * @return {Highcharts.SVGElement} * The SVGElement for chaining. */ on: function (eventType, handler) { var svgElement = this, element = svgElement.element; // touch if (hasTouch && eventType === 'click') { element.ontouchstart = function (e) { svgElement.touchEventFired = Date.now(); // #2269 e.preventDefault(); handler.call(element, e); }; element.onclick = function (e) { if (win.navigator.userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { handler.call(element, e); } }; } else { // simplest possible event model for internal use element['on' + eventType] = handler; } return this; }, /** * Set the coordinates needed to draw a consistent radial gradient across * a shape regardless of positioning inside the chart. Used on pie slices * to make all the slices have the same radial reference point. * * @function Highcharts.SVGElement#setRadialReference * * @param {Array<number>} coordinates * The center reference. The format is `[centerX, centerY, diameter]` * in pixels. * * @return {Highcharts.SVGElement} * Returns the SVGElement for chaining. */ setRadialReference: function (coordinates) { var existingGradient = this.renderer.gradients[this.element.gradient]; this.element.radialReference = coordinates; // On redrawing objects with an existing gradient, the gradient needs // to be repositioned (#3801) if (existingGradient && existingGradient.radAttr) { existingGradient.animate( this.renderer.getRadialAttr( coordinates, existingGradient.radAttr ) ); } return this; }, /** * Move an object and its children by x and y values. * * @function Highcharts.SVGElement#translate * * @param {number} x * The x value. * * @param {number} y * The y value. */ translate: function (x, y) { return this.attr({ translateX: x, translateY: y }); }, /** * Invert a group, rotate and flip. This is used internally on inverted * charts, where the points and graphs are drawn as if not inverted, then * the series group elements are inverted. * * @function Highcharts.SVGElement#invert * * @param {boolean} inverted * Whether to invert or not. An inverted shape can be un-inverted by * setting it to false. * * @return {Highcharts.SVGElement} * Return the SVGElement for chaining. */ invert: function (inverted) { var wrapper = this; wrapper.inverted = inverted; wrapper.updateTransform(); return wrapper; }, /** * Update the transform attribute based on internal properties. Deals with * the custom `translateX`, `translateY`, `rotation`, `scaleX` and `scaleY` * attributes and updates the SVG `transform` attribute. * * @private * @function Highcharts.SVGElement#updateTransform */ updateTransform: function () { var wrapper = this, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, scaleX = wrapper.scaleX, scaleY = wrapper.scaleY, inverted = wrapper.inverted, rotation = wrapper.rotation, matrix = wrapper.matrix, element = wrapper.element, transform; // Flipping affects translate as adjustment for flipping around the // group's axis if (inverted) { translateX += wrapper.width; translateY += wrapper.height; } // Apply translate. Nearly all transformed elements have translation, // so instead of checking for translate = 0, do it always (#1767, // #1846). transform = ['translate(' + translateX + ',' + translateY + ')']; // apply matrix if (defined(matrix)) { transform.push( 'matrix(' + matrix.join(',') + ')' ); } // apply rotation if (inverted) { transform.push('rotate(90) scale(-1,1)'); } else if (rotation) { // text rotation transform.push( 'rotate(' + rotation + ' ' + pick(this.rotationOriginX, element.getAttribute('x'), 0) + ' ' + pick(this.rotationOriginY, element.getAttribute('y') || 0) + ')' ); } // apply scale if (defined(scaleX) || defined(scaleY)) { transform.push( 'scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')' ); } if (transform.length) { element.setAttribute('transform', transform.join(' ')); } }, /** * Bring the element to the front. Alternatively, a new zIndex can be set. * * @sample highcharts/members/element-tofront/ * Click an element to bring it to front * * @function Highcharts.SVGElement#toFront * * @return {Highcharts.SVGElement} * Returns the SVGElement for chaining. */ toFront: function () { var element = this.element; element.parentNode.appendChild(element); return this; }, /** * Align the element relative to the chart or another box. * * @function Highcharts.SVGElement#align * * @param {Highcharts.AlignObject} [alignOptions] * The alignment options. The function can be called without this * parameter in order to re-align an element after the box has been * updated. * * @param {boolean} [alignByTranslate] * Align element by translation. * * @param {string|Highcharts.BBoxObject} [box] * The box to align to, needs a width and height. When the box is a * string, it refers to an object in the Renderer. For example, when * box is `spacingBox`, it refers to `Renderer.spacingBox` which * holds `width`, `height`, `x` and `y` properties. * * @return {Highcharts.SVGElement} Returns the SVGElement for chaining. */ align: function (alignOptions, alignByTranslate, box) { var align, vAlign, x, y, attribs = {}, alignTo, renderer = this.renderer, alignedObjects = renderer.alignedObjects, alignFactor, vAlignFactor; // First call on instanciate if (alignOptions) { this.alignOptions = alignOptions; this.alignByTranslate = alignByTranslate; if (!box || isString(box)) { this.alignTo = alignTo = box || 'renderer'; // prevent duplicates, like legendGroup after resize erase(alignedObjects, this); alignedObjects.push(this); box = null; // reassign it below } // When called on resize, no arguments are supplied } else { alignOptions = this.alignOptions; alignByTranslate = this.alignByTranslate; alignTo = this.alignTo; } box = pick(box, renderer[alignTo], renderer); // Assign variables align = alignOptions.align; vAlign = alignOptions.verticalAlign; x = (box.x || 0) + (alignOptions.x || 0); // default: left align y = (box.y || 0) + (alignOptions.y || 0); // default: top align // Align if (align === 'right') { alignFactor = 1; } else if (align === 'center') { alignFactor = 2; } if (alignFactor) { x += (box.width - (alignOptions.width || 0)) / alignFactor; } attribs[alignByTranslate ? 'translateX' : 'x'] = Math.round(x); // Vertical align if (vAlign === 'bottom') { vAlignFactor = 1; } else if (vAlign === 'middle') { vAlignFactor = 2; } if (vAlignFactor) { y += (box.height - (alignOptions.height || 0)) / vAlignFactor; } attribs[alignByTranslate ? 'translateY' : 'y'] = Math.round(y); // Animate only if already placed this[this.placed ? 'animate' : 'attr'](attribs); this.placed = true; this.alignAttr = attribs; return this; }, /** * Get the bounding box (width, height, x and y) for the element. Generally * used to get rendered text size. Since this is called a lot in charts, * the results are cached based on text properties, in order to save DOM * traffic. The returned bounding box includes the rotation, so for example * a single text line of rotation 90 will report a greater height, and a * width corresponding to the line-height. * * @sample highcharts/members/renderer-on-chart/ * Draw a rectangle based on a text's bounding box * * @function Highcharts.SVGElement#getBBox * * @param {boolean} [reload] * Skip the cache and get the updated DOM bouding box. * * @param {number} [rot] * Override the element's rotation. This is internally used on axis * labels with a value of 0 to find out what the bounding box would * be have been if it were not rotated. * * @return {Highcharts.BBoxObject} * The bounding box with `x`, `y`, `width` and `height` properties. */ getBBox: function (reload, rot) { var wrapper = this, bBox, // = wrapper.bBox, renderer = wrapper.renderer, width, height, rotation, rad, element = wrapper.element, styles = wrapper.styles, fontSize, textStr = wrapper.textStr, toggleTextShadowShim, cache = renderer.cache, cacheKeys = renderer.cacheKeys, isSVG = element.namespaceURI === wrapper.SVG_NS, cacheKey; rotation = pick(rot, wrapper.rotation); rad = rotation * deg2rad; fontSize = renderer.styledMode ? ( element && SVGElement.prototype.getStyle.call(element, 'font-size') ) : ( styles && styles.fontSize ); // Avoid undefined and null (#7316) if (defined(textStr)) { cacheKey = textStr.toString(); // Since numbers are monospaced, and numerical labels appear a lot // in a chart, we assume that a label of n characters has the same // bounding box as others of the same length. Unless there is inner // HTML in the label. In that case, leave the numbers as is (#5899). if (cacheKey.indexOf('<') === -1) { cacheKey = cacheKey.replace(/[0-9]/g, '0'); } // Properties that affect bounding box cacheKey += [ '', rotation || 0, fontSize, wrapper.textWidth, // #7874, also useHTML styles && styles.textOverflow // #5968 ] .join(','); } if (cacheKey && !reload) { bBox = cache[cacheKey]; } // No cache found if (!bBox) { // SVG elements if (isSVG || renderer.forExport) { try { // Fails in Firefox if the container has display: none. // When the text shadow shim is used, we need to hide the // fake shadows to get the correct bounding box (#3872) toggleTextShadowShim = this.fakeTS && function (display) { [].forEach.call( element.querySelectorAll( '.highcharts-text-outline' ), function (tspan) { tspan.style.display = display; } ); }; // Workaround for #3842, Firefox reporting wrong bounding // box for shadows if (toggleTextShadowShim) { toggleTextShadowShim('none'); } bBox = element.getBBox ? // SVG: use extend because IE9 is not allowed to change // width and height in case of rotation (below) extend({}, element.getBBox()) : { // Legacy IE in export mode width: element.offsetWidth, height: element.offsetHeight }; // #3842 if (toggleTextShadowShim) { toggleTextShadowShim(''); } } catch (e) {} // If the bBox is not set, the try-catch block above failed. The // other condition is for Opera that returns a width of // -Infinity on hidden elements. if (!bBox || bBox.width < 0) { bBox = { width: 0, height: 0 }; } // VML Renderer or useHTML within SVG } else { bBox = wrapper.htmlGetBBox(); } // True SVG elements as well as HTML elements in modern browsers // using the .useHTML option need to compensated for rotation if (renderer.isSVG) { width = bBox.width; height = bBox.height; // Workaround for wrong bounding box in IE, Edge and Chrome on // Windows. With Highcharts' default font, IE and Edge report // a box height of 16.899 and Chrome rounds it to 17. If this // stands uncorrected, it results in more padding added below // the text than above when adding a label border or background. // Also vertical positioning is affected. // https://jsfiddle.net/highcharts/em37nvuj/ // (#1101, #1505, #1669, #2568, #6213). if (isSVG) { bBox.height = height = ( { '11px,17': 14, '13px,20': 16 }[ styles && styles.fontSize + ',' + Math.round(height) ] || height ); } // Adjust for rotated text if (rotation) { bBox.width = Math.abs(height * Math.sin(rad)) + Math.abs(width * Math.cos(rad)); bBox.height = Math.abs(height * Math.cos(rad)) + Math.abs(width * Math.sin(rad)); } } // Cache it. When loading a chart in a hidden iframe in Firefox and // IE/Edge, the bounding box height is 0, so don't cache it (#5620). if (cacheKey && bBox.height > 0) { // Rotate (#4681) while (cacheKeys.length > 250) { delete cache[cacheKeys.shift()]; } if (!cache[cacheKey]) { cacheKeys.push(cacheKey); } cache[cacheKey] = bBox; } } return bBox; }, /** * Show the element after it has been hidden. * * @function Highcharts.SVGElement#show * * @param {boolean} [inherit=false] * Set the visibility attribute to `inherit` rather than `visible`. * The difference is that an element with `visibility="visible"` * will be visible even if the parent is hidden. * * @return {Highcharts.SVGElement} * Returns the SVGElement for chaining. */ show: function (inherit) { return this.attr({ visibility: inherit ? 'inherit' : 'visible' }); }, /** * Hide the element, equivalent to setting the `visibility` attribute to * `hidden`. * * @function Highcharts.SVGElement#hide * * @return {Highcharts.SVGElement} * Returns the SVGElement for chaining. */ hide: function () { return this.attr({ visibility: 'hidden' }); }, /** * Fade out an element by animating its opacity down to 0, and hide it on * complete. Used internally for the tooltip. * * @function Highcharts.SVGElement#fadeOut * * @param {number} [duration=150] * The fade duration in milliseconds. */ fadeOut: function (duration) { var elemWrapper = this; elemWrapper.animate({ opacity: 0 }, { duration: duration || 150, complete: function () { // #3088, assuming we're only using this for tooltips elemWrapper.attr({ y: -9999 }); } }); }, /** * Add the element to the DOM. All elements must be added this way. * * @sample highcharts/members/renderer-g * Elements added to a group * * @function Highcharts.SVGElement#add * * @param {Highcharts.SVGElement|Highcharts.SVGDOMElement} [parent] * The parent item to add it to. If undefined, the element is added * to the {@link Highcharts.SVGRenderer.box}. * * @return {Highcharts.SVGElement} * Returns the SVGElement for chaining. */ add: function (parent) { var renderer = this.renderer, element = this.element, inserted; if (parent) { this.parentGroup = parent; } // mark as inverted this.parentInverted = parent && parent.inverted; // build formatted text if (this.textStr !== undefined) { renderer.buildText(this); } // Mark as added this.added = true; // If we're adding to renderer root, or other elements in the group // have a z index, we need to handle it if (!parent || parent.handleZ || this.zIndex) { inserted = this.zIndexSetter(); } // If zIndex is not handled, append at the end if (!inserted) { (parent ? parent.element : renderer.box).appendChild(element); } // fire an event for internal hooks if (this.onAdd) { this.onAdd(); } return this; }, /** * Removes an element from the DOM. * * @private * @function Highcharts.SVGElement#safeRemoveChild * * @param {Highcharts.SVGDOMElement|Highcharts.HTMLDOMElement} element * The DOM node to remove. */ safeRemoveChild: function (element) { var parentNode = element.parentNode; if (parentNode) { parentNode.removeChild(element); } }, /** * Destroy the element and element wrapper and clear up the DOM and event * hooks. * * @function Highcharts.SVGElement#destroy */ destroy: function () { var wrapper = this, element = wrapper.element || {}, renderer = wrapper.renderer, parentToClean = renderer.isSVG && element.nodeName === 'SPAN' && wrapper.parentGroup, grandParent, ownerSVGElement = element.ownerSVGElement, i, clipPath = wrapper.clipPath; // remove events element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null; stop(wrapper); // stop running animations if (clipPath && ownerSVGElement) { // Look for existing references to this clipPath and remove them // before destroying the element (#6196). // The upper case version is for Edge [].forEach.call( ownerSVGElement.querySelectorAll('[clip-path],[CLIP-PATH]'), function (el) { var clipPathAttr = el.getAttribute('clip-path'), clipPathId = clipPath.element.id; // Include the closing paranthesis in the test to rule out // id's from 10 and above (#6550). Edge puts quotes inside // the url, others not. if ( clipPathAttr.indexOf('(#' + clipPathId + ')') > -1 || clipPathAttr.indexOf('("#' + clipPathId + '")') > -1 ) { el.removeAttribute('clip-path'); } } ); wrapper.clipPath = clipPath.destroy(); } // Destroy stops in case this is a gradient object if (wrapper.stops) { for (i = 0; i < wrapper.stops.length; i++) { wrapper.stops[i] = wrapper.stops[i].destroy(); } wrapper.stops = null; } // remove element wrapper.safeRemoveChild(element); if (!renderer.styledMode) { wrapper.destroyShadows(); } // In case of useHTML, clean up empty containers emulating SVG groups // (#1960, #2393, #2697). while ( parentToClean && parentToClean.div && parentToClean.div.childNodes.length === 0 ) { grandParent = parentToClean.parentGroup; wrapper.safeRemoveChild(parentToClean.div); delete parentToClean.div; parentToClean = grandParent; } // remove from alignObjects if (wrapper.alignTo) { erase(renderer.alignedObjects, wrapper); } objectEach(wrapper, function (val, key) { delete wrapper[key]; }); return null; }, /** * Add a shadow to the element. Must be called after the element is added to * the DOM. In styled mode, this method is not used, instead use `defs` and * filters. * * @example * renderer.rect(10, 100, 100, 100) * .attr({ fill: 'red' }) * .shadow(true); * * @function Highcharts.SVGElement#shadow * * @param {boolean|Highcharts.ShadowOptionsObject} shadowOptions * The shadow options. If `true`, the default options are applied. If * `false`, the current shadow will be removed. * * @param {Highcharts.SVGElement} [group] * The SVG group element where the shadows will be applied. The * default is to add it to the same parent as the current element. * Internally, this is ised for pie slices, where all the shadows are * added to an element behind all the slices. * * @param {boolean} [cutOff] * Used internally for column shadows. * * @return {Highcharts.SVGElement} * Returns the SVGElement for chaining. */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, shadow, element = this.element, strokeWidth, shadowWidth, shadowElementOpacity, // compensate for inverted plot area transform; if (!shadowOptions) { this.destroyShadows(); } else if (!this.shadows) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; transform = this.parentInverted ? '(-1,-1)' : '(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')'; for (i = 1; i <= shadowWidth; i++) { shadow = element.cloneNode(0); strokeWidth = (shadowWidth * 2) + 1 - (2 * i); attr(shadow, { 'stroke': shadowOptions.color || '#000000', 'stroke-opacity': shadowElementOpacity * i, 'stroke-width': strokeWidth, 'transform': 'translate' + transform, 'fill': 'none' }); shadow.setAttribute( 'class', (shadow.getAttribute('class') || '') + ' highcharts-shadow' ); if (cutOff) { attr( shadow, 'height', Math.max(attr(shadow, 'height') - strokeWidth, 0) ); shadow.cutHeight = strokeWidth; } if (group) { group.element.appendChild(shadow); } else if (element.parentNode) { element.parentNode.insertBefore(shadow, element); } shadows.push(shadow); } this.shadows = shadows; } return this; }, /** * Destroy shadows on the element. * * @private * @function Highcharts.SVGElement#destroyShadows */ destroyShadows: function () { (this.shadows || []).forEach(function (shadow) { this.safeRemoveChild(shadow); }, this); this.shadows = undefined; }, /** * @private * @function Highcharts.SVGElement#xGetter * * @param {string} key * * @return {number|string|null} */ xGetter: function (key) { if (this.element.nodeName === 'circle') { if (key === 'x') { key = 'cx'; } else if (key === 'y') { key = 'cy'; } } return this._defaultGetter(key); }, /** * Get the current value of an attribute or pseudo attribute, * used mainly for animation. Called internally from * the {@link Highcharts.SVGRenderer#attr} function. * * @private * @function Highcharts.SVGElement#_defaultGetter * * @param {string} key * Property key. * * @return {number|string|null} * Property value. */ _defaultGetter: function (key) { var ret = pick( this[key + 'Value'], // align getter this[key], this.element ? this.element.getAttribute(key) : null, 0 ); if (/^[\-0-9\.]+$/.test(ret)) { // is numerical ret = parseFloat(ret); } return ret; }, /** * @private * @function Highcharts.SVGElement#dSettter * * @param {number|string|Highcharts.SVGPathArray} value * * @param {string} key * * @param {Highcharts.SVGDOMElement} element */ dSetter: function (value, key, element) { if (value && value.join) { // join path value = value.join(' '); } if (/(NaN| {2}|^$)/.test(value)) { value = 'M 0 0'; } // Check for cache before resetting. Resetting causes disturbance in the // DOM, causing flickering in some cases in Edge/IE (#6747). Also // possible performance gain. if (this[key] !== value) { element.setAttribute(key, value); this[key] = value; } }, /** * @private * @function Highcharts.SVGElement#dashstyleSetter * * @param {string} value */ dashstyleSetter: function (value) { var i, strokeWidth = this['stroke-width']; // If "inherit", like maps in IE, assume 1 (#4981). With HC5 and the new // strokeWidth function, we should be able to use that instead. if (strokeWidth === 'inherit') { strokeWidth = 1; } value = value && value.toLowerCase(); if (value) { value = value .replace('shortdashdotdot', '3,1,1,1,1,1,') .replace('shortdashdot', '3,1,1,1') .replace('shortdot', '1,1,') .replace('shortdash', '3,1,') .replace('longdash', '8,3,') .replace(/dot/g, '1,3,') .replace('dash', '4,3,') .replace(/,$/, '') .split(','); // ending comma i = value.length; while (i--) { value[i] = pInt(value[i]) * strokeWidth; } value = value.join(',') .replace(/NaN/g, 'none'); // #3226 this.element.setAttribute('stroke-dasharray', value); } }, /** * @private * @function Highcharts.SVGElement#alignSetter * * @param {"start"|"middle"|"end"} value */ alignSetter: function (value) { var convert = { left: 'start', center: 'middle', right: 'end' }; this.alignValue = value; this.element.setAttribute('text-anchor', convert[value]); }, /** * @private * @function Highcharts.SVGElement#opacitySetter * * @param {string} value * * @param {string} key * * @param {Highcharts.SVGDOMElement} element */ opacitySetter: function (value, key, element) { this[key] = value; element.setAttribute(key, value); }, /** * @private * @function Highcharts.SVGElement#titleSetter * * @param {string} value */ titleSetter: function (value) { var titleNode = this.element.getElementsByTagName('title')[0]; if (!titleNode) { titleNode = doc.createElementNS(this.SVG_NS, 'title'); this.element.appendChild(titleNode); } // Remove text content if it exists if (titleNode.firstChild) { titleNode.removeChild(titleNode.firstChild); } titleNode.appendChild( doc.createTextNode( // #3276, #3895 (String(pick(value), '')) .replace(/<[^>]*>/g, '') .replace(/&lt;/g, '<') .replace(/&gt;/g, '>') ) ); }, /** * @private * @function Highcharts.SVGElement#textSetter * * @param {string} value */ textSetter: function (value) { if (value !== this.textStr) { // Delete bBox memo when the text changes delete this.bBox; this.textStr = value; if (this.added) { this.renderer.buildText(this); } } }, /** * @private * @function Highcharts.SVGElement#fillSetter * * @param {Highcharts.Color|Highcharts.ColorString} value * * @param {string} key * * @param {Highcharts.SVGDOMElement} element */ fillSetter: function (value, key, element) { if (typeof value === 'string') { element.setAttribute(key, value); } else if (value) { this.complexColor(value, key, element); } }, /** * @private * @function Highcharts.SVGElement#visibilitySetter * * @param {string} value * * @param {string} key * * @param {Highcharts.SVGDOMElement} element */ visibilitySetter: function (value, key, element) { // IE9-11 doesn't handle visibilty:inherit well, so we remove the // attribute instead (#2881, #3909) if (value === 'inherit') { element.removeAttribute(key); } else if (this[key] !== value) { // #6747 element.setAttribute(key, value); } this[key] = value; }, /** * @private * @function Highcharts.SVGElement#zIndexSetter * * @param {string} value * * @param {string} key * * @return {boolean} */ zIndexSetter: function (value, key) { var renderer = this.renderer, parentGroup = this.parentGroup, parentWrapper = parentGroup || renderer, parentNode = parentWrapper.element || renderer.box, childNodes, otherElement, otherZIndex, element = this.element, inserted, undefinedOtherZIndex, svgParent = parentNode === renderer.box, run = this.added, i; if (defined(value)) { // So we can read it for other elements in the group element.setAttribute('data-z-index', value); value = +value; if (this[key] === value) { // Only update when needed (#3865) run = false; } } else if (defined(this[key])) { element.removeAttribute('data-z-index'); } this[key] = value; // Insert according to this and other elements' zIndex. Before .add() is // called, nothing is done. Then on add, or by later calls to // zIndexSetter, the node is placed on the right place in the DOM. if (run) { value = this.zIndex; if (value && parentGroup) { parentGroup.handleZ = true; } childNodes = parentNode.childNodes; for (i = childNodes.length - 1; i >= 0 && !inserted; i--) { otherElement = childNodes[i]; otherZIndex = otherElement.getAttribute('data-z-index'); undefinedOtherZIndex = !defined(otherZIndex); if (otherElement !== element) { if ( // Negative zIndex versus no zIndex: // On all levels except the highest. If the parent is // <svg>, then we don't want to put items before <desc> // or <defs> (value < 0 && undefinedOtherZIndex && !svgParent && !i) ) { parentNode.insertBefore(element, childNodes[i]); inserted = true; } else if ( // Insert after the first element with a lower zIndex pInt(otherZIndex) <= value || // If negative zIndex, add this before first undefined // zIndex element ( undefinedOtherZIndex && (!defined(value) || value >= 0) ) ) { parentNode.insertBefore( element, childNodes[i + 1] || null // null for oldIE export ); inserted = true; } } } if (!inserted) { parentNode.insertBefore( element, childNodes[svgParent ? 3 : 0] || null // null for oldIE ); inserted = true; } } return inserted; }, /** * @private * @function Highcharts.SVGElement#_defaultSetter * * @param {string} value * * @param {string} key * * @param {Highcharts.SVGDOMElement} element */ _defaultSetter: function (value, key, element) { element.setAttribute(key, value); } }); // Some shared setters and getters SVGElement.prototype.yGetter = SVGElement.prototype.xGetter; SVGElement.prototype.translateXSetter = SVGElement.prototype.translateYSetter = SVGElement.prototype.rotationSetter = SVGElement.prototype.verticalAlignSetter = SVGElement.prototype.rotationOriginXSetter = SVGElement.prototype.rotationOriginYSetter = SVGElement.prototype.scaleXSetter = SVGElement.prototype.scaleYSetter = SVGElement.prototype.matrixSetter = function (value, key) { this[key] = value; this.doTransform = true; }; // WebKit and Batik have problems with a stroke-width of zero, so in this case // we remove the stroke attribute altogether. #1270, #1369, #3065, #3072. SVGElement.prototype['stroke-widthSetter'] = /** * @private * @function Highcharts.SVGElement#strokeSetter * * @param {number|string} value * * @param {string} key * * @param {Highcharts.SVGDOMElement} element */ SVGElement.prototype.strokeSetter = function (value, key, element) { this[key] = value; // Only apply the stroke attribute if the stroke width is defined and larger // than 0 if (this.stroke && this['stroke-width']) { // Use prototype as instance may be overridden SVGElement.prototype.fillSetter.call( this, this.stroke, 'stroke', element ); element.setAttribute('stroke-width', this['stroke-width']); this.hasStroke = true; } else if (key === 'stroke-width' && value === 0 && this.hasStroke) { element.removeAttribute('stroke'); this.hasStroke = false; } }; /** * Allows direct access to the Highcharts rendering layer in order to draw * primitive shapes like circles, rectangles, paths or text directly on a chart, * or independent from any chart. The SVGRenderer represents a wrapper object * for SVG in modern browsers. Through the VMLRenderer, part of the `oldie.js` * module, it also brings vector graphics to IE <= 8. * * An existing chart's renderer can be accessed through {@link Chart.renderer}. * The renderer can also be used completely decoupled from a chart. * * @sample highcharts/members/renderer-on-chart * Annotating a chart programmatically. * @sample highcharts/members/renderer-basic * Independent SVG drawing. * * @example * // Use directly without a chart object. * var renderer = new Highcharts.Renderer(parentNode, 600, 400); * * @class * @name Highcharts.SVGRenderer * * @param {Highcharts.HTMLDOMElement} container * Where to put the SVG in the web page. * * @param {number} width * The width of the SVG. * * @param {number} height * The height of the SVG. * * @param {boolean} [forExport=false] * Whether the rendered content is intended for export. * * @param {boolean} [allowHTML=true] * Whether the renderer is allowed to include HTML text, which will be * projected on top of the SVG. */ SVGRenderer = H.SVGRenderer = function () { this.init.apply(this, arguments); }; extend(SVGRenderer.prototype, /** @lends Highcharts.SVGRenderer.prototype */ { /** * A pointer to the renderer's associated Element class. The VMLRenderer * will have a pointer to VMLElement here. * * @name Highcharts.SVGRenderer#Element * @type {Highcharts.SVGElement} */ Element: SVGElement, SVG_NS: SVG_NS, /** * Initialize the SVGRenderer. Overridable initiator function that takes * the same parameters as the constructor. * * @function Highcharts.SVGRenderer#init * * @param {Highcharts.HTMLDOMElement} container * Where to put the SVG in the web page. * * @param {number} width * The width of the SVG. * * @param {number} height * The height of the SVG. * * @param {boolean} [forExport=false] * Whether the rendered content is intended for export. * * @param {boolean} [allowHTML=true] * Whether the renderer is allowed to include HTML text, which will * be projected on top of the SVG. * * @param {boolean} [styledMode=false] * Whether the renderer belongs to a chart that is in styled mode. * If it does, it will avoid setting presentational attributes in * some cases, but not when set explicitly through `.attr` and `.css` * etc. * * @return {void} */ init: function ( container, width, height, style, forExport, allowHTML, styledMode ) { var renderer = this, boxWrapper, element, desc; boxWrapper = renderer.createElement('svg') .attr({ 'version': '1.1', 'class': 'highcharts-root' }); if (!styledMode) { boxWrapper.css(this.getStyle(style)); } element = boxWrapper.element; container.appendChild(element); // Always use ltr on the container, otherwise text-anchor will be // flipped and text appear outside labels, buttons, tooltip etc (#3482) attr(container, 'dir', 'ltr'); // For browsers other than IE, add the namespace attribute (#1978) if (container.innerHTML.indexOf('xmlns') === -1) { attr(element, 'xmlns', this.SVG_NS); } // object properties renderer.isSVG = true; /** * The root `svg` node of the renderer. * * @name Highcharts.SVGRenderer#box * @type {Highcharts.SVGDOMElement} */ this.box = element; /** * The wrapper for the root `svg` node of the renderer. * * @name Highcharts.SVGRenderer#boxWrapper * @type {Highcharts.SVGElement} */ this.boxWrapper = boxWrapper; renderer.alignedObjects = []; /** * Page url used for internal references. * * @private * @name Highcharts.SVGRenderer#url * @type {string} */ // #24, #672, #1070 this.url = ( (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ) ? win.location.href .split('#')[0] // remove the hash .replace(/<[^>]*>/g, '') // wing cut HTML // escape parantheses and quotes .replace(/([\('\)])/g, '\\$1') // replace spaces (needed for Safari only) .replace(/ /g, '%20') : ''; // Add description desc = this.createElement('desc').add(); desc.element.appendChild( doc.createTextNode('Created with @product.name@ @product.version@') ); /** * A pointer to the `defs` node of the root SVG. * * @name Highcharts.SVGRenderer#defs * @type {Highcharts.SVGElement} */ renderer.defs = this.createElement('defs').add(); renderer.allowHTML = allowHTML; renderer.forExport = forExport; renderer.styledMode = styledMode; renderer.gradients = {}; // Object where gradient SvgElements are stored renderer.cache = {}; // Cache for numerical bounding boxes renderer.cacheKeys = []; renderer.imgCount = 0; renderer.setSize(width, height, false); // Issue 110 workaround: // In Firefox, if a div is positioned by percentage, its pixel position // may land between pixels. The container itself doesn't display this, // but an SVG element inside this container will be drawn at subpixel // precision. In order to draw sharp lines, this must be compensated // for. This doesn't seem to work inside iframes though (like in // jsFiddle). var subPixelFix, rect; if (isFirefox && container.getBoundingClientRect) { subPixelFix = function () { css(container, { left: 0, top: 0 }); rect = container.getBoundingClientRect(); css(container, { left: (Math.ceil(rect.left) - rect.left) + 'px', top: (Math.ceil(rect.top) - rect.top) + 'px' }); }; // run the fix now subPixelFix(); // run it on resize renderer.unSubPixelFix = addEvent(win, 'resize', subPixelFix); } }, /** * General method for adding a definition to the SVG `defs` tag. Can be used * for gradients, fills, filters etc. Styled mode only. A hook for adding * general definitions to the SVG's defs tag. Definitions can be referenced * from the CSS by its `id`. Read more in * [gradients, shadows and patterns](https://www.highcharts.com/docs/chart-design-and-style/gradients-shadows-and-patterns). * Styled mode only. * * @function Highcharts.SVGRenderer#definition * * @param {Highcharts.SVGDefinitionObject} def * A serialized form of an SVG definition, including children. * * @return {Highcharts.SVGElement} * The inserted node. */ definition: function (def) { var ren = this; function recurse(config, parent) { var ret; splat(config).forEach(function (item) { var node = ren.createElement(item.tagName), attr = {}; // Set attributes objectEach(item, function (val, key) { if ( key !== 'tagName' && key !== 'children' && key !== 'textContent' ) { attr[key] = val; } }); node.attr(attr); // Add to the tree node.add(parent || ren.defs); // Add text content if (item.textContent) { node.element.appendChild( doc.createTextNode(item.textContent) ); } // Recurse recurse(item.children || [], node); ret = node; }); // Return last node added (on top level it's the only one) return ret; } return recurse(def); }, /** * Get the global style setting for the renderer. * * @private * @function Highcharts.SVGRenderer#getStyle * * @param {Highcharts.CSSObject} style * Style settings. * * @return {Highcharts.CSSObject} * The style settings mixed with defaults. */ getStyle: function (style) { this.style = extend({ fontFamily: '"Lucida Grande", "Lucida Sans Unicode", ' + 'Arial, Helvetica, sans-serif', fontSize: '12px' }, style); return this.style; }, /** * Apply the global style on the renderer, mixed with the default styles. * * @function Highcharts.SVGRenderer#setStyle * * @param {Highcharts.CSSObject} style * CSS to apply. */ setStyle: function (style) { this.boxWrapper.css(this.getStyle(style)); }, /** * Detect whether the renderer is hidden. This happens when one of the * parent elements has `display: none`. Used internally to detect when we * needto render preliminarily in another div to get the text bounding boxes * right. * * @function Highcharts.SVGRenderer#isHidden * * @return {boolean} * True if it is hidden. */ isHidden: function () { // #608 return !this.boxWrapper.getBBox().width; }, /** * Destroys the renderer and its allocated members. * * @function Highcharts.SVGRenderer#destroy */ destroy: function () { var renderer = this, rendererDefs = renderer.defs; renderer.box = null; renderer.boxWrapper = renderer.boxWrapper.destroy(); // Call destroy on all gradient elements destroyObjectProperties(renderer.gradients || {}); renderer.gradients = null; // Defs are null in VMLRenderer // Otherwise, destroy them here. if (rendererDefs) { renderer.defs = rendererDefs.destroy(); } // Remove sub pixel fix handler (#982) if (renderer.unSubPixelFix) { renderer.unSubPixelFix(); } renderer.alignedObjects = null; return null; }, /** * Create a wrapper for an SVG element. Serves as a factory for * {@link SVGElement}, but this function is itself mostly called from * primitive factories like {@link SVGRenderer#path}, {@link * SVGRenderer#rect} or {@link SVGRenderer#text}. * * @function Highcharts.SVGRenderer#createElement * * @param {string} nodeName * The node name, for example `rect`, `g` etc. * * @return {Highcharts.SVGElement} * The generated SVGElement. */ createElement: function (nodeName) { var wrapper = new this.Element(); wrapper.init(this, nodeName); return wrapper; }, /** * Dummy function for plugins, called every time the renderer is updated. * Prior to Highcharts 5, this was used for the canvg renderer. * * @deprecated * @function Highcharts.SVGRenderer#draw */ draw: noop, /** * Get converted radial gradient attributes according to the radial * reference. Used internally from the {@link SVGElement#colorGradient} * function. * * @private * @function Highcharts.SVGRenderer#getRadialAttr * * @param {Array<number>} radialReference * * @param {Highcharts.SVGAttributes} gradAttr * * @return {Highcharts.SVGAttributes} */ getRadialAttr: function (radialReference, gradAttr) { return { cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2], cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2], r: gradAttr.r * radialReference[2] }; }, /** * Truncate the text node contents to a given length. Used when the css * width is set. If the `textOverflow` is `ellipsis`, the text is truncated * character by character to the given length. If not, the text is * word-wrapped line by line. * * @private * @function Highcharts.SVGRenderer#truncate * * @param {Highcharts.SVGElement} wrapper * * @param {Highcharts.SVGDOMElement} tspan * * @param {string} text * * @param {Array.<string>} words * * @param {number} width * * @param {Function} getString * * @return {boolean} * True if tspan is too long. */ truncate: function ( wrapper, tspan, text, words, startAt, width, getString ) { var renderer = this, rotation = wrapper.rotation, str, // Word wrap can not be truncated to shorter than one word, ellipsis // text can be completely blank. minIndex = words ? 1 : 0, maxIndex = (text || words).length, currentIndex = maxIndex, // Cache the lengths to avoid checking the same twice lengths = [], updateTSpan = function (s) { if (tspan.firstChild) { tspan.removeChild(tspan.firstChild); } if (s) { tspan.appendChild(doc.createTextNode(s)); } }, getSubStringLength = function (charEnd, concatenatedEnd) { // charEnd is useed when finding the character-by-character // break for ellipsis, concatenatedEnd is used for word-by-word // break for word wrapping. var end = concatenatedEnd || charEnd; if (lengths[end] === undefined) { // Modern browsers if (tspan.getSubStringLength) { // Fails with DOM exception on unit-tests/legend/members // of unknown reason. Desired width is 0, text content // is "5" and end is 1. try { lengths[end] = startAt + tspan.getSubStringLength( 0, words ? end + 1 : end ); } catch (e) {} // Legacy } else if (renderer.getSpanWidth) { // #9058 jsdom updateTSpan(getString(text || words, charEnd)); lengths[end] = startAt + renderer.getSpanWidth(wrapper, tspan); } } return lengths[end]; }, actualWidth, truncated; wrapper.rotation = 0; // discard rotation when computing box actualWidth = getSubStringLength(tspan.textContent.length); truncated = startAt + actualWidth > width; if (truncated) { // Do a binary search for the index where to truncate the text while (minIndex <= maxIndex) { currentIndex = Math.ceil((minIndex + maxIndex) / 2); // When checking words for word-wrap, we need to build the // string and measure the subStringLength at the concatenated // word length. if (words) { str = getString(words, currentIndex); } actualWidth = getSubStringLength( currentIndex, str && str.length - 1 ); if (minIndex === maxIndex) { // Complete minIndex = maxIndex + 1; } else if (actualWidth > width) { // Too large. Set max index to current. maxIndex = currentIndex - 1; } else { // Within width. Set min index to current. minIndex = currentIndex; } } // If max index was 0 it means the shortest possible text was also // too large. For ellipsis that means only the ellipsis, while for // word wrap it means the whole first word. if (maxIndex === 0) { // Remove ellipsis updateTSpan(''); // If the new text length is one less than the original, we don't // need the ellipsis } else if (!(text && maxIndex === text.length - 1)) { updateTSpan(str || getString(text || words, currentIndex)); } } // When doing line wrapping, prepare for the next line by removing the // items from this line. if (words) { words.splice(0, currentIndex); } wrapper.actualWidth = actualWidth; wrapper.rotation = rotation; // Apply rotation again. return truncated; }, /** * A collection of characters mapped to HTML entities. When `useHTML` on an * element is true, these entities will be rendered correctly by HTML. In * the SVG pseudo-HTML, they need to be unescaped back to simple characters, * so for example `&lt;` will render as `<`. * * @example * // Add support for unescaping quotes * Highcharts.SVGRenderer.prototype.escapes['"'] = '&quot;'; * * @name Highcharts.SVGRenderer#escapes * @type {Highcharts.Dictionary<string>} */ escapes: { '&': '&amp;', '<': '&lt;', '>': '&gt;', "'": '&#39;', // eslint-disable-line quotes '"': '&quot;' }, /** * Parse a simple HTML string into SVG tspans. Called internally when text * is set on an SVGElement. The function supports a subset of HTML tags, CSS * text features like `width`, `text-overflow`, `white-space`, and also * attributes like `href` and `style`. * * @private * @function Highcharts.SVGRenderer#buildText * * @param {Highcharts.SVGElement} wrapper * The parent SVGElement. */ buildText: function (wrapper) { var textNode = wrapper.element, renderer = this, forExport = renderer.forExport, textStr = pick(wrapper.textStr, '').toString(), hasMarkup = textStr.indexOf('<') !== -1, lines, childNodes = textNode.childNodes, truncated, parentX = attr(textNode, 'x'), textStyles = wrapper.styles, width = wrapper.textWidth, textLineHeight = textStyles && textStyles.lineHeight, textOutline = textStyles && textStyles.textOutline, ellipsis = textStyles && textStyles.textOverflow === 'ellipsis', noWrap = textStyles && textStyles.whiteSpace === 'nowrap', fontSize = textStyles && textStyles.fontSize, textCache, isSubsequentLine, i = childNodes.length, tempParent = width && !wrapper.added && this.box, getLineHeight = function (tspan) { var fontSizeStyle; if (!renderer.styledMode) { fontSizeStyle = /(px|em)$/.test(tspan && tspan.style.fontSize) ? tspan.style.fontSize : (fontSize || renderer.style.fontSize || 12); } return textLineHeight ? pInt(textLineHeight) : renderer.fontMetrics( fontSizeStyle, // Get the computed size from parent if not explicit tspan.getAttribute('style') ? tspan : textNode ).h; }, unescapeEntities = function (inputStr, except) { objectEach(renderer.escapes, function (value, key) { if (!except || except.indexOf(value) === -1) { inputStr = inputStr.toString().replace( new RegExp(value, 'g'), // eslint-disable-line security/detect-non-literal-regexp key ); } }); return inputStr; }, parseAttribute = function (s, attr) { var start, delimiter; start = s.indexOf('<'); s = s.substring(start, s.indexOf('>') - start); start = s.indexOf(attr + '='); if (start !== -1) { start = start + attr.length + 1; delimiter = s.charAt(start); if (delimiter === '"' || delimiter === "'") { // eslint-disable-line quotes s = s.substring(start + 1); return s.substring(0, s.indexOf(delimiter)); } } }; // The buildText code is quite heavy, so if we're not changing something // that affects the text, skip it (#6113). textCache = [ textStr, ellipsis, noWrap, textLineHeight, textOutline, fontSize, width ].join(','); if (textCache === wrapper.textCache) { return; } wrapper.textCache = textCache; // Remove old text while (i--) { textNode.removeChild(childNodes[i]); } // Skip tspans, add text directly to text node. The forceTSpan is a hook // used in text outline hack. if ( !hasMarkup && !textOutline && !ellipsis && !width && textStr.indexOf(' ') === -1 ) { textNode.appendChild(doc.createTextNode(unescapeEntities(textStr))); // Complex strings, add more logic } else { if (tempParent) { // attach it to the DOM to read offset width tempParent.appendChild(textNode); } if (hasMarkup) { lines = renderer.styledMode ? ( textStr.replace( /<(b|strong)>/g, '<span class="highcharts-strong">' ) .replace( /<(i|em)>/g, '<span class="highcharts-emphasized">' ) ) : ( textStr .replace( /<(b|strong)>/g, '<span style="font-weight:bold">' ) .replace( /<(i|em)>/g, '<span style="font-style:italic">' ) ); lines = lines .replace(/<a/g, '<span') .replace(/<\/(b|strong|i|em|a)>/g, '</span>') .split(/<br.*?>/g); } else { lines = [textStr]; } // Trim empty lines (#5261) lines = lines.filter(function (line) { return line !== ''; }); // build the lines lines.forEach(function buildTextLines(line, lineNo) { var spans, spanNo = 0, lineLength = 0; line = line // Trim to prevent useless/costly process on the spaces // (#5258) .replace(/^\s+|\s+$/g, '') .replace(/<span/g, '|||<span') .replace(/<\/span>/g, '</span>|||'); spans = line.split('|||'); spans.forEach(function buildTextSpans(span) { if (span !== '' || spans.length === 1) { var attributes = {}, tspan = doc.createElementNS( renderer.SVG_NS, 'tspan' ), classAttribute, styleAttribute, // #390 hrefAttribute; classAttribute = parseAttribute(span, 'class'); if (classAttribute) { attr(tspan, 'class', classAttribute); } styleAttribute = parseAttribute(span, 'style'); if (styleAttribute) { styleAttribute = styleAttribute.replace( /(;| |^)color([ :])/, '$1fill$2' ); attr(tspan, 'style', styleAttribute); } // Not for export - #1529 hrefAttribute = parseAttribute(span, 'href'); if (hrefAttribute && !forExport) { attr( tspan, 'onclick', 'location.href=\"' + hrefAttribute + '\"' ); attr(tspan, 'class', 'highcharts-anchor'); if (!renderer.styledMode) { css(tspan, { cursor: 'pointer' }); } } // Strip away unsupported HTML tags (#7126) span = unescapeEntities( span.replace(/<[a-zA-Z\/](.|\n)*?>/g, '') || ' ' ); // Nested tags aren't supported, and cause crash in // Safari (#1596) if (span !== ' ') { // add the text node tspan.appendChild(doc.createTextNode(span)); // First span in a line, align it to the left if (!spanNo) { if (lineNo && parentX !== null) { attributes.x = parentX; } } else { attributes.dx = 0; // #16 } // add attributes attr(tspan, attributes); // Append it textNode.appendChild(tspan); // first span on subsequent line, add the line // height if (!spanNo && isSubsequentLine) { // allow getting the right offset height in // exporting in IE if (!svg && forExport) { css(tspan, { display: 'block' }); } // Set the line height based on the font size of // either the text element or the tspan element attr( tspan, 'dy', getLineHeight(tspan) ); } // Check width and apply soft breaks or ellipsis if (width) { var words = span.replace( /([^\^])-/g, '$1- ' ).split(' '), // #1273 hasWhiteSpace = !noWrap && ( spans.length > 1 || lineNo || words.length > 1 ), wrapLineNo = 0, dy = getLineHeight(tspan); if (ellipsis) { truncated = renderer.truncate( wrapper, tspan, span, undefined, 0, // Target width Math.max( 0, // Substract the font face to make // room for the ellipsis itself width - parseInt(fontSize || 12, 10) ), // Build the text to test for function (text, currentIndex) { return text.substring( 0, currentIndex ) + '\u2026'; } ); } else if (hasWhiteSpace) { while (words.length) { // For subsequent lines, create tspans // with the same style attributes as the // parent text node. if ( words.length && !noWrap && wrapLineNo > 0 ) { tspan = doc.createElementNS( SVG_NS, 'tspan' ); attr(tspan, { dy: dy, x: parentX }); if (styleAttribute) { // #390 attr( tspan, 'style', styleAttribute ); } // Start by appending the full // remaining text tspan.appendChild( doc.createTextNode( words.join(' ') .replace(/- /g, '-') ) ); textNode.appendChild(tspan); } // For each line, truncate the remaining // words into the line length. renderer.truncate( wrapper, tspan, null, words, wrapLineNo === 0 ? lineLength : 0, width, // Build the text to test for function (text, currentIndex) { return words .slice(0, currentIndex) .join(' ') .replace(/- /g, '-'); } ); lineLength = wrapper.actualWidth; wrapLineNo++; } } } spanNo++; } } }); // To avoid beginning lines that doesn't add to the textNode // (#6144) isSubsequentLine = ( isSubsequentLine || textNode.childNodes.length ); }); if (ellipsis && truncated) { wrapper.attr( 'title', unescapeEntities(wrapper.textStr, ['&lt;', '&gt;']) // #7179 ); } if (tempParent) { tempParent.removeChild(textNode); } // Apply the text outline if (textOutline && wrapper.applyTextOutline) { wrapper.applyTextOutline(textOutline); } } }, /** * Returns white for dark colors and black for bright colors. * * @function Highcharts.SVGRenderer#getContrast * * @param {Highcharts.ColorString} rgba * The color to get the contrast for. * * @return {string} * The contrast color, either `#000000` or `#FFFFFF`. */ getContrast: function (rgba) { rgba = color(rgba).rgba; // The threshold may be discussed. Here's a proposal for adding // different weight to the color channels (#6216) rgba[0] *= 1; // red rgba[1] *= 1.2; // green rgba[2] *= 0.5; // blue return rgba[0] + rgba[1] + rgba[2] > 1.8 * 255 ? '#000000' : '#FFFFFF'; }, /** * Create a button with preset states. * * @function Highcharts.SVGRenderer#button * * @param {string} text * The text or HTML to draw. * * @param {number} x * The x position of the button's left side. * * @param {number} y * The y position of the button's top side. * * @param {Function} callback * The function to execute on button click or touch. * * @param {Highcharts.SVGAttributes} [normalState] * SVG attributes for the normal state. * * @param {Highcharts.SVGAttributes} [hoverState] * SVG attributes for the hover state. * * @param {Highcharts.SVGAttributes} [pressedState] * SVG attributes for the pressed state. * * @param {Highcharts.SVGAttributes} [disabledState] * SVG attributes for the disabled state. * * @param {Highcharts.SymbolKey} [shape=rect] * The shape type. * * @return {Highcharts.SVGElement} * The button element. */ button: function ( text, x, y, callback, normalState, hoverState, pressedState, disabledState, shape ) { var label = this.label( text, x, y, shape, null, null, null, null, 'button' ), curState = 0, styledMode = this.styledMode; // Default, non-stylable attributes label.attr(merge({ 'padding': 8, 'r': 2 }, normalState)); if (!styledMode) { // Presentational var normalStyle, hoverStyle, pressedStyle, disabledStyle; // Normal state - prepare the attributes normalState = merge({ fill: '#f7f7f7', stroke: '#cccccc', 'stroke-width': 1, style: { color: '#333333', cursor: 'pointer', fontWeight: 'normal' } }, normalState); normalStyle = normalState.style; delete normalState.style; // Hover state hoverState = merge(normalState, { fill: '#e6e6e6' }, hoverState); hoverStyle = hoverState.style; delete hoverState.style; // Pressed state pressedState = merge(normalState, { fill: '#e6ebf5', style: { color: '#000000', fontWeight: 'bold' } }, pressedState); pressedStyle = pressedState.style; delete pressedState.style; // Disabled state disabledState = merge(normalState, { style: { color: '#cccccc' } }, disabledState); disabledStyle = disabledState.style; delete disabledState.style; } // Add the events. IE9 and IE10 need mouseover and mouseout to funciton // (#667). addEvent(label.element, isMS ? 'mouseover' : 'mouseenter', function () { if (curState !== 3) { label.setState(1); } }); addEvent(label.element, isMS ? 'mouseout' : 'mouseleave', function () { if (curState !== 3) { label.setState(curState); } }); label.setState = function (state) { // Hover state is temporary, don't record it if (state !== 1) { label.state = curState = state; } // Update visuals label.removeClass( /highcharts-button-(normal|hover|pressed|disabled)/ ) .addClass( 'highcharts-button-' + ['normal', 'hover', 'pressed', 'disabled'][state || 0] ); if (!styledMode) { label.attr([ normalState, hoverState, pressedState, disabledState ][state || 0]) .css([ normalStyle, hoverStyle, pressedStyle, disabledStyle ][state || 0]); } }; // Presentational attributes if (!styledMode) { label .attr(normalState) .css(extend({ cursor: 'default' }, normalStyle)); } return label .on('click', function (e) { if (curState !== 3) { callback.call(label, e); } }); }, /** * Make a straight line crisper by not spilling out to neighbour pixels. * * @function Highcharts.SVGRenderer#crispLine * * @param {Highcharts.SVGPathArray} points * The original points on the format `['M', 0, 0, 'L', 100, 0]`. * * @param {number} width * The width of the line. * * @return {Highcharts.SVGPathArray} * The original points array, but modified to render crisply. */ crispLine: function (points, width) { // normalize to a crisp line if (points[1] === points[4]) { // Substract due to #1129. Now bottom and left axis gridlines behave // the same. points[1] = points[4] = Math.round(points[1]) - (width % 2 / 2); } if (points[2] === points[5]) { points[2] = points[5] = Math.round(points[2]) + (width % 2 / 2); } return points; }, /** * Draw a path, wraps the SVG `path` element. * * @sample highcharts/members/renderer-path-on-chart/ * Draw a path in a chart * @sample highcharts/members/renderer-path/ * Draw a path independent from a chart * * @example * var path = renderer.path(['M', 10, 10, 'L', 30, 30, 'z']) * .attr({ stroke: '#ff00ff' }) * .add(); * * @function Highcharts.SVGRenderer#path * * @param {Highcharts.SVGPathArray} [path] * An SVG path definition in array form. * * @return {Highcharts.SVGElement} * The generated wrapper element. * *//** * Draw a path, wraps the SVG `path` element. * * @function Highcharts.SVGRenderer#path * * @param {Highcharts.SVGAttributes} [attribs] * The initial attributes. * * @return {Highcharts.SVGElement} * The generated wrapper element. */ path: function (path) { var attribs = this.styledMode ? {} : { fill: 'none' }; if (isArray(path)) { attribs.d = path; } else if (isObject(path)) { // attributes extend(attribs, path); } return this.createElement('path').attr(attribs); }, /** * Draw a circle, wraps the SVG `circle` element. * * @sample highcharts/members/renderer-circle/ * Drawing a circle * * @function Highcharts.SVGRenderer#circle * * @param {number} [x] * The center x position. * * @param {number} [y] * The center y position. * * @param {number} [r] * The radius. * * @return {Highcharts.SVGElement} * The generated wrapper element. *//** * Draw a circle, wraps the SVG `circle` element. * * @function Highcharts.SVGRenderer#circle * * @param {Highcharts.SVGAttributes} [attribs] * The initial attributes. * * @return {Highcharts.SVGElement} * The generated wrapper element. */ circle: function (x, y, r) { var attribs = ( isObject(x) ? x : x === undefined ? {} : { x: x, y: y, r: r } ), wrapper = this.createElement('circle'); // Setting x or y translates to cx and cy wrapper.xSetter = wrapper.ySetter = function (value, key, element) { element.setAttribute('c' + key, value); }; return wrapper.attr(attribs); }, /** * Draw and return an arc. * * @sample highcharts/members/renderer-arc/ * Drawing an arc * * @function Highcharts.SVGRenderer#arc * * @param {number} [x=0] * Center X position. * * @param {number} [y=0] * Center Y position. * * @param {number} [r=0] * The outer radius of the arc. * * @param {number} [innerR=0] * Inner radius like used in donut charts. * * @param {number} [start=0] * The starting angle of the arc in radians, where 0 is to the right * and `-Math.PI/2` is up. * * @param {number} [end=0] * The ending angle of the arc in radians, where 0 is to the right * and `-Math.PI/2` is up. * * @return {Highcharts.SVGElement} * The generated wrapper element. *//** * Draw and return an arc. Overloaded function that takes arguments object. * * @function Highcharts.SVGRenderer#arc * * @param {Highcharts.SVGAttributes} attribs * Initial SVG attributes. * * @return {Highcharts.SVGElement} * The generated wrapper element. */ arc: function (x, y, r, innerR, start, end) { var arc, options; if (isObject(x)) { options = x; y = options.y; r = options.r; innerR = options.innerR; start = options.start; end = options.end; x = options.x; } else { options = { innerR: innerR, start: start, end: end }; } // Arcs are defined as symbols for the ability to set // attributes in attr and animate arc = this.symbol('arc', x, y, r, r, options); arc.r = r; // #959 return arc; }, /** * Draw and return a rectangle. * * @function Highcharts.SVGRenderer#rect * * @param {number} [x] * Left position. * * @param {number} [y] * Top position. * * @param {number} [width] * Width of the rectangle. * * @param {number} [height] * Height of the rectangle. * * @param {number} [r] * Border corner radius. * * @param {number} [strokeWidth] * A stroke width can be supplied to allow crisp drawing. * * @return {Highcharts.SVGElement} * The generated wrapper element. *//** * Draw and return a rectangle. * * @sample highcharts/members/renderer-rect-on-chart/ * Draw a rectangle in a chart * @sample highcharts/members/renderer-rect/ * Draw a rectangle independent from a chart * * @function Highcharts.SVGRenderer#rect * * @param {Highcharts.SVGAttributes} [attributes] * General SVG attributes for the rectangle. * * @return {Highcharts.SVGElement} * The generated wrapper element. */ rect: function (x, y, width, height, r, strokeWidth) { r = isObject(x) ? x.r : r; var wrapper = this.createElement('rect'), attribs = isObject(x) ? x : x === undefined ? {} : { x: x, y: y, width: Math.max(width, 0), height: Math.max(height, 0) }; if (!this.styledMode) { if (strokeWidth !== undefined) { attribs.strokeWidth = strokeWidth; attribs = wrapper.crisp(attribs); } attribs.fill = 'none'; } if (r) { attribs.r = r; } wrapper.rSetter = function (value, key, element) { attr(element, { rx: value, ry: value }); }; return wrapper.attr(attribs); }, /** * Resize the {@link SVGRenderer#box} and re-align all aligned child * elements. * * @sample highcharts/members/renderer-g/ * Show and hide grouped objects * * @function Highcharts.SVGRenderer#setSize * * @param {number} width * The new pixel width. * * @param {number} height * The new pixel height. * * @param {boolean|Highcharts.AnimationOptionsObject} [animate=true] * Whether and how to animate. */ setSize: function (width, height, animate) { var renderer = this, alignedObjects = renderer.alignedObjects, i = alignedObjects.length; renderer.width = width; renderer.height = height; renderer.boxWrapper.animate({ width: width, height: height }, { step: function () { this.attr({ viewBox: '0 0 ' + this.attr('width') + ' ' + this.attr('height') }); }, duration: pick(animate, true) ? undefined : 0 }); while (i--) { alignedObjects[i].align(); } }, /** * Create and return an svg group element. Child * {@link Highcharts.SVGElement} objects are added to the group by using the * group as the first parameter in {@link Highcharts.SVGElement#add|add()}. * * @function Highcharts.SVGRenderer#g * * @param {string} [name] * The group will be given a class name of `highcharts-{name}`. This * can be used for styling and scripting. * * @return {Highcharts.SVGElement} * The generated wrapper element. */ g: function (name) { var elem = this.createElement('g'); return name ? elem.attr({ 'class': 'highcharts-' + name }) : elem; }, /** * Display an image. * * @sample highcharts/members/renderer-image-on-chart/ * Add an image in a chart * @sample highcharts/members/renderer-image/ * Add an image independent of a chart * * @function Highcharts.SVGRenderer#image * * @param {string} src * The image source. * * @param {number} [x] * The X position. * * @param {number} [y] * The Y position. * * @param {number} [width] * The image width. If omitted, it defaults to the image file width. * * @param {number} [height] * The image height. If omitted it defaults to the image file * height. * * @param {Function} [onload] * Event handler for image load. * * @return {Highcharts.SVGElement} * The generated wrapper element. */ image: function (src, x, y, width, height, onload) { var attribs = { preserveAspectRatio: 'none' }, elemWrapper, dummy, setSVGImageSource = function (el, src) { // Set the href in the xlink namespace if (el.setAttributeNS) { el.setAttributeNS( 'http://www.w3.org/1999/xlink', 'href', src ); } else { // could be exporting in IE // using href throws "not supported" in ie7 and under, // requries regex shim to fix later el.setAttribute('hc-svg-href', src); } }, onDummyLoad = function (e) { setSVGImageSource(elemWrapper.element, src); onload.call(elemWrapper, e); }; // optional properties if (arguments.length > 1) { extend(attribs, { x: x, y: y, width: width, height: height }); } elemWrapper = this.createElement('image').attr(attribs); // Add load event if supplied if (onload) { // We have to use a dummy HTML image since IE support for SVG image // load events is very buggy. First set a transparent src, wait for // dummy to load, and then add the real src to the SVG image. setSVGImageSource( elemWrapper.element, 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==' /* eslint-disable-line */ ); dummy = new win.Image(); addEvent(dummy, 'load', onDummyLoad); dummy.src = src; if (dummy.complete) { onDummyLoad({}); } } else { setSVGImageSource(elemWrapper.element, src); } return elemWrapper; }, /** * Draw a symbol out of pre-defined shape paths from * {@link SVGRenderer#symbols}. * It is used in Highcharts for point makers, which cake a `symbol` option, * and label and button backgrounds like in the tooltip and stock flags. * * @function Highcharts.SVGRenderer#symbol * * @param {symbol} symbol * The symbol name. * * @param {number} x * The X coordinate for the top left position. * * @param {number} y * The Y coordinate for the top left position. * * @param {number} width * The pixel width. * * @param {number} height * The pixel height. * * @param {Highcharts.SymbolOptionsObject} [options] * Additional options, depending on the actual symbol drawn. * * @return {Highcharts.SVGElement} */ symbol: function (symbol, x, y, width, height, options) { var ren = this, obj, imageRegex = /^url\((.*?)\)$/, isImage = imageRegex.test(symbol), sym = !isImage && (this.symbols[symbol] ? symbol : 'circle'), // get the symbol definition function symbolFn = sym && this.symbols[sym], // check if there's a path defined for this symbol path = defined(x) && symbolFn && symbolFn.call( this.symbols, Math.round(x), Math.round(y), width, height, options ), imageSrc, centerImage; if (symbolFn) { obj = this.path(path); if (!ren.styledMode) { obj.attr('fill', 'none'); } // expando properties for use in animate and attr extend(obj, { symbolName: sym, x: x, y: y, width: width, height: height }); if (options) { extend(obj, options); } // Image symbols } else if (isImage) { imageSrc = symbol.match(imageRegex)[1]; // Create the image synchronously, add attribs async obj = this.image(imageSrc); // The image width is not always the same as the symbol width. The // image may be centered within the symbol, as is the case when // image shapes are used as label backgrounds, for example in flags. obj.imgwidth = pick( symbolSizes[imageSrc] && symbolSizes[imageSrc].width, options && options.width ); obj.imgheight = pick( symbolSizes[imageSrc] && symbolSizes[imageSrc].height, options && options.height ); /** * Set the size and position */ centerImage = function () { obj.attr({ width: obj.width, height: obj.height }); }; /** * Width and height setters that take both the image's physical size * and the label size into consideration, and translates the image * to center within the label. */ ['width', 'height'].forEach(function (key) { obj[key + 'Setter'] = function (value, key) { var attribs = {}, imgSize = this['img' + key], trans = key === 'width' ? 'translateX' : 'translateY'; this[key] = value; if (defined(imgSize)) { if (this.element) { this.element.setAttribute(key, imgSize); } if (!this.alignByTranslate) { attribs[trans] = ((this[key] || 0) - imgSize) / 2; this.attr(attribs); } } }; }); if (defined(x)) { obj.attr({ x: x, y: y }); } obj.isImg = true; if (defined(obj.imgwidth) && defined(obj.imgheight)) { centerImage(); } else { // Initialize image to be 0 size so export will still function // if there's no cached sizes. obj.attr({ width: 0, height: 0 }); // Create a dummy JavaScript image to get the width and height. createElement('img', { onload: function () { var chart = charts[ren.chartIndex]; // Special case for SVGs on IE11, the width is not // accessible until the image is part of the DOM // (#2854). if (this.width === 0) { css(this, { position: 'absolute', top: '-999em' }); doc.body.appendChild(this); } // Center the image symbolSizes[imageSrc] = { // Cache for next width: this.width, height: this.height }; obj.imgwidth = this.width; obj.imgheight = this.height; if (obj.element) { centerImage(); } // Clean up after #2854 workaround. if (this.parentNode) { this.parentNode.removeChild(this); } // Fire the load event when all external images are // loaded ren.imgCount--; if (!ren.imgCount && chart && chart.onload) { chart.onload(); } }, src: imageSrc }); this.imgCount++; } } return obj; }, /** * An extendable collection of functions for defining symbol paths. * * @name Highcharts.SVGRenderer#symbols * @type {Highcharts.SymbolDictionary} */ symbols: { 'circle': function (x, y, w, h) { // Return a full arc return this.arc(x + w / 2, y + h / 2, w / 2, h / 2, { start: 0, end: Math.PI * 2, open: false }); }, 'square': function (x, y, w, h) { return [ 'M', x, y, 'L', x + w, y, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle': function (x, y, w, h) { return [ 'M', x + w / 2, y, 'L', x + w, y + h, x, y + h, 'Z' ]; }, 'triangle-down': function (x, y, w, h) { return [ 'M', x, y, 'L', x + w, y, x + w / 2, y + h, 'Z' ]; }, 'diamond': function (x, y, w, h) { return [ 'M', x + w / 2, y, 'L', x + w, y + h / 2, x + w / 2, y + h, x, y + h / 2, 'Z' ]; }, 'arc': function (x, y, w, h, options) { var start = options.start, rx = options.r || w, ry = options.r || h || w, proximity = 0.001, fullCircle = Math.abs(options.end - options.start - 2 * Math.PI) < proximity, // Substract a small number to prevent cos and sin of start and // end from becoming equal on 360 arcs (related: #1561) end = options.end - proximity, innerRadius = options.innerR, open = pick(options.open, fullCircle), cosStart = Math.cos(start), sinStart = Math.sin(start), cosEnd = Math.cos(end), sinEnd = Math.sin(end), // Proximity takes care of rounding errors around PI (#6971) longArc = options.end - start - Math.PI < proximity ? 0 : 1, arc; arc = [ 'M', x + rx * cosStart, y + ry * sinStart, 'A', // arcTo rx, // x radius ry, // y radius 0, // slanting longArc, // long or short arc 1, // clockwise x + rx * cosEnd, y + ry * sinEnd ]; if (defined(innerRadius)) { arc.push( open ? 'M' : 'L', x + innerRadius * cosEnd, y + innerRadius * sinEnd, 'A', // arcTo innerRadius, // x radius innerRadius, // y radius 0, // slanting longArc, // long or short arc 0, // clockwise x + innerRadius * cosStart, y + innerRadius * sinStart ); } arc.push(open ? '' : 'Z'); // close return arc; }, /** * Callout shape used for default tooltips, also used for rounded * rectangles in VML */ 'callout': function (x, y, w, h, options) { var arrowLength = 6, halfDistance = 6, r = Math.min((options && options.r) || 0, w, h), safeDistance = r + halfDistance, anchorX = options && options.anchorX, anchorY = options && options.anchorY, path; path = [ 'M', x + r, y, 'L', x + w - r, y, // top side 'C', x + w, y, x + w, y, x + w, y + r, // top-right corner 'L', x + w, y + h - r, // right side 'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-rgt 'L', x + r, y + h, // bottom side 'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner 'L', x, y + r, // left side 'C', x, y, x, y, x + r, y // top-left corner ]; // Anchor on right side if (anchorX && anchorX > w) { // Chevron if ( anchorY > y + safeDistance && anchorY < y + h - safeDistance ) { path.splice(13, 3, 'L', x + w, anchorY - halfDistance, x + w + arrowLength, anchorY, x + w, anchorY + halfDistance, x + w, y + h - r ); // Simple connector } else { path.splice(13, 3, 'L', x + w, h / 2, anchorX, anchorY, x + w, h / 2, x + w, y + h - r ); } // Anchor on left side } else if (anchorX && anchorX < 0) { // Chevron if ( anchorY > y + safeDistance && anchorY < y + h - safeDistance ) { path.splice(33, 3, 'L', x, anchorY + halfDistance, x - arrowLength, anchorY, x, anchorY - halfDistance, x, y + r ); // Simple connector } else { path.splice(33, 3, 'L', x, h / 2, anchorX, anchorY, x, h / 2, x, y + r ); } } else if ( // replace bottom anchorY && anchorY > h && anchorX > x + safeDistance && anchorX < x + w - safeDistance ) { path.splice(23, 3, 'L', anchorX + halfDistance, y + h, anchorX, y + h + arrowLength, anchorX - halfDistance, y + h, x + r, y + h ); } else if ( // replace top anchorY && anchorY < 0 && anchorX > x + safeDistance && anchorX < x + w - safeDistance ) { path.splice(3, 3, 'L', anchorX - halfDistance, y, anchorX, y - arrowLength, anchorX + halfDistance, y, w - r, y ); } return path; } }, /** * Define a clipping rectangle. The clipping rectangle is later applied * to {@link SVGElement} objects through the {@link SVGElement#clip} * function. * * @example * var circle = renderer.circle(100, 100, 100) * .attr({ fill: 'red' }) * .add(); * var clipRect = renderer.clipRect(100, 100, 100, 100); * * // Leave only the lower right quarter visible * circle.clip(clipRect); * * @function Highcharts.SVGRenderer#clipRect * * @param {string} id * * @param {number} x * * @param {number} y * * @param {number} width * * @param {number} height * * @return {Highcharts.ClipRectElement} * A clipping rectangle. */ clipRect: function (x, y, width, height) { var wrapper, id = H.uniqueKey(), clipPath = this.createElement('clipPath').attr({ id: id }).add(this.defs); wrapper = this.rect(x, y, width, height, 0).add(clipPath); wrapper.id = id; wrapper.clipPath = clipPath; wrapper.count = 0; return wrapper; }, /** * Draw text. The text can contain a subset of HTML, like spans and anchors * and some basic text styling of these. For more advanced features like * border and background, use {@link Highcharts.SVGRenderer#label} instead. * To update the text after render, run `text.attr({ text: 'New text' })`. * * @sample highcharts/members/renderer-text-on-chart/ * Annotate the chart freely * @sample highcharts/members/renderer-on-chart/ * Annotate with a border and in response to the data * @sample highcharts/members/renderer-text/ * Formatted text * * @function Highcharts.SVGRenderer#text * * @param {string} str * The text of (subset) HTML to draw. * * @param {number} x * The x position of the text's lower left corner. * * @param {number} y * The y position of the text's lower left corner. * * @param {boolean} [useHTML=false] * Use HTML to render the text. * * @return {Highcharts.SVGElement} * The text object. */ text: function (str, x, y, useHTML) { // declare variables var renderer = this, wrapper, attribs = {}; if (useHTML && (renderer.allowHTML || !renderer.forExport)) { return renderer.html(str, x, y); } attribs.x = Math.round(x || 0); // X always needed for line-wrap logic if (y) { attribs.y = Math.round(y); } if (defined(str)) { attribs.text = str; } wrapper = renderer.createElement('text') .attr(attribs); if (!useHTML) { wrapper.xSetter = function (value, key, element) { var tspans = element.getElementsByTagName('tspan'), tspan, parentVal = element.getAttribute(key), i; for (i = 0; i < tspans.length; i++) { tspan = tspans[i]; // If the x values are equal, the tspan represents a // linebreak if (tspan.getAttribute(key) === parentVal) { tspan.setAttribute(key, value); } } element.setAttribute(key, value); }; } return wrapper; }, /** * Utility to return the baseline offset and total line height from the font * size. * * @function Highcharts.SVGRenderer#fontMetrics * * @param {string} [fontSize] * The current font size to inspect. If not given, the font size * will be found from the DOM element. * * @param {Highcharts.SVGElement|Highcharts.SVGDOMElement} [elem] * The element to inspect for a current font size. * * @return {Highcharts.FontMetricsObject} * The font metrics. */ fontMetrics: function (fontSize, elem) { var lineHeight, baseline; if (this.styledMode) { fontSize = elem && SVGElement.prototype.getStyle.call( elem, 'font-size' ); } else { fontSize = fontSize || // When the elem is a DOM element (#5932) (elem && elem.style && elem.style.fontSize) || // Fall back on the renderer style default (this.style && this.style.fontSize); } // Handle different units if (/px/.test(fontSize)) { fontSize = pInt(fontSize); } else if (/em/.test(fontSize)) { // The em unit depends on parent items fontSize = parseFloat(fontSize) * (elem ? this.fontMetrics(null, elem.parentNode).f : 16); } else { fontSize = 12; } // Empirical values found by comparing font size and bounding box // height. Applies to the default font family. // https://jsfiddle.net/highcharts/7xvn7/ lineHeight = fontSize < 24 ? fontSize + 3 : Math.round(fontSize * 1.2); baseline = Math.round(lineHeight * 0.8); return { h: lineHeight, b: baseline, f: fontSize }; }, /** * Correct X and Y positioning of a label for rotation (#1764). * * @private * @function Highcharts.SVGRenderer#rotCorr * * @param {number} baseline * * @param {number} rotation * * @param {boolean} alterY */ rotCorr: function (baseline, rotation, alterY) { var y = baseline; if (rotation && alterY) { y = Math.max(y * Math.cos(rotation * deg2rad), 4); } return { x: (-baseline / 3) * Math.sin(rotation * deg2rad), y: y }; }, /** * Draw a label, which is an extended text element with support for border * and background. Highcharts creates a `g` element with a text and a `path` * or `rect` inside, to make it behave somewhat like a HTML div. Border and * background are set through `stroke`, `stroke-width` and `fill` attributes * using the {@link Highcharts.SVGElement#attr|attr} method. To update the * text after render, run `label.attr({ text: 'New text' })`. * * @sample highcharts/members/renderer-label-on-chart/ * A label on the chart * * @function Highcharts.SVGRenderer#label * * @param {string} str * The initial text string or (subset) HTML to render. * * @param {number} x * The x position of the label's left side. * * @param {number} y * The y position of the label's top side or baseline, depending on * the `baseline` parameter. * * @param {string} [shape='rect'] * The shape of the label's border/background, if any. Defaults to * `rect`. Other possible values are `callout` or other shapes * defined in {@link Highcharts.SVGRenderer#symbols}. * * @param {string} [shape='rect'] * The shape of the label's border/background, if any. Defaults to * `rect`. Other possible values are `callout` or other shapes * defined in {@link Highcharts.SVGRenderer#symbols}. * * @param {number} [anchorX] * In case the `shape` has a pointer, like a flag, this is the * coordinates it should be pinned to. * * @param {number} [anchorY] * In case the `shape` has a pointer, like a flag, this is the * coordinates it should be pinned to. * * @param {boolean} [useHTML=false] * Wether to use HTML to render the label. * * @param {boolean} [baseline=false] * Whether to position the label relative to the text baseline, * like {@link Highcharts.SVGRenderer#text|renderer.text}, or to the * upper border of the rectangle. * * @param {string} [className] * Class name for the group. * * @return {Highcharts.SVGElement} * The generated label. */ label: function ( str, x, y, shape, anchorX, anchorY, useHTML, baseline, className ) { var renderer = this, styledMode = renderer.styledMode, wrapper = renderer.g(className !== 'button' && 'label'), text = wrapper.text = renderer.text('', 0, 0, useHTML) .attr({ zIndex: 1 }), box, bBox, alignFactor = 0, padding = 3, paddingLeft = 0, width, height, wrapperX, wrapperY, textAlign, deferredAttr = {}, strokeWidth, baselineOffset, hasBGImage = /^url\((.*?)\)$/.test(shape), needsBox = styledMode || hasBGImage, getCrispAdjust = function () { return styledMode ? box.strokeWidth() % 2 / 2 : (strokeWidth ? parseInt(strokeWidth, 10) : 0) % 2 / 2; }, updateBoxSize, updateTextPadding, boxAttr; if (className) { wrapper.addClass('highcharts-' + className); } /* This function runs after the label is added to the DOM (when the bounding box is available), and after the text of the label is updated to detect the new bounding box and reflect it in the border box. */ updateBoxSize = function () { var style = text.element.style, crispAdjust, attribs = {}; bBox = ( (width === undefined || height === undefined || textAlign) && defined(text.textStr) && text.getBBox() ); // #3295 && 3514 box failure when string equals 0 wrapper.width = ( (width || bBox.width || 0) + 2 * padding + paddingLeft ); wrapper.height = (height || bBox.height || 0) + 2 * padding; // Update the label-scoped y offset baselineOffset = padding + Math.min( renderer.fontMetrics(style && style.fontSize, text).b, // Math.min because of inline style (#9400) bBox ? bBox.height : Infinity ); if (needsBox) { // Create the border box if it is not already present if (!box) { // Symbol definition exists (#5324) wrapper.box = box = renderer.symbols[shape] || hasBGImage ? renderer.symbol(shape) : renderer.rect(); box.addClass( // Don't use label className for buttons (className === 'button' ? '' : 'highcharts-label-box') + (className ? ' highcharts-' + className + '-box' : '') ); box.add(wrapper); crispAdjust = getCrispAdjust(); attribs.x = crispAdjust; attribs.y = (baseline ? -baselineOffset : 0) + crispAdjust; } // Apply the box attributes attribs.width = Math.round(wrapper.width); attribs.height = Math.round(wrapper.height); box.attr(extend(attribs, deferredAttr)); deferredAttr = {}; } }; /* * This function runs after setting text or padding, but only if padding * is changed. */ updateTextPadding = function () { var textX = paddingLeft + padding, textY; // determin y based on the baseline textY = baseline ? 0 : baselineOffset; // compensate for alignment if ( defined(width) && bBox && (textAlign === 'center' || textAlign === 'right') ) { textX += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width); } // update if anything changed if (textX !== text.x || textY !== text.y) { text.attr('x', textX); // #8159 - prevent misplaced data labels in treemap // (useHTML: true) if (text.hasBoxWidthChanged) { bBox = text.getBBox(true); updateBoxSize(); } if (textY !== undefined) { text.attr('y', textY); } } // record current values text.x = textX; text.y = textY; }; /* * Set a box attribute, or defer it if the box is not yet created */ boxAttr = function (key, value) { if (box) { box.attr(key, value); } else { deferredAttr[key] = value; } }; /* * After the text element is added, get the desired size of the border * box and add it before the text in the DOM. */ wrapper.onAdd = function () { text.add(wrapper); wrapper.attr({ // Alignment is available now (#3295, 0 not rendered if given // as a value) text: (str || str === 0) ? str : '', x: x, y: y }); if (box && defined(anchorX)) { wrapper.attr({ anchorX: anchorX, anchorY: anchorY }); } }; /* * Add specific attribute setters. */ // only change local variables wrapper.widthSetter = function (value) { width = H.isNumber(value) ? value : null; // width:auto => null }; wrapper.heightSetter = function (value) { height = value; }; wrapper['text-alignSetter'] = function (value) { textAlign = value; }; wrapper.paddingSetter = function (value) { if (defined(value) && value !== padding) { padding = wrapper.padding = value; updateTextPadding(); } }; wrapper.paddingLeftSetter = function (value) { if (defined(value) && value !== paddingLeft) { paddingLeft = value; updateTextPadding(); } }; // change local variable and prevent setting attribute on the group wrapper.alignSetter = function (value) { value = { left: 0, center: 0.5, right: 1 }[value]; if (value !== alignFactor) { alignFactor = value; // Bounding box exists, means we're dynamically changing if (bBox) { wrapper.attr({ x: wrapperX }); // #5134 } } }; // apply these to the box and the text alike wrapper.textSetter = function (value) { if (value !== undefined) { text.textSetter(value); } updateBoxSize(); updateTextPadding(); }; // apply these to the box but not to the text wrapper['stroke-widthSetter'] = function (value, key) { if (value) { needsBox = true; } strokeWidth = this['stroke-width'] = value; boxAttr(key, value); }; if (styledMode) { wrapper.rSetter = function (value, key) { boxAttr(key, value); }; } else { wrapper.strokeSetter = wrapper.fillSetter = wrapper.rSetter = function (value, key) { if (key !== 'r') { if (key === 'fill' && value) { needsBox = true; } // for animation getter (#6776) wrapper[key] = value; } boxAttr(key, value); }; } wrapper.anchorXSetter = function (value, key) { anchorX = wrapper.anchorX = value; boxAttr(key, Math.round(value) - getCrispAdjust() - wrapperX); }; wrapper.anchorYSetter = function (value, key) { anchorY = wrapper.anchorY = value; boxAttr(key, value - wrapperY); }; // rename attributes wrapper.xSetter = function (value) { wrapper.x = value; // for animation getter if (alignFactor) { value -= alignFactor * ((width || bBox.width) + 2 * padding); // Force animation even when setting to the same value (#7898) wrapper['forceAnimate:x'] = true; } wrapperX = Math.round(value); wrapper.attr('translateX', wrapperX); }; wrapper.ySetter = function (value) { wrapperY = wrapper.y = Math.round(value); wrapper.attr('translateY', wrapperY); }; // Redirect certain methods to either the box or the text var baseCss = wrapper.css; var wrapperExtension = { /** * Pick up some properties and apply them to the text instead of the * wrapper. */ css: function (styles) { if (styles) { var textStyles = {}; // Create a copy to avoid altering the original object // (#537) styles = merge(styles); wrapper.textProps.forEach(function (prop) { if (styles[prop] !== undefined) { textStyles[prop] = styles[prop]; delete styles[prop]; } }); text.css(textStyles); // Update existing text and box if ('width' in textStyles) { updateBoxSize(); } // Keep updated (#9400) if ('fontSize' in textStyles) { updateBoxSize(); updateTextPadding(); } } return baseCss.call(wrapper, styles); }, /* * Return the bounding box of the box, not the group. */ getBBox: function () { return { width: bBox.width + 2 * padding, height: bBox.height + 2 * padding, x: bBox.x - padding, y: bBox.y - padding }; }, /** * Destroy and release memory. */ destroy: function () { // Added by button implementation removeEvent(wrapper.element, 'mouseenter'); removeEvent(wrapper.element, 'mouseleave'); if (text) { text = text.destroy(); } if (box) { box = box.destroy(); } // Call base implementation to destroy the rest SVGElement.prototype.destroy.call(wrapper); // Release local pointers (#1298) wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = null; } }; if (!styledMode) { /** * Apply the shadow to the box. * * @ignore * @function Highcharts.SVGElement#shadow * * @return {Highcharts.SVGElement} */ wrapperExtension.shadow = function (b) { if (b) { updateBoxSize(); if (box) { box.shadow(b); } } return wrapper; }; } return extend(wrapper, wrapperExtension); } }); // end SVGRenderer // general renderer H.Renderer = SVGRenderer;
// wrapped by build app define("FileSaver/demo/demo", ["dojo","dijit","dojox"], function(dojo,dijit,dojox){ /* FileSaver.js demo script * 2012-01-23 * * By Eli Grey, http://eligrey.com * License: X11/MIT * See LICENSE.md */ /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/demo/demo.js */ (function(view) { "use strict"; // The canvas drawing portion of the demo is based off the demo at // http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/ var document = view.document , $ = function(id) { return document.getElementById(id); } , session = view.sessionStorage // only get URL when necessary in case Blob.js hasn't defined it yet , get_blob = function() { return view.Blob; } , canvas = $("canvas") , canvas_options_form = $("canvas-options") , canvas_filename = $("canvas-filename") , canvas_clear_button = $("canvas-clear") , text = $("text") , text_options_form = $("text-options") , text_filename = $("text-filename") , html = $("html") , html_options_form = $("html-options") , html_filename = $("html-filename") , ctx = canvas.getContext("2d") , drawing = false , x_points = session.x_points || [] , y_points = session.y_points || [] , drag_points = session.drag_points || [] , add_point = function(x, y, dragging) { x_points.push(x); y_points.push(y); drag_points.push(dragging); } , draw = function(){ canvas.width = canvas.width; ctx.lineWidth = 6; ctx.lineJoin = "round"; ctx.strokeStyle = "#000000"; var i = 0 , len = x_points.length ; for(; i < len; i++) { ctx.beginPath(); if (i && drag_points[i]) { ctx.moveTo(x_points[i-1], y_points[i-1]); } else { ctx.moveTo(x_points[i]-1, y_points[i]); } ctx.lineTo(x_points[i], y_points[i]); ctx.closePath(); ctx.stroke(); } } , stop_drawing = function() { drawing = false; } // Title guesser and document creator available at https://gist.github.com/1059648 , guess_title = function(doc) { var h = "h6 h5 h4 h3 h2 h1".split(" ") , i = h.length , headers , header_text ; while (i--) { headers = doc.getElementsByTagName(h[i]); for (var j = 0, len = headers.length; j < len; j++) { header_text = headers[j].textContent.trim(); if (header_text) { return header_text; } } } } , doc_impl = document.implementation , create_html_doc = function(html) { var dt = doc_impl.createDocumentType('html', null, null) , doc = doc_impl.createDocument("http://www.w3.org/1999/xhtml", "html", dt) , doc_el = doc.documentElement , head = doc_el.appendChild(doc.createElement("head")) , charset_meta = head.appendChild(doc.createElement("meta")) , title = head.appendChild(doc.createElement("title")) , body = doc_el.appendChild(doc.createElement("body")) , i = 0 , len = html.childNodes.length ; charset_meta.setAttribute("charset", html.ownerDocument.characterSet); for (; i < len; i++) { body.appendChild(doc.importNode(html.childNodes.item(i), true)); } var title_text = guess_title(doc); if (title_text) { title.appendChild(doc.createTextNode(title_text)); } return doc; } ; canvas.width = 500; canvas.height = 300; if (typeof x_points === "string") { x_points = JSON.parse(x_points); } if (typeof y_points === "string") { y_points = JSON.parse(y_points); } if (typeof drag_points === "string") { drag_points = JSON.parse(drag_points); } if (session.canvas_filename) { canvas_filename.value = session.canvas_filename; } if (session.text) { text.value = session.text; } if (session.text_filename) { text_filename.value = session.text_filename; } if (session.html) { html.innerHTML = session.html; } if (session.html_filename) { html_filename.value = session.html_filename; } drawing = true; draw(); drawing = false; canvas_clear_button.addEventListener("click", function() { canvas.width = canvas.width; x_points.length = y_points.length = drag_points.length = 0; }, false); canvas.addEventListener("mousedown", function(event) { event.preventDefault(); drawing = true; add_point(event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop, false); draw(); }, false); canvas.addEventListener("mousemove", function(event) { if (drawing) { add_point(event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop, true); draw(); } }, false); canvas.addEventListener("mouseup", stop_drawing, false); canvas.addEventListener("mouseout", stop_drawing, false); canvas_options_form.addEventListener("submit", function(event) { event.preventDefault(); canvas.toBlob(function(blob) { saveAs( blob , (canvas_filename.value || canvas_filename.placeholder) + ".png" ); }, "image/png"); }, false); text_options_form.addEventListener("submit", function(event) { event.preventDefault(); var BB = get_blob(); saveAs( new BB( [text.value || text.placeholder] , {type: "text/plain;charset=" + document.characterSet} ) , (text_filename.value || text_filename.placeholder) + ".txt" ); }, false); html_options_form.addEventListener("submit", function(event) { event.preventDefault(); var BB = get_blob() , xml_serializer = new XMLSerializer , doc = create_html_doc(html) ; saveAs( new BB( [xml_serializer.serializeToString(doc)] , {type: "application/xhtml+xml;charset=" + document.characterSet} ) , (html_filename.value || html_filename.placeholder) + ".xhtml" ); }, false); view.addEventListener("unload", function() { session.x_points = JSON.stringify(x_points); session.y_points = JSON.stringify(y_points); session.drag_points = JSON.stringify(drag_points); session.canvas_filename = canvas_filename.value; session.text = text.value; session.text_filename = text_filename.value; session.html = html.innerHTML; session.html_filename = html_filename.value; }, false); }(self)); });
/* **************************************************************************** * Start Flags series code * *****************************************************************************/ var symbols = SVGRenderer.prototype.symbols; // 1 - set default options defaultPlotOptions.flags = merge(defaultPlotOptions.column, { dataGrouping: null, fillColor: 'white', lineWidth: 1, pointRange: 0, // #673 //radius: 2, shape: 'flag', stackDistance: 12, states: { hover: { lineColor: 'black', fillColor: '#FCFFC5' } }, style: { fontSize: '11px', fontWeight: 'bold', textAlign: 'center' }, tooltip: { pointFormat: '{point.text}<br/>' }, threshold: null, y: -30 }); // 2 - Create the CandlestickSeries object seriesTypes.flags = extendClass(seriesTypes.column, { type: 'flags', sorted: false, noSharedTooltip: true, takeOrdinalPosition: false, // #1074 trackerGroups: ['markerGroup'], forceCrop: true, /** * Inherit the initialization from base Series */ init: Series.prototype.init, /** * One-to-one mapping from options to SVG attributes */ pointAttrToOptions: { // mapping between SVG attributes and the corresponding options fill: 'fillColor', stroke: 'color', 'stroke-width': 'lineWidth', r: 'radius' }, /** * Extend the translate method by placing the point on the related series */ translate: function () { seriesTypes.column.prototype.translate.apply(this); var series = this, options = series.options, chart = series.chart, points = series.points, cursor = points.length - 1, point, lastPoint, optionsOnSeries = options.onSeries, onSeries = optionsOnSeries && chart.get(optionsOnSeries), step = onSeries && onSeries.options.step, onData = onSeries && onSeries.points, i = onData && onData.length, xAxis = series.xAxis, xAxisExt = xAxis.getExtremes(), leftPoint, lastX, rightPoint, currentDataGrouping; // relate to a master series if (onSeries && onSeries.visible && i) { currentDataGrouping = onSeries.currentDataGrouping; lastX = onData[i - 1].x + (currentDataGrouping ? currentDataGrouping.totalRange : 0); // #2374 // sort the data points points.sort(function (a, b) { return (a.x - b.x); }); while (i-- && points[cursor]) { point = points[cursor]; leftPoint = onData[i]; if (leftPoint.x <= point.x && leftPoint.plotY !== UNDEFINED) { if (point.x <= lastX) { // #803 point.plotY = leftPoint.plotY; // interpolate between points, #666 if (leftPoint.x < point.x && !step) { rightPoint = onData[i + 1]; if (rightPoint && rightPoint.plotY !== UNDEFINED) { point.plotY += ((point.x - leftPoint.x) / (rightPoint.x - leftPoint.x)) * // the distance ratio, between 0 and 1 (rightPoint.plotY - leftPoint.plotY); // the y distance } } } cursor--; i++; // check again for points in the same x position if (cursor < 0) { break; } } } } // Add plotY position and handle stacking each(points, function (point, i) { // Undefined plotY means the point is either on axis, outside series range or hidden series. // If the series is outside the range of the x axis it should fall through with // an undefined plotY, but then we must remove the shapeArgs (#847). if (point.plotY === UNDEFINED) { if (point.x >= xAxisExt.min && point.x <= xAxisExt.max) { // we're inside xAxis range point.plotY = chart.chartHeight - xAxis.bottom - (xAxis.opposite ? xAxis.height : 0) + xAxis.offset - chart.plotTop; } else { point.shapeArgs = {}; // 847 } } // if multiple flags appear at the same x, order them into a stack lastPoint = points[i - 1]; if (lastPoint && lastPoint.plotX === point.plotX) { if (lastPoint.stackIndex === UNDEFINED) { lastPoint.stackIndex = 0; } point.stackIndex = lastPoint.stackIndex + 1; } }); }, /** * Draw the markers */ drawPoints: function () { var series = this, pointAttr, points = series.points, chart = series.chart, renderer = chart.renderer, plotX, plotY, options = series.options, optionsY = options.y, shape, i, point, graphic, stackIndex, crisp = (options.lineWidth % 2 / 2), anchorX, anchorY, outsideRight; i = points.length; while (i--) { point = points[i]; outsideRight = point.plotX > series.xAxis.len; plotX = point.plotX + (outsideRight ? crisp : -crisp); stackIndex = point.stackIndex; shape = point.options.shape || options.shape; plotY = point.plotY; if (plotY !== UNDEFINED) { plotY = point.plotY + optionsY + crisp - (stackIndex !== UNDEFINED && stackIndex * options.stackDistance); } anchorX = stackIndex ? UNDEFINED : point.plotX + crisp; // skip connectors for higher level stacked points anchorY = stackIndex ? UNDEFINED : point.plotY; graphic = point.graphic; // only draw the point if y is defined and the flag is within the visible area if (plotY !== UNDEFINED && plotX >= 0 && !outsideRight) { // shortcuts pointAttr = point.pointAttr[point.selected ? 'select' : '']; if (graphic) { // update graphic.attr({ x: plotX, y: plotY, r: pointAttr.r, anchorX: anchorX, anchorY: anchorY }); } else { graphic = point.graphic = renderer.label( point.options.title || options.title || 'A', plotX, plotY, shape, anchorX, anchorY, options.useHTML ) .css(merge(options.style, point.style)) .attr(pointAttr) .attr({ align: shape === 'flag' ? 'left' : 'center', width: options.width, height: options.height }) .add(series.markerGroup) .shadow(options.shadow); } // Set the tooltip anchor position point.tooltipPos = [plotX, plotY]; } else if (graphic) { point.graphic = graphic.destroy(); } } }, /** * Extend the column trackers with listeners to expand and contract stacks */ drawTracker: function () { var series = this, points = series.points; TrackerMixin.drawTrackerPoint.apply(this); // Bring each stacked flag up on mouse over, this allows readability of vertically // stacked elements as well as tight points on the x axis. #1924. each(points, function (point) { var graphic = point.graphic; if (graphic) { addEvent(graphic.element, 'mouseover', function () { // Raise this point if (point.stackIndex > 0 && !point.raised) { point._y = graphic.y; graphic.attr({ y: point._y - 8 }); point.raised = true; } // Revert other raised points each(points, function (otherPoint) { if (otherPoint !== point && otherPoint.raised && otherPoint.graphic) { otherPoint.graphic.attr({ y: otherPoint._y }); otherPoint.raised = false; } }); }); } }); }, /** * Disable animation */ animate: noop }); // create the flag icon with anchor symbols.flag = function (x, y, w, h, options) { var anchorX = (options && options.anchorX) || x, anchorY = (options && options.anchorY) || y; return [ 'M', anchorX, anchorY, 'L', x, y + h, x, y, x + w, y, x + w, y + h, x, y + h, 'M', anchorX, anchorY, 'Z' ]; }; // create the circlepin and squarepin icons with anchor each(['circle', 'square'], function (shape) { symbols[shape + 'pin'] = function (x, y, w, h, options) { var anchorX = options && options.anchorX, anchorY = options && options.anchorY, path = symbols[shape](x, y, w, h), labelTopOrBottomY; if (anchorX && anchorY) { // if the label is below the anchor, draw the connecting line from the top edge of the label // otherwise start drawing from the bottom edge labelTopOrBottomY = (y > anchorY) ? y : y + h; path.push('M', anchorX, labelTopOrBottomY, 'L', anchorX, anchorY); } return path; }; }); // The symbol callbacks are generated on the SVGRenderer object in all browsers. Even // VML browsers need this in order to generate shapes in export. Now share // them with the VMLRenderer. if (Renderer === Highcharts.VMLRenderer) { each(['flag', 'circlepin', 'squarepin'], function (shape) { VMLRenderer.prototype.symbols[shape] = symbols[shape]; }); } /* **************************************************************************** * End Flags series code * *****************************************************************************/
version https://git-lfs.github.com/spec/v1 oid sha256:f09386339b7a083e92b706c491817eb6f328805c49481a614f996a194d761fdc size 1848
if (typeof (QP) == "undefined" || !QP) { var QP = {} }; (function() { /* Draws the lines linking nodes in query plan diagram. root - The document element in which the diagram is contained. */ QP.drawLines = function(root) { if (root === null || root === undefined) { // Try and find it ourselves root = $(".qp-root").parent(); } else { // Make sure the object passed is jQuery wrapped root = $(root); } internalDrawLines(root); }; /* Internal implementaiton of drawLines. */ function internalDrawLines(root) { var canvas = getCanvas(root); var canvasElm = canvas[0]; // Check for browser compatability if (canvasElm.getContext !== null && canvasElm.getContext !== undefined) { // Chrome is usually too quick with document.ready window.setTimeout(function() { var context = canvasElm.getContext("2d"); // The first root node may be smaller than the full query plan if using overflow var firstNode = $(".qp-tr", root); canvasElm.width = firstNode.outerWidth(true); canvasElm.height = firstNode.outerHeight(true); var offset = canvas.offset(); $(".qp-tr", root).each(function() { var from = $("> * > .qp-node", $(this)); $("> * > .qp-tr > * > .qp-node", $(this)).each(function() { drawLine(context, offset, from, $(this)); }); }); context.stroke(); }, 1); } } /* Locates or creates the canvas element to use to draw lines for a given root element. */ function getCanvas(root) { var returnValue = $("canvas", root); if (returnValue.length == 0) { root.prepend($("<canvas></canvas>") .css("position", "absolute") .css("top", 0).css("left", 0) ); returnValue = $("canvas", root); } return returnValue; } /* Draws a line between two nodes. context - The canvas context with which to draw. offset - Canvas offset in the document. from - The document jQuery object from which to draw the line. to - The document jQuery object to which to draw the line. */ function drawLine(context, offset, from, to) { var fromOffset = from.offset(); fromOffset.top += from.outerHeight() / 2; fromOffset.left += from.outerWidth(); var toOffset = to.offset(); toOffset.top += to.outerHeight() / 2; var midOffsetLeft = fromOffset.left / 2 + toOffset.left / 2; context.moveTo(fromOffset.left - offset.left, fromOffset.top - offset.top); context.lineTo(midOffsetLeft - offset.left, fromOffset.top - offset.top); context.lineTo(midOffsetLeft - offset.left, toOffset.top - offset.top); context.lineTo(toOffset.left - offset.left, toOffset.top - offset.top); } })();
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.1.0-rc4-master-c81f9f1 */ goog.provide('ng.material.components.swipe'); goog.require('ng.material.core'); /** * @ngdoc module * @name material.components.swipe * @description Swipe module! */ /** * @ngdoc directive * @module material.components.swipe * @name mdSwipeLeft * * @restrict A * * @description * The md-swipe-left directive allows you to specify custom behavior when an element is swiped * left. * * @usage * <hljs lang="html"> * <div md-swipe-left="onSwipeLeft()">Swipe me left!</div> * </hljs> */ /** * @ngdoc directive * @module material.components.swipe * @name mdSwipeRight * * @restrict A * * @description * The md-swipe-right directive allows you to specify custom behavior when an element is swiped * right. * * @usage * <hljs lang="html"> * <div md-swipe-right="onSwipeRight()">Swipe me right!</div> * </hljs> */ /** * @ngdoc directive * @module material.components.swipe * @name mdSwipeUp * * @restrict A * * @description * The md-swipe-up directive allows you to specify custom behavior when an element is swiped * up. * * @usage * <hljs lang="html"> * <div md-swipe-up="onSwipeUp()">Swipe me up!</div> * </hljs> */ /** * @ngdoc directive * @module material.components.swipe * @name mdSwipeDown * * @restrict A * * @description * The md-swipe-down directive allows you to specify custom behavior when an element is swiped * down. * * @usage * <hljs lang="html"> * <div md-swipe-down="onSwipDown()">Swipe me down!</div> * </hljs> */ angular.module('material.components.swipe', ['material.core']) .directive('mdSwipeLeft', getDirective('SwipeLeft')) .directive('mdSwipeRight', getDirective('SwipeRight')) .directive('mdSwipeUp', getDirective('SwipeUp')) .directive('mdSwipeDown', getDirective('SwipeDown')); function getDirective(name) { var directiveName = 'md' + name; var eventName = '$md.' + name.toLowerCase(); DirectiveFactory.$inject = ["$parse"]; return DirectiveFactory; /* ngInject */ function DirectiveFactory($parse) { return { restrict: 'A', link: postLink }; function postLink(scope, element, attr) { var fn = $parse(attr[directiveName]); element.on(eventName, function(ev) { scope.$apply(function() { fn(scope, { $event: ev }); }); }); } } } ng.material.components.swipe = angular.module("material.components.swipe");
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v18.0.0 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LinkedList = (function () { function LinkedList() { this.first = null; this.last = null; } LinkedList.prototype.add = function (item) { var entry = { item: item, next: null }; if (this.last) { this.last.next = entry; } else { this.first = entry; } this.last = entry; }; LinkedList.prototype.remove = function () { var result = this.first; if (result) { this.first = result.next; if (!this.first) { this.last = null; } } return result.item; }; LinkedList.prototype.isEmpty = function () { return !this.first; }; return LinkedList; }()); exports.LinkedList = LinkedList; var LinkedListItem = (function () { function LinkedListItem() { } return LinkedListItem; }());
/** * This pagination style shows Previous/Next buttons, and page numbers only * for "known" pages that are visited at least once time using [Next>] button. * Initially only Prev/Next buttons are shown (Prev is initially disabled). * * [<Previous] [Next>] * * When user navigates through the pages using [Next>] button, navigation shows * the numbers for the previous pages. As an example, when user reaches page 2, * page numbers 1 and 2 are shown: * * [<Previous] 1 2 [Next>] * * When user reaches page 4, page numbers 1, 2, 3, and 4 are shown: * * [<Previous] 1 2 3 4 [Next>] * * When user navigates back, pagination will remember the last page number * he reached and the numbesr up to the last known page are shown. As an example, * when user returns to the page 2, page numbers 1, 2, 3, and 4 are still shown: * * [<Previous] 1 2 3 4 [Next>] * * This pagination style is designed for users who will not directly jump to * the random page that they have not opened before. Assumption is that users * will discover new pages using [Next>] button. This pagination enables users * to easily go back and forth to any page that they discovered. * * Key benefit: This pagination supports usual pagination pattern and does not * require server to return total count of items just to calculate last page and * all numbers. This migh be huge performance benefit because server does not * need to execute two queries in server-side processing mode: * - One to get the records that will be shown on the current page, * - Second to get the total count just to calculate full pagination. * * Without second query, page load time might be 2x faster, especially in cases * when server can quickly get top 100 records, but it would need to scan entire * database table just to calculate the total count and position of the last * page. This pagination style is reasonable trade-off between simple and fullnumbers * pagination. * * @name Simple Incremental navigation (Bootstrap) * @summary Shows forward/back buttons and all known page numbers. * @author [Jovan Popovic](http://github.com/JocaPC) * * @example * $(document).ready(function() { * $('#example').dataTable( { * "pagingType": "simple_incremental_bootstrap" * } ); * } ); */ $.fn.dataTableExt.oPagination.simple_incremental_bootstrap = { "fnInit": function (oSettings, nPaging, fnCallbackDraw) { $(nPaging).prepend($("<ul class=\"pagination\"></ul>")); var ul = $("ul", $(nPaging)); nFirst = document.createElement('li'); nPrevious = document.createElement('li'); nNext = document.createElement('li'); $(nPrevious).append($('<span>' + (oSettings.oLanguage.oPaginate.sPrevious) + '</span>')); $(nFirst).append($('<span>1</span>')); $(nNext).append($('<span>' + (oSettings.oLanguage.oPaginate.sNext) + '</span>')); nFirst.className = "paginate_button first active"; nPrevious.className = "paginate_button previous"; nNext.className = "paginate_button next"; ul.append(nPrevious); ul.append(nFirst); ul.append(nNext); $(nFirst).click(function () { oSettings.oApi._fnPageChange(oSettings, "first"); fnCallbackDraw(oSettings); }); $(nPrevious).click(function () { if (!(oSettings._iDisplayStart === 0)) { oSettings.oApi._fnPageChange(oSettings, "previous"); fnCallbackDraw(oSettings); } }); $(nNext).click(function () { if(oSettings.aiDisplay.length < oSettings._iDisplayLength){ oSettings._iRecordsTotal = oSettings._iDisplayStart + oSettings.aiDisplay.length; }else{ oSettings._iRecordsTotal = oSettings._iDisplayStart + oSettings._iDisplayLength + 1; } if (!(oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay() || oSettings.aiDisplay.length < oSettings._iDisplayLength)) { oSettings.oApi._fnPageChange(oSettings, "next"); fnCallbackDraw(oSettings); } }); /* Disallow text selection */ $(nFirst).bind('selectstart', function () { return false; }); $(nPrevious).bind('selectstart', function () { return false; }); $(nNext).bind('selectstart', function () { return false; }); // Reset dynamically generated pages on length/filter change. $(oSettings.nTable).DataTable().on('length.dt', function (e, settings, len) { $("li.dynamic_page_item", nPaging).remove(); }); $(oSettings.nTable).DataTable().on('search.dt', function (e, settings, len) { $("li.dynamic_page_item", nPaging).remove(); }); }, /* * Function: oPagination.simple_incremental_bootstrap.fnUpdate * Purpose: Update the list of page buttons shows * Inputs: object:oSettings - dataTables settings object * function:fnCallbackDraw - draw function which must be called on update */ "fnUpdate": function (oSettings, fnCallbackDraw) { if (!oSettings.aanFeatures.p) { return; } /* Loop over each instance of the pager */ var an = oSettings.aanFeatures.p; for (var i = 0, iLen = an.length ; i < iLen ; i++) { var buttons = an[i].getElementsByTagName('li'); $(buttons).removeClass("active"); if (oSettings._iDisplayStart === 0) { buttons[0].className = "paginate_buttons disabled previous"; buttons[buttons.length - 1].className = "paginate_button enabled next"; } else { buttons[0].className = "paginate_buttons enabled previous"; } var page = Math.round(oSettings._iDisplayStart / oSettings._iDisplayLength) + 1; if (page == buttons.length-1 && oSettings.aiDisplay.length > 0) { $new = $('<li class="dynamic_page_item active"><span>' + page + "</span></li>"); $(buttons[buttons.length - 1]).before($new); $new.click(function () { $(oSettings.nTable).DataTable().page(page-1); fnCallbackDraw(oSettings); }); } else $(buttons[page]).addClass("active"); if (oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay() || oSettings.aiDisplay.length < oSettings._iDisplayLength) { buttons[buttons.length - 1].className = "paginate_button disabled next"; } } } };
module.exports={title:"Kibana",hex:"005571",source:"https://www.elastic.co/brand",svg:'<svg aria-labelledby="simpleicons-kibana-icon" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title id="simpleicons-kibana-icon">Kibana icon</title><path d="M21.04 23.99H4.18l9.88-11.86c4.23 2.76 6.98 7.04 6.98 11.86zm0-23.95H3.08v21.55z"/></svg>\n'};
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview Contains the third and last part of the {@link CKEDITOR} object * definition. */ // Remove the CKEDITOR.loadFullCore reference defined on ckeditor_basic. delete CKEDITOR.loadFullCore; /** * Holds references to all editor instances created. The name of the properties * in this object correspond to instance names, and their values contains the * {@link CKEDITOR.editor} object representing them. * @type {Object} * @example * alert( <b>CKEDITOR.instances</b>.editor1.name ); // "editor1" */ CKEDITOR.instances = {}; /** * The document of the window holding the CKEDITOR object. * @type {CKEDITOR.dom.document} * @example * alert( <b>CKEDITOR.document</b>.getBody().getName() ); // "body" */ CKEDITOR.document = new CKEDITOR.dom.document( document ); /** * Adds an editor instance to the global {@link CKEDITOR} object. This function * is available for internal use mainly. * @param {CKEDITOR.editor} editor The editor instance to be added. * @example */ CKEDITOR.add = function( editor ) { CKEDITOR.instances[ editor.name ] = editor; editor.on( 'focus', function() { if ( CKEDITOR.currentInstance != editor ) { CKEDITOR.currentInstance = editor; CKEDITOR.fire( 'currentInstance' ); } }); editor.on( 'blur', function() { if ( CKEDITOR.currentInstance == editor ) { CKEDITOR.currentInstance = null; CKEDITOR.fire( 'currentInstance' ); } }); }; /** * Removes an editor instance from the global {@link CKEDITOR} object. This function * is available for internal use only. External code must use {@link CKEDITOR.editor.prototype.destroy} * to avoid memory leaks. * @param {CKEDITOR.editor} editor The editor instance to be removed. * @example */ CKEDITOR.remove = function( editor ) { delete CKEDITOR.instances[ editor.name ]; }; /** * Perform global clean up to free as much memory as possible * when there are no instances left */ CKEDITOR.on( 'instanceDestroyed', function () { if ( CKEDITOR.tools.isEmpty( this.instances ) ) CKEDITOR.fire( 'reset' ); }); // Load the bootstrap script. CKEDITOR.loader.load( 'core/_bootstrap' ); // @Packager.RemoveLine // Tri-state constants. /** * Used to indicate the ON or ACTIVE state. * @constant * @example */ CKEDITOR.TRISTATE_ON = 1; /** * Used to indicate the OFF or NON ACTIVE state. * @constant * @example */ CKEDITOR.TRISTATE_OFF = 2; /** * Used to indicate DISABLED state. * @constant * @example */ CKEDITOR.TRISTATE_DISABLED = 0; /** * The editor which is currently active (have user focus). * @name CKEDITOR.currentInstance * @type CKEDITOR.editor * @see CKEDITOR#currentInstance * @example * function showCurrentEditorName() * { * if ( CKEDITOR.currentInstance ) * alert( CKEDITOR.currentInstance.name ); * else * alert( 'Please focus an editor first.' ); * } */ /** * Fired when the CKEDITOR.currentInstance object reference changes. This may * happen when setting the focus on different editor instances in the page. * @name CKEDITOR#currentInstance * @event * var editor; // Variable to hold a reference to the current editor. * CKEDITOR.on( 'currentInstance' , function( e ) * { * editor = CKEDITOR.currentInstance; * }); */ /** * Fired when the last instance has been destroyed. This event is used to perform * global memory clean up. * @name CKEDITOR#reset * @event */
/** @module breeze **/ var EntityAction = (function () { /** EntityAction is an 'Enum' containing all of the valid actions that can occur to an 'Entity'. @class EntityAction @static **/ var entityActionMethods = { isAttach: function () { return !!this.isAttach; }, isDetach: function () { return !!this.isDetach; }, isModification: function () { return !!this.isModification; } }; var EntityAction = new Enum("EntityAction", entityActionMethods); /** Attach - Entity was attached via an AttachEntity call. @property Attach {EntityAction} @final @static **/ EntityAction.Attach = EntityAction.addSymbol({ isAttach: true}); /** AttachOnQuery - Entity was attached as a result of a query. @property AttachOnQuery {EntityAction} @final @static **/ EntityAction.AttachOnQuery = EntityAction.addSymbol({ isAttach: true}); /** AttachOnImport - Entity was attached as a result of an import. @property AttachOnImport {EntityAction} @final @static **/ EntityAction.AttachOnImport = EntityAction.addSymbol({ isAttach: true}); /** Detach - Entity was detached. @property Detach {EntityAction} @final @static **/ EntityAction.Detach = EntityAction.addSymbol({ isDetach: true }); /** MergeOnQuery - Properties on the entity were merged as a result of a query. @property MergeOnQuery {EntityAction} @final @static **/ EntityAction.MergeOnQuery = EntityAction.addSymbol({ isModification: true }); /** MergeOnImport - Properties on the entity were merged as a result of an import. @property MergeOnImport {EntityAction} @final @static **/ EntityAction.MergeOnImport = EntityAction.addSymbol({ isModification: true }); /** MergeOnSave - Properties on the entity were merged as a result of a save @property MergeOnSave {EntityAction} @final @static **/ EntityAction.MergeOnSave = EntityAction.addSymbol({ isModification: true }); /** PropertyChange - A property on the entity was changed. @property PropertyChange {EntityAction} @final @static **/ EntityAction.PropertyChange = EntityAction.addSymbol({ isModification: true}); /** EntityStateChange - The EntityState of the entity was changed. @property EntityStateChange {EntityAction} @final @static **/ EntityAction.EntityStateChange = EntityAction.addSymbol(); /** AcceptChanges - AcceptChanges was called on the entity, or its entityState was set to Unmodified. @property AcceptChanges {EntityAction} @final @static **/ EntityAction.AcceptChanges = EntityAction.addSymbol(); /** RejectChanges - RejectChanges was called on the entity. @property RejectChanges {EntityAction} @final @static **/ EntityAction.RejectChanges = EntityAction.addSymbol({ isModification: true}); /** Clear - The EntityManager was cleared. All entities detached. @property Clear {EntityAction} @final @static **/ EntityAction.Clear = EntityAction.addSymbol({ isDetach: true}); EntityAction.resolveSymbols(); return EntityAction; })(); breeze.EntityAction = EntityAction;
/** * Globalize v1.4.0-alpha.2 * * http://github.com/jquery/globalize * * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2018-03-09T13:51Z */ /*! * Globalize v1.4.0-alpha.2 2018-03-09T13:51Z Released under the MIT license * http://git.io/TrdQbw */ (function( root, factory ) { // UMD returnExports if ( typeof define === "function" && define.amd ) { // AMD define([ "cldr", "../globalize", "./number", "cldr/event", "cldr/supplemental" ], factory ); } else if ( typeof exports === "object" ) { // Node, CommonJS module.exports = factory( require( "cldrjs" ), require( "../globalize" ) ); } else { // Extend global factory( root.Cldr, root.Globalize ); } }(this, function( Cldr, Globalize ) { var createError = Globalize._createError, createErrorUnsupportedFeature = Globalize._createErrorUnsupportedFeature, formatMessage = Globalize._formatMessage, isPlainObject = Globalize._isPlainObject, looseMatching = Globalize._looseMatching, numberNumberingSystemDigitsMap = Globalize._numberNumberingSystemDigitsMap, numberSymbol = Globalize._numberSymbol, regexpEscape = Globalize._regexpEscape, removeLiteralQuotes = Globalize._removeLiteralQuotes, runtimeBind = Globalize._runtimeBind, stringPad = Globalize._stringPad, validate = Globalize._validate, validateCldr = Globalize._validateCldr, validateDefaultLocale = Globalize._validateDefaultLocale, validateParameterPresence = Globalize._validateParameterPresence, validateParameterType = Globalize._validateParameterType, validateParameterTypePlainObject = Globalize._validateParameterTypePlainObject, validateParameterTypeString = Globalize._validateParameterTypeString; var validateParameterTypeDate = function( value, name ) { validateParameterType( value, name, value === undefined || value instanceof Date, "Date" ); }; var createErrorInvalidParameterValue = function( name, value ) { return createError( "E_INVALID_PAR_VALUE", "Invalid `{name}` value ({value}).", { name: name, value: value }); }; /** * Create a map between the skeleton fields and their positions, e.g., * { * G: 0 * y: 1 * ... * } */ var validateSkeletonFieldsPosMap = "GyYuUrQqMLlwWEecdDFghHKkmsSAzZOvVXx".split( "" ).reduce(function( memo, item, i ) { memo[ item ] = i; return memo; }, {}); /** * validateSkeleton( skeleton ) * * skeleton: Assume `j` has already been converted into a localized hour field. */ var validateSkeleton = function validateSkeleton( skeleton ) { var last, // Using easier to read variable. fieldsPosMap = validateSkeletonFieldsPosMap; // "The fields are from the Date Field Symbol Table in Date Format Patterns" // Ref: http://www.unicode.org/reports/tr35/tr35-dates.html#availableFormats_appendItems // I.e., check for invalid characters. skeleton.replace( /[^GyYuUrQqMLlwWEecdDFghHKkmsSAzZOvVXx]/, function( field ) { throw createError( "E_INVALID_OPTIONS", "Invalid field `{invalidField}` of skeleton `{value}`", { invalidField: field, type: "skeleton", value: skeleton } ); }); // "The canonical order is from top to bottom in that table; that is, yM not My". // http://www.unicode.org/reports/tr35/tr35-dates.html#availableFormats_appendItems // I.e., check for invalid order. skeleton.split( "" ).every(function( field ) { if ( fieldsPosMap[ field ] < last ) { throw createError( "E_INVALID_OPTIONS", "Invalid order `{invalidField}` of skeleton `{value}`", { invalidField: field, type: "skeleton", value: skeleton } ); } last = fieldsPosMap[ field ]; return true; }); }; /** * Returns a new object created by using `object`'s values as keys, and the keys as values. */ var objectInvert = function( object, fn ) { fn = fn || function( object, key, value ) { object[ value ] = key; return object; }; return Object.keys( object ).reduce(function( newObject, key ) { return fn( newObject, key, object[ key ] ); }, {}); }; // Invert key and values, e.g., {"e": "eEc"} ==> {"e": "e", "E": "e", "c": "e"}. var dateExpandPatternSimilarFieldsMap = objectInvert({ "e": "eEc", "L": "ML" }, function( object, key, value ) { value.split( "" ).forEach(function( field ) { object[ field ] = key; }); return object; }); var dateExpandPatternNormalizePatternType = function( character ) { return dateExpandPatternSimilarFieldsMap[ character ] || character; }; var datePatternRe = ( /([a-z])\1*|'([^']|'')+'|''|./ig ); var stringRepeat = function( str, count ) { var i, result = ""; for ( i = 0; i < count; i++ ) { result = result + str; } return result; }; var dateExpandPatternAugmentFormat = function( requestedSkeleton, bestMatchFormat ) { var i, j, matchedType, matchedLength, requestedType, requestedLength, // Using an easier to read variable. normalizePatternType = dateExpandPatternNormalizePatternType; requestedSkeleton = requestedSkeleton.match( datePatternRe ); bestMatchFormat = bestMatchFormat.match( datePatternRe ); for ( i = 0; i < bestMatchFormat.length; i++ ) { matchedType = bestMatchFormat[i].charAt( 0 ); matchedLength = bestMatchFormat[i].length; for ( j = 0; j < requestedSkeleton.length; j++ ) { requestedType = requestedSkeleton[j].charAt( 0 ); requestedLength = requestedSkeleton[j].length; if ( normalizePatternType( matchedType ) === normalizePatternType( requestedType ) && matchedLength < requestedLength ) { bestMatchFormat[i] = stringRepeat( matchedType, requestedLength ); } } } return bestMatchFormat.join( "" ); }; var dateExpandPatternCompareFormats = function( formatA, formatB ) { var a, b, distance, lenA, lenB, typeA, typeB, i, j, // Using easier to read variables. normalizePatternType = dateExpandPatternNormalizePatternType; if ( formatA === formatB ) { return 0; } formatA = formatA.match( datePatternRe ); formatB = formatB.match( datePatternRe ); if ( formatA.length !== formatB.length ) { return -1; } distance = 1; for ( i = 0; i < formatA.length; i++ ) { a = formatA[ i ].charAt( 0 ); typeA = normalizePatternType( a ); typeB = null; for ( j = 0; j < formatB.length; j++ ) { b = formatB[ j ].charAt( 0 ); typeB = normalizePatternType( b ); if ( typeA === typeB ) { break; } else { typeB = null; } } if ( typeB === null ) { return -1; } lenA = formatA[ i ].length; lenB = formatB[ j ].length; distance = distance + Math.abs( lenA - lenB ); // Most symbols have a small distance from each other, e.g., M ≅ L; E ≅ c; a ≅ b ≅ B; // H ≅ k ≅ h ≅ K; ... if ( a !== b ) { distance += 1; } // Numeric (l<3) and text fields (l>=3) are given a larger distance from each other. if ( ( lenA < 3 && lenB >= 3 ) || ( lenA >= 3 && lenB < 3 ) ) { distance += 20; } } return distance; }; var dateExpandPatternGetBestMatchPattern = function( cldr, askedSkeleton ) { var availableFormats, pattern, ratedFormats, skeleton, path = "dates/calendars/gregorian/dateTimeFormats/availableFormats", // Using easier to read variables. augmentFormat = dateExpandPatternAugmentFormat, compareFormats = dateExpandPatternCompareFormats; pattern = cldr.main([ path, askedSkeleton ]); if ( askedSkeleton && !pattern ) { availableFormats = cldr.main([ path ]); ratedFormats = []; for ( skeleton in availableFormats ) { ratedFormats.push({ skeleton: skeleton, pattern: availableFormats[ skeleton ], rate: compareFormats( askedSkeleton, skeleton ) }); } ratedFormats = ratedFormats .filter( function( format ) { return format.rate > -1; } ) .sort( function( formatA, formatB ) { return formatA.rate - formatB.rate; }); if ( ratedFormats.length ) { pattern = augmentFormat( askedSkeleton, ratedFormats[0].pattern ); } } return pattern; }; /** * expandPattern( options, cldr ) * * @options [Object] if String, it's considered a skeleton. Object accepts: * - skeleton: [String] lookup availableFormat; * - date: [String] ( "full" | "long" | "medium" | "short" ); * - time: [String] ( "full" | "long" | "medium" | "short" ); * - datetime: [String] ( "full" | "long" | "medium" | "short" ); * - raw: [String] For more info see datetime/format.js. * * @cldr [Cldr instance]. * * Return the corresponding pattern. * Eg for "en": * - "GyMMMd" returns "MMM d, y G"; * - { skeleton: "GyMMMd" } returns "MMM d, y G"; * - { date: "full" } returns "EEEE, MMMM d, y"; * - { time: "full" } returns "h:mm:ss a zzzz"; * - { datetime: "full" } returns "EEEE, MMMM d, y 'at' h:mm:ss a zzzz"; * - { raw: "dd/mm" } returns "dd/mm"; */ var dateExpandPattern = function( options, cldr ) { var dateSkeleton, result, skeleton, timeSkeleton, type, // Using easier to read variables. getBestMatchPattern = dateExpandPatternGetBestMatchPattern; function combineDateTime( type, datePattern, timePattern ) { return formatMessage( cldr.main([ "dates/calendars/gregorian/dateTimeFormats", type ]), [ timePattern, datePattern ] ); } switch ( true ) { case "skeleton" in options: skeleton = options.skeleton; // Preferred hour (j). skeleton = skeleton.replace( /j/g, function() { return cldr.supplemental.timeData.preferred(); }); validateSkeleton( skeleton ); // Try direct map (note that getBestMatchPattern handles it). // ... or, try to "best match" the whole skeleton. result = getBestMatchPattern( cldr, skeleton ); if ( result ) { break; } // ... or, try to "best match" the date and time parts individually. timeSkeleton = skeleton.split( /[^hHKkmsSAzZOvVXx]/ ).slice( -1 )[ 0 ]; dateSkeleton = skeleton.split( /[^GyYuUrQqMLlwWdDFgEec]/ )[ 0 ]; dateSkeleton = getBestMatchPattern( cldr, dateSkeleton ); timeSkeleton = getBestMatchPattern( cldr, timeSkeleton ); if ( /(MMMM|LLLL).*[Ec]/.test( dateSkeleton ) ) { type = "full"; } else if ( /MMMM|LLLL/.test( dateSkeleton ) ) { type = "long"; } else if ( /MMM|LLL/.test( dateSkeleton ) ) { type = "medium"; } else { type = "short"; } if ( dateSkeleton && timeSkeleton ) { result = combineDateTime( type, dateSkeleton, timeSkeleton ); } else { result = dateSkeleton || timeSkeleton; } break; case "date" in options: case "time" in options: result = cldr.main([ "dates/calendars/gregorian", "date" in options ? "dateFormats" : "timeFormats", ( options.date || options.time ) ]); break; case "datetime" in options: result = combineDateTime( options.datetime, cldr.main([ "dates/calendars/gregorian/dateFormats", options.datetime ]), cldr.main([ "dates/calendars/gregorian/timeFormats", options.datetime ]) ); break; case "raw" in options: result = options.raw; break; default: throw createErrorInvalidParameterValue({ name: "options", value: options }); } return result; }; var dateWeekDays = [ "sun", "mon", "tue", "wed", "thu", "fri", "sat" ]; /** * firstDayOfWeek */ var dateFirstDayOfWeek = function( cldr ) { return dateWeekDays.indexOf( cldr.supplemental.weekData.firstDay() ); }; /** * getTimeZoneName( length, type ) */ var dateGetTimeZoneName = function( length, type, timeZone, cldr ) { var metaZone, result; if ( !timeZone ) { return; } result = cldr.main([ "dates/timeZoneNames/zone", timeZone, length < 4 ? "short" : "long", type ]); if ( result ) { return result; } // The latest metazone data of the metazone array. // TODO expand to support the historic metazones based on the given date. metaZone = cldr.supplemental([ "metaZones/metazoneInfo/timezone", timeZone, 0, "usesMetazone/_mzone" ]); return cldr.main([ "dates/timeZoneNames/metazone", metaZone, length < 4 ? "short" : "long", type ]); }; /** * timezoneHourFormatShortH( hourFormat ) * * @hourFormat [String] * * Unofficial deduction of the short hourFormat given time zone `hourFormat` element. * Official spec is pending resolution: http://unicode.org/cldr/trac/ticket/8293 * * Example: * - "+HH.mm;-HH.mm" => "+H;-H" * - "+HH:mm;-HH:mm" => "+H;-H" * - "+HH:mm;−HH:mm" => "+H;−H" (Note MINUS SIGN \u2212) * - "+HHmm;-HHmm" => "+H:-H" */ var dateTimezoneHourFormatH = function( hourFormat ) { return hourFormat .split( ";" ) .map(function( format ) { return format.slice( 0, format.indexOf( "H" ) + 1 ); }) .join( ";" ); }; /** * timezoneHourFormatLongHm( hourFormat ) * * @hourFormat [String] * * Unofficial deduction of the short hourFormat given time zone `hourFormat` element. * Official spec is pending resolution: http://unicode.org/cldr/trac/ticket/8293 * * Example (hFormat === "H"): (used for short Hm) * - "+HH.mm;-HH.mm" => "+H.mm;-H.mm" * - "+HH:mm;-HH:mm" => "+H:mm;-H:mm" * - "+HH:mm;−HH:mm" => "+H:mm;−H:mm" (Note MINUS SIGN \u2212) * - "+HHmm;-HHmm" => "+Hmm:-Hmm" * * Example (hFormat === "HH": (used for long Hm) * - "+HH.mm;-HH.mm" => "+HH.mm;-HH.mm" * - "+HH:mm;-HH:mm" => "+HH:mm;-HH:mm" * - "+H:mm;-H:mm" => "+HH:mm;-HH:mm" * - "+HH:mm;−HH:mm" => "+HH:mm;−HH:mm" (Note MINUS SIGN \u2212) * - "+HHmm;-HHmm" => "+HHmm:-HHmm" */ var dateTimezoneHourFormatHm = function( hourFormat, hFormat ) { return hourFormat .split( ";" ) .map(function( format ) { var parts = format.split( /H+/ ); parts.splice( 1, 0, hFormat ); return parts.join( "" ); }) .join( ";" ); }; var runtimeCacheDataBind = function( key, data ) { var fn = function() { return data; }; fn.dataCacheKey = key; return fn; }; /** * properties( pattern, cldr ) * * @pattern [String] raw pattern. * ref: http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns * * @cldr [Cldr instance]. * * Return the properties given the pattern and cldr. * * TODO Support other calendar types. */ var dateFormatProperties = function( pattern, cldr, timeZone ) { var properties = { numberFormatters: {}, pattern: pattern, timeSeparator: numberSymbol( "timeSeparator", cldr ) }, widths = [ "abbreviated", "wide", "narrow" ]; function setNumberFormatterPattern( pad ) { properties.numberFormatters[ pad ] = stringPad( "", pad ); } if ( timeZone ) { properties.timeZoneData = runtimeCacheDataBind( "iana/" + timeZone, { offsets: cldr.get([ "globalize-iana/zoneData", timeZone, "offsets" ]), untils: cldr.get([ "globalize-iana/zoneData", timeZone, "untils" ]), isdsts: cldr.get([ "globalize-iana/zoneData", timeZone, "isdsts" ]) }); } pattern.replace( datePatternRe, function( current ) { var aux, chr, daylightTzName, formatNumber, genericTzName, length, standardTzName; chr = current.charAt( 0 ); length = current.length; if ( chr === "j" ) { // Locale preferred hHKk. // http://www.unicode.org/reports/tr35/tr35-dates.html#Time_Data properties.preferredTime = chr = cldr.supplemental.timeData.preferred(); } // ZZZZ: same as "OOOO". if ( chr === "Z" && length === 4 ) { chr = "O"; length = 4; } // z...zzz: "{shortRegion}", eg. "PST" or "PDT". // zzzz: "{regionName} {Standard Time}" or "{regionName} {Daylight Time}", // e.g., "Pacific Standard Time" or "Pacific Daylight Time". // http://unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns if ( chr === "z" ) { standardTzName = dateGetTimeZoneName( length, "standard", timeZone, cldr ); daylightTzName = dateGetTimeZoneName( length, "daylight", timeZone, cldr ); if ( standardTzName ) { properties.standardTzName = standardTzName; } if ( daylightTzName ) { properties.daylightTzName = daylightTzName; } // Fall through the "O" format in case one name is missing. if ( !standardTzName || !daylightTzName ) { chr = "O"; if ( length < 4 ) { length = 1; } } } // v...vvv: "{shortRegion}", eg. "PT". // vvvv: "{regionName} {Time}" or "{regionName} {Time}", // e.g., "Pacific Time" // http://unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns if ( chr === "v" ) { genericTzName = dateGetTimeZoneName( length, "generic", timeZone, cldr ); // Fall back to "V" format. if ( !genericTzName ) { chr = "V"; length = 4; } } switch ( chr ) { // Era case "G": properties.eras = cldr.main([ "dates/calendars/gregorian/eras", length <= 3 ? "eraAbbr" : ( length === 4 ? "eraNames" : "eraNarrow" ) ]); break; // Year case "y": // Plain year. formatNumber = true; break; case "Y": // Year in "Week of Year" properties.firstDay = dateFirstDayOfWeek( cldr ); properties.minDays = cldr.supplemental.weekData.minDays(); formatNumber = true; break; case "u": // Extended year. Need to be implemented. case "U": // Cyclic year name. Need to be implemented. throw createErrorUnsupportedFeature({ feature: "year pattern `" + chr + "`" }); // Quarter case "Q": case "q": if ( length > 2 ) { if ( !properties.quarters ) { properties.quarters = {}; } if ( !properties.quarters[ chr ] ) { properties.quarters[ chr ] = {}; } properties.quarters[ chr ][ length ] = cldr.main([ "dates/calendars/gregorian/quarters", chr === "Q" ? "format" : "stand-alone", widths[ length - 3 ] ]); } else { formatNumber = true; } break; // Month case "M": case "L": if ( length > 2 ) { if ( !properties.months ) { properties.months = {}; } if ( !properties.months[ chr ] ) { properties.months[ chr ] = {}; } properties.months[ chr ][ length ] = cldr.main([ "dates/calendars/gregorian/months", chr === "M" ? "format" : "stand-alone", widths[ length - 3 ] ]); } else { formatNumber = true; } break; // Week - Week of Year (w) or Week of Month (W). case "w": case "W": properties.firstDay = dateFirstDayOfWeek( cldr ); properties.minDays = cldr.supplemental.weekData.minDays(); formatNumber = true; break; // Day case "d": case "D": case "F": formatNumber = true; break; case "g": // Modified Julian day. Need to be implemented. throw createErrorUnsupportedFeature({ feature: "Julian day pattern `g`" }); // Week day case "e": case "c": if ( length <= 2 ) { properties.firstDay = dateFirstDayOfWeek( cldr ); formatNumber = true; break; } /* falls through */ case "E": if ( !properties.days ) { properties.days = {}; } if ( !properties.days[ chr ] ) { properties.days[ chr ] = {}; } if ( length === 6 ) { // If short day names are not explicitly specified, abbreviated day names are // used instead. // http://www.unicode.org/reports/tr35/tr35-dates.html#months_days_quarters_eras // http://unicode.org/cldr/trac/ticket/6790 properties.days[ chr ][ length ] = cldr.main([ "dates/calendars/gregorian/days", chr === "c" ? "stand-alone" : "format", "short" ]) || cldr.main([ "dates/calendars/gregorian/days", chr === "c" ? "stand-alone" : "format", "abbreviated" ]); } else { properties.days[ chr ][ length ] = cldr.main([ "dates/calendars/gregorian/days", chr === "c" ? "stand-alone" : "format", widths[ length < 3 ? 0 : length - 3 ] ]); } break; // Period (AM or PM) case "a": properties.dayPeriods = { am: cldr.main( "dates/calendars/gregorian/dayPeriods/format/wide/am" ), pm: cldr.main( "dates/calendars/gregorian/dayPeriods/format/wide/pm" ) }; break; // Hour case "h": // 1-12 case "H": // 0-23 case "K": // 0-11 case "k": // 1-24 // Minute case "m": // Second case "s": case "S": case "A": formatNumber = true; break; // Zone case "v": if ( length !== 1 && length !== 4 ) { throw createErrorUnsupportedFeature({ feature: "timezone pattern `" + pattern + "`" }); } properties.genericTzName = genericTzName; break; case "V": if ( length === 1 ) { throw createErrorUnsupportedFeature({ feature: "timezone pattern `" + pattern + "`" }); } if ( timeZone ) { if ( length === 2 ) { properties.timeZoneName = timeZone; break; } var timeZoneName, exemplarCity = cldr.main([ "dates/timeZoneNames/zone", timeZone, "exemplarCity" ]); if ( length === 3 ) { if ( !exemplarCity ) { exemplarCity = cldr.main([ "dates/timeZoneNames/zone/Etc/Unknown/exemplarCity" ]); } timeZoneName = exemplarCity; } if ( exemplarCity && length === 4 ) { timeZoneName = formatMessage( cldr.main( "dates/timeZoneNames/regionFormat" ), [ exemplarCity ] ); } if ( timeZoneName ) { properties.timeZoneName = timeZoneName; break; } } if ( current === "v" ) { length = 1; } /* falls through */ case "O": // O: "{gmtFormat}+H;{gmtFormat}-H" or "{gmtZeroFormat}", eg. "GMT-8" or "GMT". // OOOO: "{gmtFormat}{hourFormat}" or "{gmtZeroFormat}", eg. "GMT-08:00" or "GMT". properties.gmtFormat = cldr.main( "dates/timeZoneNames/gmtFormat" ); properties.gmtZeroFormat = cldr.main( "dates/timeZoneNames/gmtZeroFormat" ); // Unofficial deduction of the hourFormat variations. // Official spec is pending resolution: http://unicode.org/cldr/trac/ticket/8293 aux = cldr.main( "dates/timeZoneNames/hourFormat" ); properties.hourFormat = length < 4 ? [ dateTimezoneHourFormatH( aux ), dateTimezoneHourFormatHm( aux, "H" ) ] : dateTimezoneHourFormatHm( aux, "HH" ); /* falls through */ case "Z": case "X": case "x": setNumberFormatterPattern( 1 ); setNumberFormatterPattern( 2 ); break; } if ( formatNumber ) { setNumberFormatterPattern( length ); } }); return properties; }; var dateFormatterFn = function( dateToPartsFormatter ) { return function dateFormatter( value ) { return dateToPartsFormatter( value ).map( function( part ) { return part.value; }).join( "" ); }; }; /** * parseProperties( cldr ) * * @cldr [Cldr instance]. * * @timeZone [String] FIXME. * * Return parser properties. */ var dateParseProperties = function( cldr, timeZone ) { var properties = { preferredTimeData: cldr.supplemental.timeData.preferred() }; if ( timeZone ) { properties.timeZoneData = runtimeCacheDataBind( "iana/" + timeZone, { offsets: cldr.get([ "globalize-iana/zoneData", timeZone, "offsets" ]), untils: cldr.get([ "globalize-iana/zoneData", timeZone, "untils" ]), isdsts: cldr.get([ "globalize-iana/zoneData", timeZone, "isdsts" ]) }); } return properties; }; var ZonedDateTime = (function() { function definePrivateProperty(object, property, value) { Object.defineProperty(object, property, { value: value }); } function getUntilsIndex(original, untils) { var index = 0; var originalTime = original.getTime(); // TODO Should we do binary search for improved performance? while (index < untils.length - 1 && originalTime >= untils[index]) { index++; } return index; } function setWrap(fn) { var offset1 = this.getTimezoneOffset(); var ret = fn(); this.original.setTime(new Date(this.getTime())); var offset2 = this.getTimezoneOffset(); if (offset2 - offset1) { this.original.setMinutes(this.original.getMinutes() + offset2 - offset1); } return ret; } var ZonedDateTime = function(date, timeZoneData) { definePrivateProperty(this, "original", new Date(date.getTime())); definePrivateProperty(this, "local", new Date(date.getTime())); definePrivateProperty(this, "timeZoneData", timeZoneData); definePrivateProperty(this, "setWrap", setWrap); if (!(timeZoneData.untils && timeZoneData.offsets && timeZoneData.isdsts)) { throw new Error("Invalid IANA data"); } this.setTime(this.local.getTime() - this.getTimezoneOffset() * 60 * 1000); }; ZonedDateTime.prototype.clone = function() { return new ZonedDateTime(this.original, this.timeZoneData); }; // Date field getters. ["getFullYear", "getMonth", "getDate", "getDay", "getHours", "getMinutes", "getSeconds", "getMilliseconds"].forEach(function(method) { // Corresponding UTC method, e.g., "getUTCFullYear" if method === "getFullYear". var utcMethod = "getUTC" + method.substr(3); ZonedDateTime.prototype[method] = function() { return this.local[utcMethod](); }; }); // Note: Define .valueOf = .getTime for arithmetic operations like date1 - date2. ZonedDateTime.prototype.valueOf = ZonedDateTime.prototype.getTime = function() { return this.local.getTime() + this.getTimezoneOffset() * 60 * 1000; }; ZonedDateTime.prototype.getTimezoneOffset = function() { var index = getUntilsIndex(this.original, this.timeZoneData.untils); return this.timeZoneData.offsets[index]; }; // Date field setters. ["setFullYear", "setMonth", "setDate", "setHours", "setMinutes", "setSeconds", "setMilliseconds"].forEach(function(method) { // Corresponding UTC method, e.g., "setUTCFullYear" if method === "setFullYear". var utcMethod = "setUTC" + method.substr(3); ZonedDateTime.prototype[method] = function(value) { var local = this.local; // Note setWrap is needed for seconds and milliseconds just because // abs(value) could be >= a minute. return this.setWrap(function() { return local[utcMethod](value); }); }; }); ZonedDateTime.prototype.setTime = function(time) { return this.local.setTime(time); }; ZonedDateTime.prototype.isDST = function() { var index = getUntilsIndex(this.original, this.timeZoneData.untils); return Boolean(this.timeZoneData.isdsts[index]); }; ZonedDateTime.prototype.inspect = function() { var index = getUntilsIndex(this.original, this.timeZoneData.untils); var abbrs = this.timeZoneData.abbrs; return this.local.toISOString().replace(/Z$/, "") + " " + (abbrs && abbrs[index] + " " || (this.getTimezoneOffset() * -1) + " ") + (this.isDST() ? "(daylight savings)" : ""); }; ZonedDateTime.prototype.toDate = function() { return new Date(this.getTime()); }; // Type cast getters. ["toISOString", "toJSON", "toUTCString"].forEach(function(method) { ZonedDateTime.prototype[method] = function() { return this.toDate()[method](); }; }); return ZonedDateTime; }()); /** * isLeapYear( year ) * * @year [Number] * * Returns an indication whether the specified year is a leap year. */ var dateIsLeapYear = function( year ) { return new Date( year, 1, 29 ).getMonth() === 1; }; /** * lastDayOfMonth( date ) * * @date [Date] * * Return the last day of the given date's month */ var dateLastDayOfMonth = function( date ) { return new Date( date.getFullYear(), date.getMonth() + 1, 0 ).getDate(); }; /** * startOf changes the input to the beginning of the given unit. * * For example, starting at the start of a day, resets hours, minutes * seconds and milliseconds to 0. Starting at the month does the same, but * also sets the date to 1. * * Returns the modified date */ var dateStartOf = function( date, unit ) { date = date instanceof ZonedDateTime ? date.clone() : new Date( date.getTime() ); switch ( unit ) { case "year": date.setMonth( 0 ); /* falls through */ case "month": date.setDate( 1 ); /* falls through */ case "day": date.setHours( 0 ); /* falls through */ case "hour": date.setMinutes( 0 ); /* falls through */ case "minute": date.setSeconds( 0 ); /* falls through */ case "second": date.setMilliseconds( 0 ); } return date; }; /** * Differently from native date.setDate(), this function returns a date whose * day remains inside the month boundaries. For example: * * setDate( FebDate, 31 ): a "Feb 28" date. * setDate( SepDate, 31 ): a "Sep 30" date. */ var dateSetDate = function( date, day ) { var lastDay = new Date( date.getFullYear(), date.getMonth() + 1, 0 ).getDate(); date.setDate( day < 1 ? 1 : day < lastDay ? day : lastDay ); }; /** * Differently from native date.setMonth(), this function adjusts date if * needed, so final month is always the one set. * * setMonth( Jan31Date, 1 ): a "Feb 28" date. * setDate( Jan31Date, 8 ): a "Sep 30" date. */ var dateSetMonth = function( date, month ) { var originalDate = date.getDate(); date.setDate( 1 ); date.setMonth( month ); dateSetDate( date, originalDate ); }; var outOfRange = function( value, low, high ) { return value < low || value > high; }; /** * parse( value, tokens, properties ) * * @value [String] string date. * * @tokens [Object] tokens returned by date/tokenizer. * * @properties [Object] output returned by date/tokenizer-properties. * * ref: http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns */ var dateParse = function( value, tokens, properties ) { var amPm, day, daysOfYear, month, era, hour, hour12, timezoneOffset, valid, YEAR = 0, MONTH = 1, DAY = 2, HOUR = 3, MINUTE = 4, SECOND = 5, MILLISECONDS = 6, date = new Date(), truncateAt = [], units = [ "year", "month", "day", "hour", "minute", "second", "milliseconds" ]; // Create globalize date with given timezone data. if ( properties.timeZoneData ) { date = new ZonedDateTime( date, properties.timeZoneData() ); } if ( !tokens.length ) { return null; } valid = tokens.every(function( token ) { var century, chr, value, length; if ( token.type === "literal" ) { // continue return true; } chr = token.type.charAt( 0 ); length = token.type.length; if ( chr === "j" ) { // Locale preferred hHKk. // http://www.unicode.org/reports/tr35/tr35-dates.html#Time_Data chr = properties.preferredTimeData; } switch ( chr ) { // Era case "G": truncateAt.push( YEAR ); era = +token.value; break; // Year case "y": value = token.value; if ( length === 2 ) { if ( outOfRange( value, 0, 99 ) ) { return false; } // mimic dojo/date/locale: choose century to apply, according to a sliding // window of 80 years before and 20 years after present year. century = Math.floor( date.getFullYear() / 100 ) * 100; value += century; if ( value > date.getFullYear() + 20 ) { value -= 100; } } date.setFullYear( value ); truncateAt.push( YEAR ); break; case "Y": // Year in "Week of Year" throw createErrorUnsupportedFeature({ feature: "year pattern `" + chr + "`" }); // Quarter (skip) case "Q": case "q": break; // Month case "M": case "L": if ( length <= 2 ) { value = token.value; } else { value = +token.value; } if ( outOfRange( value, 1, 12 ) ) { return false; } // Setting the month later so that we have the correct year and can determine // the correct last day of February in case of leap year. month = value; truncateAt.push( MONTH ); break; // Week (skip) case "w": // Week of Year. case "W": // Week of Month. break; // Day case "d": day = token.value; truncateAt.push( DAY ); break; case "D": daysOfYear = token.value; truncateAt.push( DAY ); break; case "F": // Day of Week in month. eg. 2nd Wed in July. // Skip break; // Week day case "e": case "c": case "E": // Skip. // value = arrayIndexOf( dateWeekDays, token.value ); break; // Period (AM or PM) case "a": amPm = token.value; break; // Hour case "h": // 1-12 value = token.value; if ( outOfRange( value, 1, 12 ) ) { return false; } hour = hour12 = true; date.setHours( value === 12 ? 0 : value ); truncateAt.push( HOUR ); break; case "K": // 0-11 value = token.value; if ( outOfRange( value, 0, 11 ) ) { return false; } hour = hour12 = true; date.setHours( value ); truncateAt.push( HOUR ); break; case "k": // 1-24 value = token.value; if ( outOfRange( value, 1, 24 ) ) { return false; } hour = true; date.setHours( value === 24 ? 0 : value ); truncateAt.push( HOUR ); break; case "H": // 0-23 value = token.value; if ( outOfRange( value, 0, 23 ) ) { return false; } hour = true; date.setHours( value ); truncateAt.push( HOUR ); break; // Minute case "m": value = token.value; if ( outOfRange( value, 0, 59 ) ) { return false; } date.setMinutes( value ); truncateAt.push( MINUTE ); break; // Second case "s": value = token.value; if ( outOfRange( value, 0, 59 ) ) { return false; } date.setSeconds( value ); truncateAt.push( SECOND ); break; case "A": date.setHours( 0 ); date.setMinutes( 0 ); date.setSeconds( 0 ); /* falls through */ case "S": value = Math.round( token.value * Math.pow( 10, 3 - length ) ); date.setMilliseconds( value ); truncateAt.push( MILLISECONDS ); break; // Zone case "z": case "Z": case "O": case "v": case "V": case "X": case "x": if ( typeof token.value === "number" ) { timezoneOffset = token.value; } break; } return true; }); if ( !valid ) { return null; } // 12-hour format needs AM or PM, 24-hour format doesn't, ie. return null // if amPm && !hour12 || !amPm && hour12. if ( hour && !( !amPm ^ hour12 ) ) { return null; } if ( era === 0 ) { // 1 BC = year 0 date.setFullYear( date.getFullYear() * -1 + 1 ); } if ( month !== undefined ) { dateSetMonth( date, month - 1 ); } if ( day !== undefined ) { if ( outOfRange( day, 1, dateLastDayOfMonth( date ) ) ) { return null; } date.setDate( day ); } else if ( daysOfYear !== undefined ) { if ( outOfRange( daysOfYear, 1, dateIsLeapYear( date.getFullYear() ) ? 366 : 365 ) ) { return null; } date.setMonth( 0 ); date.setDate( daysOfYear ); } if ( hour12 && amPm === "pm" ) { date.setHours( date.getHours() + 12 ); } if ( timezoneOffset !== undefined ) { date.setMinutes( date.getMinutes() + timezoneOffset - date.getTimezoneOffset() ); } // Truncate date at the most precise unit defined. Eg. // If value is "12/31", and pattern is "MM/dd": // => new Date( <current Year>, 12, 31, 0, 0, 0, 0 ); truncateAt = Math.max.apply( null, truncateAt ); date = dateStartOf( date, units[ truncateAt ] ); // Get date back from globalize date. if ( date instanceof ZonedDateTime ) { date = date.toDate(); } return date; }; /** * tokenizer( value, numberParser, properties ) * * @value [String] string date. * * @numberParser [Function] * * @properties [Object] output returned by date/tokenizer-properties. * * Returns an Array of tokens, eg. value "5 o'clock PM", pattern "h 'o''clock' a": * [{ * type: "h", * lexeme: "5" * }, { * type: "literal", * lexeme: " " * }, { * type: "literal", * lexeme: "o'clock" * }, { * type: "literal", * lexeme: " " * }, { * type: "a", * lexeme: "PM", * value: "pm" * }] * * OBS: lexeme's are always String and may return invalid ranges depending of the token type. * Eg. "99" for month number. * * Return an empty Array when not successfully parsed. */ var dateTokenizer = function( value, numberParser, properties ) { var digitsRe, valid, tokens = [], widths = [ "abbreviated", "wide", "narrow" ]; digitsRe = properties.digitsRe; value = looseMatching( value ); valid = properties.pattern.match( datePatternRe ).every(function( current ) { var aux, chr, length, numeric, tokenRe, token = {}; function hourFormatParse( tokenRe, numberParser ) { var aux, isPositive, match = value.match( tokenRe ); numberParser = numberParser || function( value ) { return +value; }; if ( !match ) { return false; } isPositive = match[ 1 ]; // hourFormat containing H only, e.g., `+H;-H` if ( match.length < 6 ) { aux = isPositive ? 1 : 3; token.value = numberParser( match[ aux ] ) * 60; // hourFormat containing H and m, e.g., `+HHmm;-HHmm` } else if ( match.length < 10 ) { aux = isPositive ? [ 1, 3 ] : [ 5, 7 ]; token.value = numberParser( match[ aux[ 0 ] ] ) * 60 + numberParser( match[ aux[ 1 ] ] ); // hourFormat containing H, m, and s e.g., `+HHmmss;-HHmmss` } else { aux = isPositive ? [ 1, 3, 5 ] : [ 7, 9, 11 ]; token.value = numberParser( match[ aux[ 0 ] ] ) * 60 + numberParser( match[ aux[ 1 ] ] ) + numberParser( match[ aux[ 2 ] ] ) / 60; } if ( isPositive ) { token.value *= -1; } return true; } function oneDigitIfLengthOne() { if ( length === 1 ) { // Unicode equivalent to /\d/ numeric = true; return tokenRe = digitsRe; } } function oneOrTwoDigitsIfLengthOne() { if ( length === 1 ) { // Unicode equivalent to /\d\d?/ numeric = true; return tokenRe = new RegExp( "^(" + digitsRe.source + "){1,2}" ); } } function oneOrTwoDigitsIfLengthOneOrTwo() { if ( length === 1 || length === 2 ) { // Unicode equivalent to /\d\d?/ numeric = true; return tokenRe = new RegExp( "^(" + digitsRe.source + "){1,2}" ); } } function twoDigitsIfLengthTwo() { if ( length === 2 ) { // Unicode equivalent to /\d\d/ numeric = true; return tokenRe = new RegExp( "^(" + digitsRe.source + "){2}" ); } } // Brute-force test every locale entry in an attempt to match the given value. // Return the first found one (and set token accordingly), or null. function lookup( path ) { var array = properties[ path.join( "/" ) ]; if ( !array ) { return null; } // array of pairs [key, value] sorted by desc value length. array.some(function( item ) { var valueRe = item[ 1 ]; if ( valueRe.test( value ) ) { token.value = item[ 0 ]; tokenRe = item[ 1 ]; return true; } }); return null; } token.type = current; chr = current.charAt( 0 ); length = current.length; if ( chr === "Z" ) { // Z..ZZZ: same as "xxxx". if ( length < 4 ) { chr = "x"; length = 4; // ZZZZ: same as "OOOO". } else if ( length < 5 ) { chr = "O"; length = 4; // ZZZZZ: same as "XXXXX" } else { chr = "X"; length = 5; } } if ( chr === "z" ) { if ( properties.standardOrDaylightTzName ) { token.value = null; tokenRe = properties.standardOrDaylightTzName; } } // v...vvv: "{shortRegion}", eg. "PT". // vvvv: "{regionName} {Time}" or "{regionName} {Time}", // e.g., "Pacific Time" // http://unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns if ( chr === "v" ) { if ( properties.genericTzName ) { token.value = null; tokenRe = properties.genericTzName; // Fall back to "V" format. } else { chr = "V"; length = 4; } } if ( chr === "V" && properties.timeZoneName ) { token.value = length === 2 ? properties.timeZoneName : null; tokenRe = properties.timeZoneNameRe; } switch ( chr ) { // Era case "G": lookup([ "gregorian/eras", length <= 3 ? "eraAbbr" : ( length === 4 ? "eraNames" : "eraNarrow" ) ]); break; // Year case "y": case "Y": numeric = true; // number l=1:+, l=2:{2}, l=3:{3,}, l=4:{4,}, ... if ( length === 1 ) { // Unicode equivalent to /\d+/. tokenRe = new RegExp( "^(" + digitsRe.source + ")+" ); } else if ( length === 2 ) { // Lenient parsing: there's no year pattern to indicate non-zero-padded 2-digits // year, so parser accepts both zero-padded and non-zero-padded for `yy`. // // Unicode equivalent to /\d\d?/ tokenRe = new RegExp( "^(" + digitsRe.source + "){1,2}" ); } else { // Unicode equivalent to /\d{length,}/ tokenRe = new RegExp( "^(" + digitsRe.source + "){" + length + ",}" ); } break; // Quarter case "Q": case "q": // number l=1:{1}, l=2:{2}. // lookup l=3... oneDigitIfLengthOne() || twoDigitsIfLengthTwo() || lookup([ "gregorian/quarters", chr === "Q" ? "format" : "stand-alone", widths[ length - 3 ] ]); break; // Month case "M": case "L": // number l=1:{1,2}, l=2:{2}. // lookup l=3... // // Lenient parsing: skeleton "yMd" (i.e., one M) may include MM for the pattern, // therefore parser accepts both zero-padded and non-zero-padded for M and MM. // Similar for L. oneOrTwoDigitsIfLengthOneOrTwo() || lookup([ "gregorian/months", chr === "M" ? "format" : "stand-alone", widths[ length - 3 ] ]); break; // Day case "D": // number {l,3}. if ( length <= 3 ) { // Equivalent to /\d{length,3}/ numeric = true; tokenRe = new RegExp( "^(" + digitsRe.source + "){" + length + ",3}" ); } break; case "W": case "F": // number l=1:{1}. oneDigitIfLengthOne(); break; // Week day case "e": case "c": // number l=1:{1}, l=2:{2}. // lookup for length >=3. if ( length <= 2 ) { oneDigitIfLengthOne() || twoDigitsIfLengthTwo(); break; } /* falls through */ case "E": if ( length === 6 ) { // Note: if short day names are not explicitly specified, abbreviated day // names are used instead http://www.unicode.org/reports/tr35/tr35-dates.html#months_days_quarters_eras lookup([ "gregorian/days", [ chr === "c" ? "stand-alone" : "format" ], "short" ]) || lookup([ "gregorian/days", [ chr === "c" ? "stand-alone" : "format" ], "abbreviated" ]); } else { lookup([ "gregorian/days", [ chr === "c" ? "stand-alone" : "format" ], widths[ length < 3 ? 0 : length - 3 ] ]); } break; // Period (AM or PM) case "a": lookup([ "gregorian/dayPeriods/format/wide" ]); break; // Week case "w": // number l1:{1,2}, l2:{2}. oneOrTwoDigitsIfLengthOne() || twoDigitsIfLengthTwo(); break; // Day, Hour, Minute, or Second case "d": case "h": case "H": case "K": case "k": case "j": case "m": case "s": // number l1:{1,2}, l2:{2}. // // Lenient parsing: // - skeleton "hms" (i.e., one m) always includes mm for the pattern, i.e., it's // impossible to use a different skeleton to parse non-zero-padded minutes, // therefore parser accepts both zero-padded and non-zero-padded for m. Similar // for seconds s. // - skeleton "hms" (i.e., one h) may include h or hh for the pattern, i.e., it's // impossible to use a different skeleton to parser non-zero-padded hours for some // locales, therefore parser accepts both zero-padded and non-zero-padded for h. // Similar for d (in skeleton yMd). oneOrTwoDigitsIfLengthOneOrTwo(); break; case "S": // number {l}. // Unicode equivalent to /\d{length}/ numeric = true; tokenRe = new RegExp( "^(" + digitsRe.source + "){" + length + "}" ); break; case "A": // number {l+5}. // Unicode equivalent to /\d{length+5}/ numeric = true; tokenRe = new RegExp( "^(" + digitsRe.source + "){" + ( length + 5 ) + "}" ); break; // Zone case "v": case "V": case "z": if ( tokenRe && tokenRe.test( value ) ) { break; } if ( chr === "V" && length === 2 ) { break; } /* falls through */ case "O": // O: "{gmtFormat}+H;{gmtFormat}-H" or "{gmtZeroFormat}", eg. "GMT-8" or "GMT". // OOOO: "{gmtFormat}{hourFormat}" or "{gmtZeroFormat}", eg. "GMT-08:00" or "GMT". if ( value === properties[ "timeZoneNames/gmtZeroFormat" ] ) { token.value = 0; tokenRe = properties[ "timeZoneNames/gmtZeroFormatRe" ]; } else { aux = properties[ "timeZoneNames/hourFormat" ].some(function( hourFormatRe ) { if ( hourFormatParse( hourFormatRe, numberParser ) ) { tokenRe = hourFormatRe; return true; } }); if ( !aux ) { return null; } } break; case "X": // Same as x*, except it uses "Z" for zero offset. if ( value === "Z" ) { token.value = 0; tokenRe = /^Z/; break; } /* falls through */ case "x": // x: hourFormat("+HH[mm];-HH[mm]") // xx: hourFormat("+HHmm;-HHmm") // xxx: hourFormat("+HH:mm;-HH:mm") // xxxx: hourFormat("+HHmm[ss];-HHmm[ss]") // xxxxx: hourFormat("+HH:mm[:ss];-HH:mm[:ss]") aux = properties.x.some(function( hourFormatRe ) { if ( hourFormatParse( hourFormatRe ) ) { tokenRe = hourFormatRe; return true; } }); if ( !aux ) { return null; } break; case "'": token.type = "literal"; tokenRe = new RegExp( "^" + regexpEscape( removeLiteralQuotes( current ) ) ); break; default: token.type = "literal"; tokenRe = new RegExp( "^" + regexpEscape( current ) ); } if ( !tokenRe ) { return false; } // Get lexeme and consume it. value = value.replace( tokenRe, function( lexeme ) { token.lexeme = lexeme; if ( numeric ) { token.value = numberParser( lexeme ); } return ""; }); if ( !token.lexeme ) { return false; } if ( numeric && isNaN( token.value ) ) { return false; } tokens.push( token ); return true; }); if ( value !== "" ) { valid = false; } return valid ? tokens : []; }; var dateParserFn = function( numberParser, parseProperties, tokenizerProperties ) { return function dateParser( value ) { var tokens; validateParameterPresence( value, "value" ); validateParameterTypeString( value, "value" ); tokens = dateTokenizer( value, numberParser, tokenizerProperties ); return dateParse( value, tokens, parseProperties ) || null; }; }; var objectFilter = function( object, testRe ) { var key, copy = {}; for ( key in object ) { if ( testRe.test( key ) ) { copy[ key ] = object[ key ]; } } return copy; }; /** * tokenizerProperties( pattern, cldr ) * * @pattern [String] raw pattern. * * @cldr [Cldr instance]. * * Return Object with data that will be used by tokenizer. */ var dateTokenizerProperties = function( pattern, cldr, timeZone ) { var digitsReSource, properties = { pattern: looseMatching( pattern ) }, timeSeparator = numberSymbol( "timeSeparator", cldr ), widths = [ "abbreviated", "wide", "narrow" ]; digitsReSource = numberNumberingSystemDigitsMap( cldr ); digitsReSource = digitsReSource ? "[" + digitsReSource + "]" : "\\d"; properties.digitsRe = new RegExp( digitsReSource ); // Transform: // - "+H;-H" -> /\+(\d\d?)|-(\d\d?)/ // - "+HH;-HH" -> /\+(\d\d)|-(\d\d)/ // - "+HHmm;-HHmm" -> /\+(\d\d)(\d\d)|-(\d\d)(\d\d)/ // - "+HH:mm;-HH:mm" -> /\+(\d\d):(\d\d)|-(\d\d):(\d\d)/ // // If gmtFormat is GMT{0}, the regexp must fill {0} in each side, e.g.: // - "+H;-H" -> /GMT\+(\d\d?)|GMT-(\d\d?)/ function hourFormatRe( hourFormat, gmtFormat, digitsReSource, timeSeparator ) { var re; if ( !digitsReSource ) { digitsReSource = "\\d"; } if ( !gmtFormat ) { gmtFormat = "{0}"; } re = hourFormat .replace( "+", "\\+" ) // Unicode equivalent to (\\d\\d) .replace( /HH|mm|ss/g, "((" + digitsReSource + "){2})" ) // Unicode equivalent to (\\d\\d?) .replace( /H|m/g, "((" + digitsReSource + "){1,2})" ); if ( timeSeparator ) { re = re.replace( /:/g, timeSeparator ); } re = re.split( ";" ).map(function( part ) { return gmtFormat.replace( "{0}", part ); }).join( "|" ); return new RegExp( "^" + re ); } function populateProperties( path, value ) { // Skip var skipRe = /(timeZoneNames\/zone|supplemental\/metaZones|timeZoneNames\/metazone|timeZoneNames\/regionFormat|timeZoneNames\/gmtFormat)/; if ( skipRe.test( path ) ) { return; } if ( !value ) { return; } // The `dates` and `calendars` trim's purpose is to reduce properties' key size only. path = path.replace( /^.*\/dates\//, "" ).replace( /calendars\//, "" ); // Specific filter for "gregorian/dayPeriods/format/wide". if ( path === "gregorian/dayPeriods/format/wide" ) { value = objectFilter( value, /^am|^pm/ ); } // Transform object into array of pairs [key, /value/], sort by desc value length. if ( isPlainObject( value ) ) { value = Object.keys( value ).map(function( key ) { return [ key, new RegExp( "^" + regexpEscape( looseMatching( value[ key ] ) ) ) ]; }).sort(function( a, b ) { return b[ 1 ].source.length - a[ 1 ].source.length; }); // If typeof value === "string". } else { value = looseMatching( value ); } properties[ path ] = value; } function regexpSourceSomeTerm( terms ) { return "(" + terms.filter(function( item ) { return item; }).reduce(function( memo, item ) { return memo + "|" + item; }) + ")"; } cldr.on( "get", populateProperties ); pattern.match( datePatternRe ).forEach(function( current ) { var aux, chr, daylightTzName, gmtFormat, length, standardTzName; chr = current.charAt( 0 ); length = current.length; if ( chr === "Z" ) { if ( length < 5 ) { chr = "O"; length = 4; } else { chr = "X"; length = 5; } } // z...zzz: "{shortRegion}", eg. "PST" or "PDT". // zzzz: "{regionName} {Standard Time}" or "{regionName} {Daylight Time}", // e.g., "Pacific Standard Time" or "Pacific Daylight Time". // http://unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns if ( chr === "z" ) { standardTzName = dateGetTimeZoneName( length, "standard", timeZone, cldr ); daylightTzName = dateGetTimeZoneName( length, "daylight", timeZone, cldr ); if ( standardTzName ) { standardTzName = regexpEscape( looseMatching( standardTzName ) ); } if ( daylightTzName ) { daylightTzName = regexpEscape( looseMatching( daylightTzName ) ); } if ( standardTzName || daylightTzName ) { properties.standardOrDaylightTzName = new RegExp( "^" + regexpSourceSomeTerm([ standardTzName, daylightTzName ]) ); } // Fall through the "O" format in case one name is missing. if ( !standardTzName || !daylightTzName ) { chr = "O"; if ( length < 4 ) { length = 1; } } } // v...vvv: "{shortRegion}", eg. "PT". // vvvv: "{regionName} {Time}" or "{regionName} {Time}", // e.g., "Pacific Time" // http://unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns if ( chr === "v" ) { if ( length !== 1 && length !== 4 ) { throw createErrorUnsupportedFeature({ feature: "timezone pattern `" + pattern + "`" }); } var genericTzName = dateGetTimeZoneName( length, "generic", timeZone, cldr ); if ( genericTzName ) { properties.genericTzName = new RegExp( "^" + regexpEscape( looseMatching( genericTzName ) ) ); chr = "O"; // Fall back to "V" format. } else { chr = "V"; length = 4; } } switch ( chr ) { // Era case "G": cldr.main([ "dates/calendars/gregorian/eras", length <= 3 ? "eraAbbr" : ( length === 4 ? "eraNames" : "eraNarrow" ) ]); break; // Year case "u": // Extended year. Need to be implemented. case "U": // Cyclic year name. Need to be implemented. throw createErrorUnsupportedFeature({ feature: "year pattern `" + chr + "`" }); // Quarter case "Q": case "q": if ( length > 2 ) { cldr.main([ "dates/calendars/gregorian/quarters", chr === "Q" ? "format" : "stand-alone", widths[ length - 3 ] ]); } break; // Month case "M": case "L": // number l=1:{1,2}, l=2:{2}. // lookup l=3... if ( length > 2 ) { cldr.main([ "dates/calendars/gregorian/months", chr === "M" ? "format" : "stand-alone", widths[ length - 3 ] ]); } break; // Day case "g": // Modified Julian day. Need to be implemented. throw createErrorUnsupportedFeature({ feature: "Julian day pattern `g`" }); // Week day case "e": case "c": // lookup for length >=3. if ( length <= 2 ) { break; } /* falls through */ case "E": if ( length === 6 ) { // Note: if short day names are not explicitly specified, abbreviated day // names are used instead http://www.unicode.org/reports/tr35/tr35-dates.html#months_days_quarters_eras cldr.main([ "dates/calendars/gregorian/days", [ chr === "c" ? "stand-alone" : "format" ], "short" ]) || cldr.main([ "dates/calendars/gregorian/days", [ chr === "c" ? "stand-alone" : "format" ], "abbreviated" ]); } else { cldr.main([ "dates/calendars/gregorian/days", [ chr === "c" ? "stand-alone" : "format" ], widths[ length < 3 ? 0 : length - 3 ] ]); } break; // Period (AM or PM) case "a": cldr.main( "dates/calendars/gregorian/dayPeriods/format/wide" ); break; // Zone case "V": if ( length === 1 ) { throw createErrorUnsupportedFeature({ feature: "timezone pattern `" + pattern + "`" }); } if ( timeZone ) { if ( length === 2 ) { // Skip looseMatching processing since timeZone is a canonical posix value. properties.timeZoneName = timeZone; properties.timeZoneNameRe = new RegExp( "^" + regexpEscape( timeZone ) ); break; } var timeZoneName, exemplarCity = cldr.main([ "dates/timeZoneNames/zone", timeZone, "exemplarCity" ]); if ( length === 3 ) { if ( !exemplarCity ) { exemplarCity = cldr.main([ "dates/timeZoneNames/zone/Etc/Unknown/exemplarCity" ]); } timeZoneName = exemplarCity; } if ( exemplarCity && length === 4 ) { timeZoneName = formatMessage( cldr.main( "dates/timeZoneNames/regionFormat" ), [ exemplarCity ] ); } if ( timeZoneName ) { timeZoneName = looseMatching( timeZoneName ); properties.timeZoneName = timeZoneName; properties.timeZoneNameRe = new RegExp( "^" + regexpEscape( timeZoneName ) ); } } if ( current === "v" ) { length = 1; } /* falls through */ case "z": case "O": gmtFormat = cldr.main( "dates/timeZoneNames/gmtFormat" ); cldr.main( "dates/timeZoneNames/gmtZeroFormat" ); cldr.main( "dates/timeZoneNames/hourFormat" ); properties[ "timeZoneNames/gmtZeroFormatRe" ] = new RegExp( "^" + regexpEscape( properties[ "timeZoneNames/gmtZeroFormat" ] ) ); aux = properties[ "timeZoneNames/hourFormat" ]; properties[ "timeZoneNames/hourFormat" ] = ( length < 4 ? [ dateTimezoneHourFormatHm( aux, "H" ), dateTimezoneHourFormatH( aux ) ] : [ dateTimezoneHourFormatHm( aux, "HH" ) ] ).map(function( hourFormat ) { return hourFormatRe( hourFormat, gmtFormat, digitsReSource, timeSeparator ); }); /* falls through */ case "X": case "x": // x: hourFormat("+HH[mm];-HH[mm]") // xx: hourFormat("+HHmm;-HHmm") // xxx: hourFormat("+HH:mm;-HH:mm") // xxxx: hourFormat("+HHmm[ss];-HHmm[ss]") // xxxxx: hourFormat("+HH:mm[:ss];-HH:mm[:ss]") properties.x = [ [ "+HHmm;-HHmm", "+HH;-HH" ], [ "+HHmm;-HHmm" ], [ "+HH:mm;-HH:mm" ], [ "+HHmmss;-HHmmss", "+HHmm;-HHmm" ], [ "+HH:mm:ss;-HH:mm:ss", "+HH:mm;-HH:mm" ] ][ length - 1 ].map(function( hourFormat ) { return hourFormatRe( hourFormat ); }); } }); cldr.off( "get", populateProperties ); return properties; }; /** * dayOfWeek( date, firstDay ) * * @date * * @firstDay the result of `dateFirstDayOfWeek( cldr )` * * Return the day of the week normalized by the territory's firstDay [0-6]. * Eg for "mon": * - return 0 if territory is GB, or BR, or DE, or FR (week starts on "mon"); * - return 1 if territory is US (week starts on "sun"); * - return 2 if territory is EG (week starts on "sat"); */ var dateDayOfWeek = function( date, firstDay ) { return ( date.getDay() - firstDay + 7 ) % 7; }; /** * distanceInDays( from, to ) * * Return the distance in days between from and to Dates. */ var dateDistanceInDays = function( from, to ) { var inDays = 864e5; return ( to.getTime() - from.getTime() ) / inDays; }; /** * dayOfYear * * Return the distance in days of the date to the begin of the year [0-d]. */ var dateDayOfYear = function( date ) { return Math.floor( dateDistanceInDays( dateStartOf( date, "year" ), date ) ); }; // Invert key and values, e.g., {"year": "yY"} ==> {"y": "year", "Y": "year"} var dateFieldsMap = objectInvert({ "era": "G", "year": "yY", "quarter": "qQ", "month": "ML", "week": "wW", "day": "dDF", "weekday": "ecE", "dayperiod": "a", "hour": "hHkK", "minute": "m", "second": "sSA", "zone": "zvVOxX" }, function( object, key, value ) { value.split( "" ).forEach(function( symbol ) { object[ symbol ] = key; }); return object; }); /** * millisecondsInDay */ var dateMillisecondsInDay = function( date ) { // TODO Handle daylight savings discontinuities return date - dateStartOf( date, "day" ); }; /** * hourFormat( date, format, timeSeparator, formatNumber ) * * Return date's timezone offset according to the format passed. * Eg for format when timezone offset is 180: * - "+H;-H": -3 * - "+HHmm;-HHmm": -0300 * - "+HH:mm;-HH:mm": -03:00 * - "+HH:mm:ss;-HH:mm:ss": -03:00:00 */ var dateTimezoneHourFormat = function( date, format, timeSeparator, formatNumber ) { var absOffset, offset = date.getTimezoneOffset(); absOffset = Math.abs( offset ); formatNumber = formatNumber || { 1: function( value ) { return stringPad( value, 1 ); }, 2: function( value ) { return stringPad( value, 2 ); } }; return format // Pick the correct sign side (+ or -). .split( ";" )[ offset > 0 ? 1 : 0 ] // Localize time separator .replace( ":", timeSeparator ) // Update hours offset. .replace( /HH?/, function( match ) { return formatNumber[ match.length ]( Math.floor( absOffset / 60 ) ); }) // Update minutes offset and return. .replace( /mm/, function() { return formatNumber[ 2 ]( Math.floor( absOffset % 60 ) ); }) // Update minutes offset and return. .replace( /ss/, function() { return formatNumber[ 2 ]( Math.floor( absOffset % 1 * 60 ) ); }); }; /** * format( date, properties ) * * @date [Date instance]. * * @properties * * TODO Support other calendar types. * * Disclosure: this function borrows excerpts of dojo/date/locale. */ var dateFormat = function( date, numberFormatters, properties ) { var parts = []; var timeSeparator = properties.timeSeparator; // create globalize date with given timezone data if ( properties.timeZoneData ) { date = new ZonedDateTime( date, properties.timeZoneData() ); } properties.pattern.replace( datePatternRe, function( current ) { var aux, dateField, type, value, chr = current.charAt( 0 ), length = current.length; if ( chr === "j" ) { // Locale preferred hHKk. // http://www.unicode.org/reports/tr35/tr35-dates.html#Time_Data chr = properties.preferredTime; } if ( chr === "Z" ) { // Z..ZZZ: same as "xxxx". if ( length < 4 ) { chr = "x"; length = 4; // ZZZZ: same as "OOOO". } else if ( length < 5 ) { chr = "O"; length = 4; // ZZZZZ: same as "XXXXX" } else { chr = "X"; length = 5; } } // z...zzz: "{shortRegion}", e.g., "PST" or "PDT". // zzzz: "{regionName} {Standard Time}" or "{regionName} {Daylight Time}", // e.g., "Pacific Standard Time" or "Pacific Daylight Time". if ( chr === "z" ) { if ( date.isDST ) { value = date.isDST() ? properties.daylightTzName : properties.standardTzName; } // Fall back to "O" format. if ( !value ) { chr = "O"; if ( length < 4 ) { length = 1; } } } switch ( chr ) { // Era case "G": value = properties.eras[ date.getFullYear() < 0 ? 0 : 1 ]; break; // Year case "y": // Plain year. // The length specifies the padding, but for two letters it also specifies the // maximum length. value = date.getFullYear(); if ( length === 2 ) { value = String( value ); value = +value.substr( value.length - 2 ); } break; case "Y": // Year in "Week of Year" // The length specifies the padding, but for two letters it also specifies the // maximum length. // yearInWeekofYear = date + DaysInAWeek - (dayOfWeek - firstDay) - minDays value = new Date( date.getTime() ); value.setDate( value.getDate() + 7 - dateDayOfWeek( date, properties.firstDay ) - properties.firstDay - properties.minDays ); value = value.getFullYear(); if ( length === 2 ) { value = String( value ); value = +value.substr( value.length - 2 ); } break; // Quarter case "Q": case "q": value = Math.ceil( ( date.getMonth() + 1 ) / 3 ); if ( length > 2 ) { value = properties.quarters[ chr ][ length ][ value ]; } break; // Month case "M": case "L": value = date.getMonth() + 1; if ( length > 2 ) { value = properties.months[ chr ][ length ][ value ]; } break; // Week case "w": // Week of Year. // woy = ceil( ( doy + dow of 1/1 ) / 7 ) - minDaysStuff ? 1 : 0. // TODO should pad on ww? Not documented, but I guess so. value = dateDayOfWeek( dateStartOf( date, "year" ), properties.firstDay ); value = Math.ceil( ( dateDayOfYear( date ) + value ) / 7 ) - ( 7 - value >= properties.minDays ? 0 : 1 ); break; case "W": // Week of Month. // wom = ceil( ( dom + dow of `1/month` ) / 7 ) - minDaysStuff ? 1 : 0. value = dateDayOfWeek( dateStartOf( date, "month" ), properties.firstDay ); value = Math.ceil( ( date.getDate() + value ) / 7 ) - ( 7 - value >= properties.minDays ? 0 : 1 ); break; // Day case "d": value = date.getDate(); break; case "D": value = dateDayOfYear( date ) + 1; break; case "F": // Day of Week in month. eg. 2nd Wed in July. value = Math.floor( date.getDate() / 7 ) + 1; break; // Week day case "e": case "c": if ( length <= 2 ) { // Range is [1-7] (deduced by example provided on documentation) // TODO Should pad with zeros (not specified in the docs)? value = dateDayOfWeek( date, properties.firstDay ) + 1; break; } /* falls through */ case "E": value = dateWeekDays[ date.getDay() ]; value = properties.days[ chr ][ length ][ value ]; break; // Period (AM or PM) case "a": value = properties.dayPeriods[ date.getHours() < 12 ? "am" : "pm" ]; break; // Hour case "h": // 1-12 value = ( date.getHours() % 12 ) || 12; break; case "H": // 0-23 value = date.getHours(); break; case "K": // 0-11 value = date.getHours() % 12; break; case "k": // 1-24 value = date.getHours() || 24; break; // Minute case "m": value = date.getMinutes(); break; // Second case "s": value = date.getSeconds(); break; case "S": value = Math.round( date.getMilliseconds() * Math.pow( 10, length - 3 ) ); break; case "A": value = Math.round( dateMillisecondsInDay( date ) * Math.pow( 10, length - 3 ) ); break; // Zone case "z": break; case "v": // v...vvv: "{shortRegion}", eg. "PT". // vvvv: "{regionName} {Time}", // e.g., "Pacific Time". if ( properties.genericTzName ) { value = properties.genericTzName; break; } /* falls through */ case "V": //VVVV: "{explarCity} {Time}", e.g., "Los Angeles Time" if ( properties.timeZoneName ) { value = properties.timeZoneName; break; } if ( current === "v" ) { length = 1; } /* falls through */ case "O": // O: "{gmtFormat}+H;{gmtFormat}-H" or "{gmtZeroFormat}", eg. "GMT-8" or "GMT". // OOOO: "{gmtFormat}{hourFormat}" or "{gmtZeroFormat}", eg. "GMT-08:00" or "GMT". if ( date.getTimezoneOffset() === 0 ) { value = properties.gmtZeroFormat; } else { // If O..OOO and timezone offset has non-zero minutes, show minutes. if ( length < 4 ) { aux = date.getTimezoneOffset(); aux = properties.hourFormat[ aux % 60 - aux % 1 === 0 ? 0 : 1 ]; } else { aux = properties.hourFormat; } value = dateTimezoneHourFormat( date, aux, timeSeparator, numberFormatters ); value = properties.gmtFormat.replace( /\{0\}/, value ); } break; case "X": // Same as x*, except it uses "Z" for zero offset. if ( date.getTimezoneOffset() === 0 ) { value = "Z"; break; } /* falls through */ case "x": // x: hourFormat("+HH[mm];-HH[mm]") // xx: hourFormat("+HHmm;-HHmm") // xxx: hourFormat("+HH:mm;-HH:mm") // xxxx: hourFormat("+HHmm[ss];-HHmm[ss]") // xxxxx: hourFormat("+HH:mm[:ss];-HH:mm[:ss]") aux = date.getTimezoneOffset(); // If x and timezone offset has non-zero minutes, use xx (i.e., show minutes). if ( length === 1 && aux % 60 - aux % 1 !== 0 ) { length += 1; } // If (xxxx or xxxxx) and timezone offset has zero seconds, use xx or xxx // respectively (i.e., don't show optional seconds). if ( ( length === 4 || length === 5 ) && aux % 1 === 0 ) { length -= 2; } value = [ "+HH;-HH", "+HHmm;-HHmm", "+HH:mm;-HH:mm", "+HHmmss;-HHmmss", "+HH:mm:ss;-HH:mm:ss" ][ length - 1 ]; value = dateTimezoneHourFormat( date, value, ":" ); break; // timeSeparator case ":": value = timeSeparator; break; // ' literals. case "'": value = removeLiteralQuotes( current ); break; // Anything else is considered a literal, including [ ,:/.@#], chinese, japonese, and // arabic characters. default: value = current; } if ( typeof value === "number" ) { value = numberFormatters[ length ]( value ); } dateField = dateFieldsMap[ chr ]; type = dateField ? dateField : "literal"; // Concat two consecutive literals if ( type === "literal" && parts.length && parts[ parts.length - 1 ].type === "literal" ) { parts[ parts.length - 1 ].value += value; return; } parts.push( { type: type, value: value } ); }); return parts; }; var dateToPartsFormatterFn = function( numberFormatters, properties ) { return function dateToPartsFormatter( value ) { validateParameterPresence( value, "value" ); validateParameterTypeDate( value, "value" ); return dateFormat( value, numberFormatters, properties ); }; }; function optionsHasStyle( options ) { return options.skeleton !== undefined || options.date !== undefined || options.time !== undefined || options.datetime !== undefined || options.raw !== undefined; } function validateRequiredCldr( path, value ) { validateCldr( path, value, { skip: [ /dates\/calendars\/gregorian\/dateTimeFormats\/availableFormats/, /dates\/calendars\/gregorian\/days\/.*\/short/, /dates\/timeZoneNames\/zone/, /dates\/timeZoneNames\/metazone/, /globalize-iana/, /supplemental\/metaZones/, /supplemental\/timeData\/(?!001)/, /supplemental\/weekData\/(?!001)/ ] }); } function validateOptionsPreset( options ) { validateOptionsPresetEach( "date", options ); validateOptionsPresetEach( "time", options ); validateOptionsPresetEach( "datetime", options ); } function validateOptionsPresetEach( type, options ) { var value = options[ type ]; validate( "E_INVALID_OPTIONS", "Invalid `{{type}: \"{value}\"}`.", value === undefined || [ "short", "medium", "long", "full" ].indexOf( value ) !== -1, { type: type, value: value } ); } function validateOptionsSkeleton( pattern, skeleton ) { validate( "E_INVALID_OPTIONS", "Invalid `{skeleton: \"{value}\"}` based on provided CLDR.", skeleton === undefined || ( typeof pattern === "string" && pattern ), { type: "skeleton", value: skeleton } ); } function validateRequiredIana( timeZone ) { return function( path, value ) { if ( !/globalize-iana/.test( path ) ) { return; } validate( "E_MISSING_IANA_TZ", "Missing required IANA timezone content for `{timeZone}`: `{path}`.", value, { path: path.replace( /globalize-iana\//, "" ), timeZone: timeZone } ); }; } /** * .loadTimeZone( json ) * * @json [JSON] * * Load IANA timezone data. */ Globalize.loadTimeZone = function( json ) { var customData = { "globalize-iana": json }; validateParameterPresence( json, "json" ); validateParameterTypePlainObject( json, "json" ); Cldr.load( customData ); }; /** * .dateFormatter( options ) * * @options [Object] see date/expand_pattern for more info. * * Return a date formatter function (of the form below) according to the given options and the * default/instance locale. * * fn( value ) * * @value [Date] * * Return a function that formats a date according to the given `format` and the default/instance * locale. */ Globalize.dateFormatter = Globalize.prototype.dateFormatter = function( options ) { var args, dateToPartsFormatter, returnFn; validateParameterTypePlainObject( options, "options" ); options = options || {}; if ( !optionsHasStyle( options ) ) { options.skeleton = "yMd"; } args = [ options ]; dateToPartsFormatter = this.dateToPartsFormatter( options ); returnFn = dateFormatterFn( dateToPartsFormatter ); runtimeBind( args, this.cldr, returnFn, [ dateToPartsFormatter ] ); return returnFn; }; /** * .dateToPartsFormatter( options ) * * @options [Object] see date/expand_pattern for more info. * * Return a date formatter function (of the form below) according to the given options and the * default/instance locale. * * fn( value ) * * @value [Date] * * Return a function that formats a date to parts according to the given `format` * and the default/instance * locale. */ Globalize.dateToPartsFormatter = Globalize.prototype.dateToPartsFormatter = function( options ) { var args, cldr, numberFormatters, pad, pattern, properties, returnFn, timeZone, ianaListener; validateParameterTypePlainObject( options, "options" ); cldr = this.cldr; options = options || {}; if ( !optionsHasStyle( options ) ) { options.skeleton = "yMd"; } validateOptionsPreset( options ); validateDefaultLocale( cldr ); timeZone = options.timeZone; validateParameterTypeString( timeZone, "options.timeZone" ); args = [ options ]; cldr.on( "get", validateRequiredCldr ); if ( timeZone ) { ianaListener = validateRequiredIana( timeZone ); cldr.on( "get", ianaListener ); } pattern = dateExpandPattern( options, cldr ); validateOptionsSkeleton( pattern, options.skeleton ); properties = dateFormatProperties( pattern, cldr, timeZone ); cldr.off( "get", validateRequiredCldr ); if ( ianaListener ) { cldr.off( "get", ianaListener ); } // Create needed number formatters. numberFormatters = properties.numberFormatters; delete properties.numberFormatters; for ( pad in numberFormatters ) { numberFormatters[ pad ] = this.numberFormatter({ raw: numberFormatters[ pad ] }); } returnFn = dateToPartsFormatterFn( numberFormatters, properties ); runtimeBind( args, cldr, returnFn, [ numberFormatters, properties ] ); return returnFn; }; /** * .dateParser( options ) * * @options [Object] see date/expand_pattern for more info. * * Return a function that parses a string date according to the given `formats` and the * default/instance locale. */ Globalize.dateParser = Globalize.prototype.dateParser = function( options ) { var args, cldr, numberParser, parseProperties, pattern, returnFn, timeZone, tokenizerProperties; validateParameterTypePlainObject( options, "options" ); cldr = this.cldr; options = options || {}; if ( !optionsHasStyle( options ) ) { options.skeleton = "yMd"; } validateOptionsPreset( options ); validateDefaultLocale( cldr ); timeZone = options.timeZone; validateParameterTypeString( timeZone, "options.timeZone" ); args = [ options ]; cldr.on( "get", validateRequiredCldr ); if ( timeZone ) { cldr.on( "get", validateRequiredIana( timeZone ) ); } pattern = dateExpandPattern( options, cldr ); validateOptionsSkeleton( pattern, options.skeleton ); tokenizerProperties = dateTokenizerProperties( pattern, cldr, timeZone ); parseProperties = dateParseProperties( cldr, timeZone ); cldr.off( "get", validateRequiredCldr ); if ( timeZone ) { cldr.off( "get", validateRequiredIana( timeZone ) ); } numberParser = this.numberParser({ raw: "0" }); returnFn = dateParserFn( numberParser, parseProperties, tokenizerProperties ); runtimeBind( args, cldr, returnFn, [ numberParser, parseProperties, tokenizerProperties ] ); return returnFn; }; /** * .formatDate( value, options ) * * @value [Date] * * @options [Object] see date/expand_pattern for more info. * * Formats a date or number according to the given options string and the default/instance locale. */ Globalize.formatDate = Globalize.prototype.formatDate = function( value, options ) { validateParameterPresence( value, "value" ); validateParameterTypeDate( value, "value" ); return this.dateFormatter( options )( value ); }; /** * .formatDateToParts( value, options ) * * @value [Date] * * @options [Object] see date/expand_pattern for more info. * * Formats a date or number to parts according to the given options and the default/instance locale. */ Globalize.formatDateToParts = Globalize.prototype.formatDateToParts = function( value, options ) { validateParameterPresence( value, "value" ); validateParameterTypeDate( value, "value" ); return this.dateToPartsFormatter( options )( value ); }; /** * .parseDate( value, options ) * * @value [String] * * @options [Object] see date/expand_pattern for more info. * * Return a Date instance or null. */ Globalize.parseDate = Globalize.prototype.parseDate = function( value, options ) { validateParameterPresence( value, "value" ); validateParameterTypeString( value, "value" ); return this.dateParser( options )( value ); }; return Globalize; }));
/** * v1.0.45 generated on: Mon May 30 2016 15:59:00 GMT-0500 (CDT) * Copyright (c) 2014-2016, Ecor Ventures LLC. All Rights Reserved. See LICENSE (BSD). */ "use strict";if(window.NGN=window.NGN||{},window.NGN.DATA=window.NGN.DATA||{},!NGN.HTTP)throw new Error("NGN.DATA.Proxy requires NGN.HTTP.");window.NGN.DATA.Proxy=function(e){if(e=e||{},!e.store)throw new Error("NGN.DATA.Proxy requires a NGN.DATA.Store.");e.store.proxy=this,Object.defineProperties(this,{store:NGN.define(!0,!1,!1,e.store),url:NGN.define(!0,!0,!1,e.url||"http://localhost"),username:NGN.define(!0,!0,!1,e.username||null),password:NGN.define(!0,!0,!1,e.password||null),token:NGN.define(!0,!0,!1,e.token||null),actions:NGN._get(function(){return{create:e.store._created,update:e.store.records.filter(function(r){return e.store._created.indexOf(r)<0&&e.store._deleted.indexOf(r)<0?!1:r.modified}).map(function(e){return e}),"delete":e.store._deleted}}),save:NGN.define(!0,!1,!0,function(){}),fetch:NGN.define(!0,!1,!0,function(){})})},NGN.DATA.util.inherit(NGN.DATA.util.EventEmitter,NGN.DATA.Proxy);
import util from "../utils"; class ApplicationService { getServiceFramework(controller) { let sf = util.utilities.sf; sf.moduleRoot = "PersonaBar"; sf.controller = controller; return sf; } getGeneralSettings(callback) { const sf = this.getServiceFramework("SEO"); sf.get("GetGeneralSettings", {}, callback); } updateGeneralSettings(payload, callback, failureCallback) { const sf = this.getServiceFramework("SEO"); sf.post("UpdateGeneralSettings", payload, callback, failureCallback); } getRegexSettings(callback) { const sf = this.getServiceFramework("SEO"); sf.get("GetRegexSettings", {}, callback); } updateRegexSettings(payload, callback, failureCallback) { const sf = this.getServiceFramework("SEO"); sf.post("UpdateRegexSettings", payload, callback, failureCallback); } testUrl(pageId, queryString, customPageName, callback) { const sf = this.getServiceFramework("SEO"); sf.get("TestUrl?pageId=" + pageId + "&queryString=" + encodeURIComponent(queryString) + "&customPageName=" + encodeURIComponent(customPageName), {}, callback); } testUrlRewrite(uri, callback) { const sf = this.getServiceFramework("SEO"); sf.get("TestUrlRewrite?uri=" + uri, {}, callback); } getSitemapSettings(callback) { const sf = this.getServiceFramework("SEO"); sf.get("GetSitemapSettings", {}, callback); } updateSitemapSettings(payload, callback, failureCallback) { const sf = this.getServiceFramework("SEO"); sf.post("UpdateSitemapSettings", payload, callback, failureCallback); } getSitemapProviders(callback) { const sf = this.getServiceFramework("SEO"); sf.get("GetSitemapProviders", {}, callback); } updateSitemapProvider(payload, callback, failureCallback) { const sf = this.getServiceFramework("SEO"); sf.post("UpdateSitemapProvider", payload, callback, failureCallback); } createVerification(verification, callback, failureCallback) { const sf = this.getServiceFramework("SEO"); sf.post("CreateVerification?verification=" + verification, {}, callback, failureCallback); } clearCache(callback, failureCallback) { const sf = this.getServiceFramework("SEO"); sf.post("ResetCache", {}, callback, failureCallback); } getExtensionUrlProviders(callback) { const sf = this.getServiceFramework("SEO"); sf.get("GetExtensionUrlProviders", {}, callback); } updateExtensionUrlProviderStatus(payload, callback, failureCallback) { const sf = this.getServiceFramework("SEO"); sf.post("UpdateExtensionUrlProviderStatus", payload, callback, failureCallback); } } const applicationService = new ApplicationService(); export default applicationService;
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ 'use strict'; // THIS CHECK SHOULD BE THE FIRST THING IN THIS FILE // This is to ensure that we catch env issues before we error while requiring other dependencies. const engines = require('./package.json').engines; require('./tools/check-environment')({ requiredNodeVersion: engines.node, requiredNpmVersion: engines.npm, requiredYarnVersion: engines.yarn }); const gulp = require('gulp'); // See `tools/gulp-tasks/README.md` for information about task loading. function loadTask(fileName, taskName) { const taskModule = require('./tools/gulp-tasks/' + fileName); const task = taskName ? taskModule[taskName] : taskModule; return task(gulp); } gulp.task('format:enforce', loadTask('format', 'enforce')); gulp.task('format', loadTask('format', 'format')); gulp.task('build.sh', loadTask('build', 'all')); gulp.task('build.sh:no-bundle', loadTask('build', 'no-bundle')); gulp.task('public-api:enforce', loadTask('public-api', 'enforce')); gulp.task('public-api:update', ['build.sh'], loadTask('public-api', 'update')); gulp.task('lint', ['format:enforce', 'validate-commit-messages', 'tslint']); gulp.task('tslint', ['tools:build'], loadTask('lint')); gulp.task('validate-commit-messages', loadTask('validate-commit-message')); gulp.task('tools:build', loadTask('tools-build')); gulp.task('check-cycle', loadTask('check-cycle')); gulp.task('serve', loadTask('serve', 'default')); gulp.task('serve-examples', loadTask('serve', 'examples')); gulp.task('changelog', loadTask('changelog')); gulp.task('check-env', () => {/* this is a noop because the env test ran already above */});
function initMessaging(){var e=[];chrome.runtime.onMessage.addListener(function(n,t){n.source=n.target=kango,"undefined"!=typeof n.tab&&(kango.tab.isPrivate=function(){return n.tab.isPrivate});for(var r=0;r<e.length;r++)e[r](n)}),kango.dispatchMessage=function(e,n){var t={name:e,data:n,origin:"tab",source:null,target:null};return chrome.runtime.sendMessage(t),!0},kango.addEventListener=function(n,t){if("message"==n){for(var r=0;r<e.length;r++)if(e[r]==t)return;e.push(t)}}}kango.browser={getName:function(){return"chrome"}},kango.io={getResourceUrl:function(e){return chrome.extension.getURL(e)}};
QUnit.module('pages > strategy > tabs > logger', function () { const logger = KC3StrategyTabs.logger.definition; QUnit.module('filters > logTypes', { beforeEach() { this.subject = logger.filterFuncs.logTypes; }, }, function () { QUnit.test('check type is set to visible', function (assert) { logger.filterState.logTypes = { yellow: true, purple: false }; assert.ok(this.subject({ type: 'yellow' })); assert.notOk(this.subject({ type: 'purple' })); }); }); QUnit.module('filters > contexts', { beforeEach() { this.subject = logger.filterFuncs.contexts; }, }, function () { QUnit.test('check context is set to visible', function (assert) { logger.filterState.contexts = { banana: true, potato: false }; assert.ok(this.subject({ context: 'banana' })); assert.notOk(this.subject({ context: 'potato' })); }); }); QUnit.module('filters > logSearch', { beforeEach() { this.subject = logger.filterFuncs.logSearch; }, }, function () { QUnit.test('search message', function (assert) { logger.filterState.logSearch = 'small'; assert.equal(this.subject({ message: 'a big blue dog' }), false); assert.equal(this.subject({ message: 'a small blue dog' }), true); }); QUnit.test('search data', function (assert) { logger.filterState.logSearch = 'banana'; assert.equal(this.subject({ data: ['red', 'blue'] }), false); assert.equal(this.subject({ data: ['apple', 'orange', 'banana'] }), true); }); QUnit.test('case-insensitive search', function (assert) { logger.filterState.logSearch = 'tea'; assert.equal(this.subject({ message: 'Drinks', data: ['Coffee', 'TEA'] }), true); }); }); QUnit.module('isDateSplit', { beforeEach() { this.subject = logger.isDateSplit; }, }, function () { QUnit.test('true if specified times are on different days', function (assert) { const result = this.subject({ timestamp: new Date(2017, 1, 1).getTime() }, { timestamp: new Date(2017, 1, 2).getTime() }); assert.equal(result, true); }); QUnit.test('false if specified times are on the same day', function (assert) { const result = this.subject({ timestamp: new Date(2017, 1, 1, 5) }, { timestamp: new Date(2017, 1, 1, 20) }); assert.equal(result, false); }); }); QUnit.module('createDateSeparator', { beforeEach() { this.subject = logger.createDateSeparator; }, }, function () { QUnit.test('success', function (assert) { const entry = { timestamp: new Date().getTime() }; const result = this.subject(entry); assert.deepEqual(result, { type: 'dateSeparator', timestamp: entry.timestamp, }); }); }); QUnit.module('elementFactory > error > formatStack', { beforeEach() { this.subject = logger.formatStack; }, }, function () { QUnit.test('undefined stack', function (assert) { const result = this.subject(); assert.equal(result, ''); }); QUnit.test('replace chrome extension id', function (assert) { const stack = `at loadLogEntries (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/pages/strategy/tabs/logger/logger.js:56:18) at Object.execute (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/pages/strategy/tabs/logger/logger.js:30:21) at chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/library/objects/StrategyTab.js:80:21 at Object.success (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/library/objects/StrategyTab.js:40:6) at i (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/assets/js/jquery.min.js:2:27151) at Object.fireWith [as resolveWith] (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/assets/js/jquery.min.js:2:27914) at z (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/assets/js/jquery.min.js:4:12059) at XMLHttpRequest.<anonymous> (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/assets/js/jquery.min.js:4:15619)`; const result = this.subject(stack); assert.equal(result, `at loadLogEntries (src/pages/strategy/tabs/logger/logger.js:56:18) at Object.execute (src/pages/strategy/tabs/logger/logger.js:30:21) at src/library/objects/StrategyTab.js:80:21 at Object.success (src/library/objects/StrategyTab.js:40:6) at i (src/assets/js/jquery.min.js:2:27151) at Object.fireWith [as resolveWith] (src/assets/js/jquery.min.js:2:27914) at z (src/assets/js/jquery.min.js:4:12059) at XMLHttpRequest.<anonymous> (src/assets/js/jquery.min.js:4:15619)`); }); }); QUnit.module('getCallsite', { beforeEach() { this.subject = logger.getCallsite; }, }, function () { QUnit.test('named function', function (assert) { const stack = `Error: message at loadLogEntries (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/pages/strategy/tabs/logger/logger.js:56:18) at Object.execute (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/pages/strategy/tabs/logger/logger.js:30:21) at chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/library/objects/StrategyTab.js:80:21 at Object.success (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/library/objects/StrategyTab.js:40:6) at i (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/assets/js/jquery.min.js:2:27151) at Object.fireWith [as resolveWith] (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/assets/js/jquery.min.js:2:27914) at z (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/assets/js/jquery.min.js:4:12059) at XMLHttpRequest.<anonymous> (chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/assets/js/jquery.min.js:4:15619)`; const result = this.subject(stack); assert.deepEqual(result, { short: 'logger.js:56', full: 'src/pages/strategy/tabs/logger/logger.js:56:18', }); }); QUnit.test('anonymous function', function (assert) { const stack = `Error: gameScreenChg at chrome-extension://hgnaklcechmjlpaeamgcnagnhpjhllne/library/modules/Service.js:471:12 at EventImpl.dispatchToListener (extensions::event_bindings:388:22) at Event.publicClassPrototype.(anonymous function) [as dispatchToListener] (extensions::utils:149:26) at EventImpl.dispatch_ (extensions::event_bindings:372:35) at EventImpl.dispatch (extensions::event_bindings:394:17) at Event.publicClassPrototype.(anonymous function) [as dispatch] (extensions::utils:149:26) at messageListener (extensions::messaging:196:29)`; const result = this.subject(stack); assert.deepEqual(result, { short: 'Service.js:471', full: 'src/library/modules/Service.js:471:12', }); }); }); });
import { installation as ActionTypes, extension as ExtensionActionTypes } from "constants/actionTypes"; import { InstallationService } from "services"; const installationActions = { parsePackage(file, callback, errorCallback) { return (dispatch) => { InstallationService.parsePackage(file, (data) => { dispatch({ type: ActionTypes.PARSED_INSTALLATION_PACKAGE, payload: JSON.parse(data) }); if (callback) { callback(data); } }, errorCallback); }; }, navigateWizard(wizardStep, callback) { return (dispatch) => { dispatch({ type: ActionTypes.GO_TO_WIZARD_STEP, payload: { wizardStep } }); if (callback) { setTimeout(() => { callback(); }, 0); } }; }, setInstallingAvailablePackage(FileName, PackageType, callback) { return (dispatch) => { dispatch({ type: ActionTypes.INSTALLING_AVAILABLE_PACKAGE, payload: { PackageType, FileName } }); if (callback) { setTimeout(() => { callback(); }, 0); } }; }, notInstallingAvailablePackage(callback) { return (dispatch) => { dispatch({ type: ActionTypes.NOT_INSTALLING_AVAILABLE_PACKAGE }); if (callback) { setTimeout(() => { callback(); }, 0); } }; }, installExtension(file, newExtension, legacyType, isPortalPackage, callback, addToList) { let _newExtension = JSON.parse(JSON.stringify(newExtension)); return (dispatch) => { InstallationService.installPackage(file, legacyType, isPortalPackage, (data) => { dispatch({ type: ActionTypes.INSTALLED_EXTENSION_LOGS, payload: JSON.parse(data) }); if (addToList) { _newExtension.packageId = JSON.parse(data).newPackageId; _newExtension.inUse = "No"; dispatch({ type: ExtensionActionTypes.INSTALLED_EXTENSION, payload: { PackageInfo: _newExtension, logs: JSON.parse(data).logs } }); } if (callback) { callback(data); } }); }; }, clearParsedInstallationPackage(callback) { return (dispatch) => { dispatch({ type: ActionTypes.CLEAR_PARSED_INSTALLATION_PACKAGE }); if (callback) { callback(); } }; }, toggleAcceptLicense(value, callback) { return (dispatch) => { dispatch({ type: ActionTypes.TOGGLE_ACCEPT_LICENSE, payload: value }); if (callback) { callback(); } }; }, setViewingLog(value, callback) { return (dispatch) => { dispatch({ type: ActionTypes.TOGGLE_VIEWING_LOG, payload: value }); if (callback) { callback(); } }; }, setIsPortalPackage(value, callback) { return (dispatch) => { dispatch({ type: ActionTypes.SET_IS_PORTAL_PACKAGE, payload: value }); if (callback) { callback(); } }; } }; export default installationActions;
'use strict'; /* Controllers */ app // Flot Chart controller .controller('FlotChartDemoCtrl', ['$scope', function($scope) { $scope.d = [ [1,6.5],[2,6.5],[3,7],[4,8],[5,7.5],[6,7],[7,6.8],[8,7],[9,7.2],[10,7],[11,6.8],[12,7] ]; $scope.d0_1 = [ [0,7],[1,6.5],[2,12.5],[3,7],[4,9],[5,6],[6,11],[7,6.5],[8,8],[9,7] ]; $scope.d0_2 = [ [0,4],[1,4.5],[2,7],[3,4.5],[4,3],[5,3.5],[6,6],[7,3],[8,4],[9,3] ]; $scope.d1_1 = [ [10, 120], [20, 70], [30, 70], [40, 60] ]; $scope.d1_2 = [ [10, 50], [20, 60], [30, 90], [40, 35] ]; $scope.d1_3 = [ [10, 80], [20, 40], [30, 30], [40, 20] ]; $scope.d2 = []; for (var i = 0; i < 20; ++i) { $scope.d2.push([i, Math.round( Math.sin(i)*100)/100] ); } $scope.d3 = [ { label: "iPhone5S", data: 40 }, { label: "iPad Mini", data: 10 }, { label: "iPad Mini Retina", data: 20 }, { label: "iPhone4S", data: 12 }, { label: "iPad Air", data: 18 } ]; $scope.refreshData = function(){ $scope.d0_1 = $scope.d0_2; }; $scope.getRandomData = function() { var data = [], totalPoints = 150; if (data.length > 0) data = data.slice(1); while (data.length < totalPoints) { var prev = data.length > 0 ? data[data.length - 1] : 50, y = prev + Math.random() * 10 - 5; if (y < 0) { y = 0; } else if (y > 100) { y = 100; } data.push(Math.round(y*100)/100); } // Zip the generated y values with the x values var res = []; for (var i = 0; i < data.length; ++i) { res.push([i, data[i]]) } return res; } $scope.d4 = $scope.getRandomData(); }]);
'use strict'; exports.baseTechPath = require.resolve('./level-proto.js');
import merge from "ember-data/system/merge"; import RootState from "ember-data/system/model/states"; import Relationships from "ember-data/system/relationships/state/create"; import Snapshot from "ember-data/system/snapshot"; import EmptyObject from "ember-data/system/empty-object"; var Promise = Ember.RSVP.Promise; var get = Ember.get; var set = Ember.set; var _extractPivotNameCache = new EmptyObject(); var _splitOnDotCache = new EmptyObject(); function splitOnDot(name) { return _splitOnDotCache[name] || ( _splitOnDotCache[name] = name.split('.') ); } function extractPivotName(name) { return _extractPivotNameCache[name] || ( _extractPivotNameCache[name] = splitOnDot(name)[0] ); } function retrieveFromCurrentState(key) { return function() { return get(this.currentState, key); }; } var guid = 0; /** `InternalModel` is the Model class that we use internally inside Ember Data to represent models. Internal ED methods should only deal with `InternalModel` objects. It is a fast, plain Javascript class. We expose `DS.Model` to application code, by materializing a `DS.Model` from `InternalModel` lazily, as a performance optimization. `InternalModel` should never be exposed to application code. At the boundaries of the system, in places like `find`, `push`, etc. we convert between Models and InternalModels. We need to make sure that the properties from `InternalModel` are correctly exposed/proxied on `Model` if they are needed. @class InternalModel */ export default function InternalModel(type, id, store, container, data) { this.type = type; this.id = id; this.store = store; this.container = container; this._data = data || new EmptyObject(); this.modelName = type.modelName; this.dataHasInitialized = false; //Look into making this lazy this._deferredTriggers = []; this._attributes = new EmptyObject(); this._inFlightAttributes = new EmptyObject(); this._relationships = new Relationships(this); this._recordArrays = undefined; this.currentState = RootState.empty; this.isReloading = false; this.isError = false; this.error = null; this[Ember.GUID_KEY] = guid++ + 'internal-model'; /* implicit relationships are relationship which have not been declared but the inverse side exists on another record somewhere For example if there was ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ name: DS.attr() }) ``` but there is also ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ name: DS.attr(), comments: DS.hasMany('comment') }) ``` would have a implicit post relationship in order to be do things like remove ourselves from the post when we are deleted */ this._implicitRelationships = new EmptyObject(); } InternalModel.prototype = { isEmpty: retrieveFromCurrentState('isEmpty'), isLoading: retrieveFromCurrentState('isLoading'), isLoaded: retrieveFromCurrentState('isLoaded'), hasDirtyAttributes: retrieveFromCurrentState('hasDirtyAttributes'), isSaving: retrieveFromCurrentState('isSaving'), isDeleted: retrieveFromCurrentState('isDeleted'), isNew: retrieveFromCurrentState('isNew'), isValid: retrieveFromCurrentState('isValid'), dirtyType: retrieveFromCurrentState('dirtyType'), constructor: InternalModel, materializeRecord: function() { Ember.assert("Materialized " + this.modelName + " record with id:" + this.id + "more than once", this.record === null || this.record === undefined); // lookupFactory should really return an object that creates // instances with the injections applied this.record = this.type._create({ store: this.store, container: this.container, _internalModel: this, currentState: get(this, 'currentState'), isError: this.isError, adapterError: this.error }); this._triggerDeferredTriggers(); }, recordObjectWillDestroy: function() { this.record = null; }, deleteRecord: function() { this.send('deleteRecord'); }, save: function(options) { var promiseLabel = "DS: Model#save " + this; var resolver = Ember.RSVP.defer(promiseLabel); this.store.scheduleSave(this, resolver, options); return resolver.promise; }, startedReloading: function() { this.isReloading = true; if (this.record) { set(this.record, 'isReloading', true); } }, finishedReloading: function() { this.isReloading = false; if (this.record) { set(this.record, 'isReloading', false); } }, reload: function() { this.startedReloading(); var record = this; var promiseLabel = "DS: Model#reload of " + this; return new Promise(function(resolve) { record.send('reloadRecord', resolve); }, promiseLabel).then(function() { record.didCleanError(); return record; }, function(error) { record.didError(error); throw error; }, "DS: Model#reload complete, update flags").finally(function () { record.finishedReloading(); record.updateRecordArrays(); }); }, getRecord: function() { if (!this.record) { this.materializeRecord(); } return this.record; }, unloadRecord: function() { this.send('unloadRecord'); }, eachRelationship: function(callback, binding) { return this.type.eachRelationship(callback, binding); }, eachAttribute: function(callback, binding) { return this.type.eachAttribute(callback, binding); }, inverseFor: function(key) { return this.type.inverseFor(key); }, setupData: function(data) { var changedKeys = this._changedKeys(data.attributes); merge(this._data, data.attributes); this.pushedData(); if (this.record) { this.record._notifyProperties(changedKeys); } this.didInitalizeData(); }, becameReady: function() { Ember.run.schedule('actions', this.store.recordArrayManager, this.store.recordArrayManager.recordWasLoaded, this); }, didInitalizeData: function() { if (!this.dataHasInitialized) { this.becameReady(); this.dataHasInitialized = true; } }, destroy: function() { if (this.record) { return this.record.destroy(); } }, /** @method createSnapshot @private */ createSnapshot: function(options) { var adapterOptions = options && options.adapterOptions; var snapshot = new Snapshot(this); snapshot.adapterOptions = adapterOptions; return snapshot; }, /** @method loadingData @private @param {Promise} promise */ loadingData: function(promise) { this.send('loadingData', promise); }, /** @method loadedData @private */ loadedData: function() { this.send('loadedData'); this.didInitalizeData(); }, /** @method notFound @private */ notFound: function() { this.send('notFound'); }, /** @method pushedData @private */ pushedData: function() { this.send('pushedData'); }, flushChangedAttributes: function() { this._inFlightAttributes = this._attributes; this._attributes = new EmptyObject(); }, /** @method adapterWillCommit @private */ adapterWillCommit: function() { this.send('willCommit'); }, /** @method adapterDidDirty @private */ adapterDidDirty: function() { this.send('becomeDirty'); this.updateRecordArraysLater(); }, /** @method send @private @param {String} name @param {Object} context */ send: function(name, context) { var currentState = get(this, 'currentState'); if (!currentState[name]) { this._unhandledEvent(currentState, name, context); } return currentState[name](this, context); }, notifyHasManyAdded: function(key, record, idx) { if (this.record) { this.record.notifyHasManyAdded(key, record, idx); } }, notifyHasManyRemoved: function(key, record, idx) { if (this.record) { this.record.notifyHasManyRemoved(key, record, idx); } }, notifyBelongsToChanged: function(key, record) { if (this.record) { this.record.notifyBelongsToChanged(key, record); } }, notifyPropertyChange: function(key) { if (this.record) { this.record.notifyPropertyChange(key); } }, rollbackAttributes: function() { var dirtyKeys = Object.keys(this._attributes); this._attributes = new EmptyObject(); if (get(this, 'isError')) { this._inFlightAttributes = new EmptyObject(); this.didCleanError(); } //Eventually rollback will always work for relationships //For now we support it only out of deleted state, because we //have an explicit way of knowing when the server acked the relationship change if (this.isDeleted()) { //TODO: Should probably move this to the state machine somehow this.becameReady(); } if (this.isNew()) { this.clearRelationships(); } if (this.isValid()) { this._inFlightAttributes = new EmptyObject(); } this.send('rolledBack'); this.record._notifyProperties(dirtyKeys); }, /** @method transitionTo @private @param {String} name */ transitionTo: function(name) { // POSSIBLE TODO: Remove this code and replace with // always having direct reference to state objects var pivotName = extractPivotName(name); var currentState = get(this, 'currentState'); var state = currentState; do { if (state.exit) { state.exit(this); } state = state.parentState; } while (!state.hasOwnProperty(pivotName)); var path = splitOnDot(name); var setups = []; var enters = []; var i, l; for (i=0, l=path.length; i<l; i++) { state = state[path[i]]; if (state.enter) { enters.push(state); } if (state.setup) { setups.push(state); } } for (i=0, l=enters.length; i<l; i++) { enters[i].enter(this); } set(this, 'currentState', state); //TODO Consider whether this is the best approach for keeping these two in sync if (this.record) { set(this.record, 'currentState', state); } for (i=0, l=setups.length; i<l; i++) { setups[i].setup(this); } this.updateRecordArraysLater(); }, _unhandledEvent: function(state, name, context) { var errorMessage = "Attempted to handle event `" + name + "` "; errorMessage += "on " + String(this) + " while in state "; errorMessage += state.stateName + ". "; if (context !== undefined) { errorMessage += "Called with " + Ember.inspect(context) + "."; } throw new Ember.Error(errorMessage); }, triggerLater: function() { var length = arguments.length; var args = new Array(length); for (var i = 0; i < length; i++) { args[i] = arguments[i]; } if (this._deferredTriggers.push(args) !== 1) { return; } Ember.run.scheduleOnce('actions', this, '_triggerDeferredTriggers'); }, _triggerDeferredTriggers: function() { //TODO: Before 1.0 we want to remove all the events that happen on the pre materialized record, //but for now, we queue up all the events triggered before the record was materialized, and flush //them once we have the record if (!this.record) { return; } for (var i=0, l= this._deferredTriggers.length; i<l; i++) { this.record.trigger.apply(this.record, this._deferredTriggers[i]); } this._deferredTriggers.length = 0; }, /** @method clearRelationships @private */ clearRelationships: function() { this.eachRelationship((name, relationship) => { if (this._relationships.has(name)) { var rel = this._relationships.get(name); rel.clear(); rel.destroy(); } }); Object.keys(this._implicitRelationships).forEach((key) => { this._implicitRelationships[key].clear(); this._implicitRelationships[key].destroy(); }); }, /** When a find request is triggered on the store, the user can optionally pass in attributes and relationships to be preloaded. These are meant to behave as if they came back from the server, except the user obtained them out of band and is informing the store of their existence. The most common use case is for supporting client side nested URLs, such as `/posts/1/comments/2` so the user can do `store.find('comment', 2, {post:1})` without having to fetch the post. Preloaded data can be attributes and relationships passed in either as IDs or as actual models. @method _preloadData @private @param {Object} preload */ _preloadData: function(preload) { //TODO(Igor) consider the polymorphic case Object.keys(preload).forEach((key) => { var preloadValue = get(preload, key); var relationshipMeta = this.type.metaForProperty(key); if (relationshipMeta.isRelationship) { this._preloadRelationship(key, preloadValue); } else { this._data[key] = preloadValue; } }); }, _preloadRelationship: function(key, preloadValue) { var relationshipMeta = this.type.metaForProperty(key); var type = relationshipMeta.type; if (relationshipMeta.kind === 'hasMany') { this._preloadHasMany(key, preloadValue, type); } else { this._preloadBelongsTo(key, preloadValue, type); } }, _preloadHasMany: function(key, preloadValue, type) { Ember.assert("You need to pass in an array to set a hasMany property on a record", Ember.isArray(preloadValue)); var internalModel = this; var recordsToSet = preloadValue.map((recordToPush) => { return internalModel._convertStringOrNumberIntoInternalModel(recordToPush, type); }); //We use the pathway of setting the hasMany as if it came from the adapter //because the user told us that they know this relationships exists already this._relationships.get(key).updateRecordsFromAdapter(recordsToSet); }, _preloadBelongsTo: function(key, preloadValue, type) { var recordToSet = this._convertStringOrNumberIntoInternalModel(preloadValue, type); //We use the pathway of setting the hasMany as if it came from the adapter //because the user told us that they know this relationships exists already this._relationships.get(key).setRecord(recordToSet); }, _convertStringOrNumberIntoInternalModel: function(value, type) { if (typeof value === 'string' || typeof value === 'number') { return this.store._internalModelForId(type, value); } if (value._internalModel) { return value._internalModel; } return value; }, /** @method updateRecordArrays @private */ updateRecordArrays: function() { this._updatingRecordArraysLater = false; this.store.dataWasUpdated(this.type, this); }, setId: function(id) { Ember.assert('A record\'s id cannot be changed once it is in the loaded state', this.id === null || this.id === id || this.isNew()); this.id = id; }, didError: function(error) { this.error = error; this.isError = true; if (this.record) { this.record.setProperties({ isError: true, adapterError: error }); } }, didCleanError: function() { this.error = null; this.isError = false; if (this.record) { this.record.setProperties({ isError: false, adapterError: null }); } }, /** If the adapter did not return a hash in response to a commit, merge the changed attributes and relationships into the existing saved data. @method adapterDidCommit */ adapterDidCommit: function(data) { if (data) { data = data.attributes; } this.didCleanError(); var changedKeys = this._changedKeys(data); merge(this._data, this._inFlightAttributes); if (data) { merge(this._data, data); } this._inFlightAttributes = new EmptyObject(); this.send('didCommit'); this.updateRecordArraysLater(); if (!data) { return; } this.record._notifyProperties(changedKeys); }, /** @method updateRecordArraysLater @private */ updateRecordArraysLater: function() { // quick hack (something like this could be pushed into run.once if (this._updatingRecordArraysLater) { return; } this._updatingRecordArraysLater = true; Ember.run.schedule('actions', this, this.updateRecordArrays); }, addErrorMessageToAttribute: function(attribute, message) { var record = this.getRecord(); get(record, 'errors').add(attribute, message); }, removeErrorMessageFromAttribute: function(attribute) { var record = this.getRecord(); get(record, 'errors').remove(attribute); }, clearErrorMessages: function() { var record = this.getRecord(); get(record, 'errors').clear(); }, // FOR USE DURING COMMIT PROCESS /** @method adapterDidInvalidate @private */ adapterDidInvalidate: function(errors) { var attribute; for (attribute in errors) { if (errors.hasOwnProperty(attribute)) { this.addErrorMessageToAttribute(attribute, errors[attribute]); } } this._saveWasRejected(); }, /** @method adapterDidError @private */ adapterDidError: function(error) { this.send('becameError'); this.didError(error); this._saveWasRejected(); }, _saveWasRejected: function() { var keys = Object.keys(this._inFlightAttributes); for (var i=0; i < keys.length; i++) { if (this._attributes[keys[i]] === undefined) { this._attributes[keys[i]] = this._inFlightAttributes[keys[i]]; } } this._inFlightAttributes = new EmptyObject(); }, /** Ember Data has 3 buckets for storing the value of an attribute on an internalModel. `_data` holds all of the attributes that have been acknowledged by a backend via the adapter. When rollbackAttributes is called on a model all attributes will revert to the record's state in `_data`. `_attributes` holds any change the user has made to an attribute that has not been acknowledged by the adapter. Any values in `_attributes` are have priority over values in `_data`. `_inFlightAttributes`. When a record is being synced with the backend the values in `_attributes` are copied to `_inFlightAttributes`. This way if the backend acknowledges the save but does not return the new state Ember Data can copy the values from `_inFlightAttributes` to `_data`. Without having to worry about changes made to `_attributes` while the save was happenign. Changed keys builds a list of all of the values that may have been changed by the backend after a successful save. It does this by iterating over each key, value pair in the payload returned from the server after a save. If the `key` is found in `_attributes` then the user has a local changed to the attribute that has not been synced with the server and the key is not included in the list of changed keys. If the value, for a key differs from the value in what Ember Data believes to be the truth about the backend state (A merger of the `_data` and `_inFlightAttributes` objects where `_inFlightAttributes` has priority) then that means the backend has updated the value and the key is added to the list of changed keys. @method _changedKeys @private */ _changedKeys: function(updates) { var changedKeys = []; if (updates) { var original, i, value, key; var keys = Object.keys(updates); var length = keys.length; original = merge(new EmptyObject(), this._data); original = merge(original, this._inFlightAttributes); for (i = 0; i < length; i++) { key = keys[i]; value = updates[key]; // A value in _attributes means the user has a local change to // this attributes. We never override this value when merging // updates from the backend so we should not sent a change // notification if the server value differs from the original. if (this._attributes[key] !== undefined) { continue; } if (!Ember.isEqual(original[key], value)) { changedKeys.push(key); } } } return changedKeys; }, toString: function() { if (this.record) { return this.record.toString(); } else { return `<${this.modelName}:${this.id}>`; } } };
import { sendMail } from '../functions/sendMail'; import { unsubscribe } from '../functions/unsubscribe'; export const Mailer = { sendMail, unsubscribe, };
/* flatpickr v4.2.1, @license MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.sv = {}))); }(this, (function (exports) { 'use strict'; var fp = typeof window !== "undefined" && window.flatpickr !== undefined ? window.flatpickr : { l10ns: {}, }; var Swedish = { firstDayOfWeek: 1, weekAbbreviation: "v", weekdays: { shorthand: ["Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"], longhand: [ "Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag", ], }, months: { shorthand: [ "Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec", ], longhand: [ "Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December", ], }, ordinal: function () { return "."; }, }; fp.l10ns.sv = Swedish; var sv = fp.l10ns; exports.Swedish = Swedish; exports['default'] = sv; Object.defineProperty(exports, '__esModule', { value: true }); })));
// ------------------------------------ // #POSTCSS - LOAD OPTIONS - OPTIONS // ------------------------------------ 'use strict' /** * * @method options * * @param {Object} options PostCSS Config * * @return {Object} options PostCSS Options */ module.exports = function options (options) { if (options.parser) { options.parser = require(options.parser) } if (options.syntax) { options.syntax = require(options.syntax) } if (options.stringifier) { options.stringifier = require(options.stringifier) } if (options.plugins) { delete options.plugins } return options }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const Command = require('../ember-cli/lib/models/command'); const test_1 = require("../tasks/test"); const config_1 = require("../models/config"); const common_tags_1 = require("common-tags"); const config = config_1.CliConfig.fromProject() || config_1.CliConfig.fromGlobal(); const testConfigDefaults = config.getPaths('defaults.build', [ 'progress', 'poll' ]); const TestCommand = Command.extend({ name: 'test', aliases: ['t'], description: 'Run unit tests in existing project.', works: 'insideProject', availableOptions: [ { name: 'watch', type: Boolean, aliases: ['w'], description: 'Run build when files change.' }, { name: 'code-coverage', type: Boolean, default: false, aliases: ['cc'], description: 'Coverage report will be in the coverage/ directory.' }, { name: 'config', type: String, aliases: ['c'], description: common_tags_1.oneLine `Use a specific config file. Defaults to the karma config file in .angular-cli.json.` }, { name: 'single-run', type: Boolean, aliases: ['sr'], description: 'Run tests a single time.' }, { name: 'progress', type: Boolean, default: testConfigDefaults['progress'], description: 'Log progress to the console while in progress.' }, { name: 'browsers', type: String, description: 'Override which browsers tests are run against.' }, { name: 'colors', type: Boolean, description: 'Enable or disable colors in the output (reporters and logs).' }, { name: 'log-level', type: String, description: 'Level of logging.' }, { name: 'port', type: Number, description: 'Port where the web server will be listening.' }, { name: 'reporters', type: String, description: 'List of reporters to use.' }, { name: 'sourcemaps', type: Boolean, default: true, aliases: ['sm', 'sourcemap'], description: 'Output sourcemaps.' }, { name: 'poll', type: Number, default: testConfigDefaults['poll'], description: 'Enable and define the file watching poll time period (milliseconds).' }, { name: 'environment', type: String, aliases: ['e'], description: 'Defines the build environment.' }, { name: 'app', type: String, aliases: ['a'], description: 'Specifies app name to use.' } ], run: function (commandOptions) { const testTask = new test_1.default({ ui: this.ui, project: this.project }); if (commandOptions.watch !== undefined && !commandOptions.watch) { // if not watching ensure karma is doing a single run commandOptions.singleRun = true; } return testTask.run(commandOptions); } }); TestCommand.overrideCore = true; exports.default = TestCommand; //# sourceMappingURL=/users/hansl/sources/angular-cli/commands/test.js.map
import Ember from "ember-metal/core"; import EmberObject from "ember-runtime/system/object"; import TargetActionSupport from "ember-runtime/mixins/target_action_support"; var originalLookup; QUnit.module("TargetActionSupport", { setup() { originalLookup = Ember.lookup; }, teardown() { Ember.lookup = originalLookup; } }); QUnit.test("it should return false if no target or action are specified", function() { expect(1); var obj = EmberObject.createWithMixins(TargetActionSupport); ok(false === obj.triggerAction(), "no target or action was specified"); }); QUnit.test("it should support actions specified as strings", function() { expect(2); var obj = EmberObject.createWithMixins(TargetActionSupport, { target: EmberObject.create({ anEvent() { ok(true, "anEvent method was called"); } }), action: 'anEvent' }); ok(true === obj.triggerAction(), "a valid target and action were specified"); }); QUnit.test("it should invoke the send() method on objects that implement it", function() { expect(3); var obj = EmberObject.createWithMixins(TargetActionSupport, { target: EmberObject.create({ send(evt, context) { equal(evt, 'anEvent', "send() method was invoked with correct event name"); equal(context, obj, "send() method was invoked with correct context"); } }), action: 'anEvent' }); ok(true === obj.triggerAction(), "a valid target and action were specified"); }); QUnit.test("it should find targets specified using a property path", function() { expect(2); var Test = {}; Ember.lookup = { Test: Test }; Test.targetObj = EmberObject.create({ anEvent() { ok(true, "anEvent method was called on global object"); } }); var myObj = EmberObject.createWithMixins(TargetActionSupport, { target: 'Test.targetObj', action: 'anEvent' }); ok(true === myObj.triggerAction(), "a valid target and action were specified"); }); QUnit.test("it should use an actionContext object specified as a property on the object", function() { expect(2); var obj = EmberObject.createWithMixins(TargetActionSupport, { action: 'anEvent', actionContext: {}, target: EmberObject.create({ anEvent(ctx) { ok(obj.actionContext === ctx, "anEvent method was called with the expected context"); } }) }); ok(true === obj.triggerAction(), "a valid target and action were specified"); }); QUnit.test("it should find an actionContext specified as a property path", function() { expect(2); var Test = {}; Ember.lookup = { Test: Test }; Test.aContext = {}; var obj = EmberObject.createWithMixins(TargetActionSupport, { action: 'anEvent', actionContext: 'Test.aContext', target: EmberObject.create({ anEvent(ctx) { ok(Test.aContext === ctx, "anEvent method was called with the expected context"); } }) }); ok(true === obj.triggerAction(), "a valid target and action were specified"); }); QUnit.test("it should use the target specified in the argument", function() { expect(2); var targetObj = EmberObject.create({ anEvent() { ok(true, "anEvent method was called"); } }); var obj = EmberObject.createWithMixins(TargetActionSupport, { action: 'anEvent' }); ok(true === obj.triggerAction({ target: targetObj }), "a valid target and action were specified"); }); QUnit.test("it should use the action specified in the argument", function() { expect(2); var obj = EmberObject.createWithMixins(TargetActionSupport, { target: EmberObject.create({ anEvent() { ok(true, "anEvent method was called"); } }) }); ok(true === obj.triggerAction({ action: 'anEvent' }), "a valid target and action were specified"); }); QUnit.test("it should use the actionContext specified in the argument", function() { expect(2); var context = {}; var obj = EmberObject.createWithMixins(TargetActionSupport, { target: EmberObject.create({ anEvent(ctx) { ok(context === ctx, "anEvent method was called with the expected context"); } }), action: 'anEvent' }); ok(true === obj.triggerAction({ actionContext: context }), "a valid target and action were specified"); }); QUnit.test("it should allow multiple arguments from actionContext", function() { expect(3); var param1 = 'someParam'; var param2 = 'someOtherParam'; var obj = EmberObject.createWithMixins(TargetActionSupport, { target: EmberObject.create({ anEvent(first, second) { ok(first === param1, "anEvent method was called with the expected first argument"); ok(second === param2, "anEvent method was called with the expected second argument"); } }), action: 'anEvent' }); ok(true === obj.triggerAction({ actionContext: [param1, param2] }), "a valid target and action were specified"); }); QUnit.test("it should use a null value specified in the actionContext argument", function() { expect(2); var obj = EmberObject.createWithMixins(TargetActionSupport, { target: EmberObject.create({ anEvent(ctx) { ok(null === ctx, "anEvent method was called with the expected context (null)"); } }), action: 'anEvent' }); ok(true === obj.triggerAction({ actionContext: null }), "a valid target and action were specified"); });
/** * 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. * * @format * @flow */ 'use strict'; import {BatchedBridge} from 'react-native/Libraries/ReactPrivate/ReactNativePrivateInterface'; // TODO @sema: Adjust types import type {ReactNativeType} from './ReactNativeTypes'; let ReactFabric; if (__DEV__) { ReactFabric = require('../implementations/ReactFabric-dev'); } else { ReactFabric = require('../implementations/ReactFabric-prod'); } BatchedBridge.registerCallableModule('ReactFabric', ReactFabric); module.exports = (ReactFabric: ReactNativeType);
version https://git-lfs.github.com/spec/v1 oid sha256:ac03974d85317d75edc2dc62eb1c40e9514aae0dcfe5e69e3a62c6d419484632 size 887
version https://git-lfs.github.com/spec/v1 oid sha256:98117aa63db915fed8f72d5c0c414049013e63982817c75864b5e01bb3997090 size 17927
"use strict";import"../../Stock/Indicators/SlowStochastic/SlowStochasticIndicator.js";
// 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. // Copyright 2006 Google Inc. All Rights Reserved. /** * @fileoverview Anchored viewport positioning class with both adjust and * resize options for the popup. * */ goog.provide('goog.positioning.MenuAnchoredPosition'); goog.require('goog.math.Box'); goog.require('goog.math.Coordinate'); goog.require('goog.math.Size'); goog.require('goog.positioning'); goog.require('goog.positioning.AnchoredViewportPosition'); goog.require('goog.positioning.Corner'); goog.require('goog.positioning.CornerBit'); goog.require('goog.positioning.Overflow'); goog.require('goog.positioning.OverflowStatus'); /** * Encapsulates a popup position where the popup is anchored at a corner of * an element. The positioning behavior changes based on the values of * opt_adjust and opt_resize. * * When using this positioning object it's recommended that the movable element * be absolutely positioned. * * @param {Element} anchorElement Element the movable element should be * anchored against. * @param {goog.positioning.Corner} corner Corner of anchored element the * movable element should be positioned at. * @param {boolean} opt_adjust Whether the positioning should be adjusted until * the element fits inside the viewport even if that means that the anchored * corners are ignored. * @param {boolean} opt_resize Whether the positioning should be adjusted until * the element fits inside the viewport on the X axis and it's heigh is * resized so if fits in the viewport. This take precedence over * opt_adjust. * @constructor * @extends {goog.positioning.AnchoredViewportPosition} */ goog.positioning.MenuAnchoredPosition = function(anchorElement, corner, opt_adjust, opt_resize) { goog.positioning.AnchoredViewportPosition.call(this, anchorElement, corner, opt_adjust); /** * Whether the positioning should be adjusted until the element fits inside * the viewport even if that means that the anchored corners are ignored. * @type {boolean|undefined} * @private */ this.resize_ = opt_resize; }; goog.inherits(goog.positioning.MenuAnchoredPosition, goog.positioning.AnchoredViewportPosition); /** * Repositions the movable element. * * @param {Element} movableElement Element to position. * @param {goog.positioning.Corner} movableCorner Corner of the movable element * that should be positioned adjacent to the anchored element. * @param {goog.math.Box} opt_margin A margin specifin pixels. * @param {goog.math.Size} opt_preferredSize Preferred size of the * moveableElement. */ goog.positioning.MenuAnchoredPosition.prototype.reposition = function(movableElement, movableCorner, opt_margin, opt_preferredSize) { if (this.resize_) { goog.positioning.positionAtAnchor(this.element, this.corner, movableElement, movableCorner, null, opt_margin, goog.positioning.Overflow.ADJUST_X | goog.positioning.Overflow.RESIZE_HEIGHT, opt_preferredSize); } else { goog.positioning.MenuAnchoredPosition.superClass_.reposition.call( this, movableElement, movableCorner, opt_margin, opt_preferredSize); } };
let x = { a: (b ? 1 : 2)};
angular.module('examples', []) .factory('formPostData', ['$document', function($document) { return function(url, fields) { var form = angular.element('<form style="display: none;" method="post" action="' + url + '" target="_blank"></form>'); angular.forEach(fields, function(value, name) { var input = angular.element('<input type="hidden" name="' + name + '">'); input.attr('value', value); form.append(input); }); $document.find('body').append(form); form[0].submit(); form.remove(); }; }]) .factory('openPlunkr', ['formPostData', '$http', '$q', function(formPostData, $http, $q) { return function(exampleFolder) { var exampleName = 'AngularJS Example'; // Load the manifest for the example $http.get(exampleFolder + '/manifest.json') .then(function(response) { return response.data; }) .then(function(manifest) { var filePromises = []; // Build a pretty title for the Plunkr var exampleNameParts = manifest.name.split('-'); exampleNameParts.unshift('AngularJS'); angular.forEach(exampleNameParts, function(part, index) { exampleNameParts[index] = part.charAt(0).toUpperCase() + part.substr(1); }); exampleName = exampleNameParts.join(' - '); angular.forEach(manifest.files, function(filename) { filePromises.push($http.get(exampleFolder + '/' + filename, { transformResponse: [] }) .then(function(response) { // The manifests provide the production index file but Plunkr wants // a straight index.html if (filename === "index-production.html") { filename = "index.html" } return { name: filename, content: response.data }; })); }); return $q.all(filePromises); }) .then(function(files) { var postData = {}; angular.forEach(files, function(file) { postData['files[' + file.name + ']'] = file.content; }); postData['tags[0]'] = "angularjs"; postData['tags[1]'] = "example"; postData.private = true; postData.description = exampleName; formPostData('http://plnkr.co/edit/?p=preview', postData); }); }; }]);
// Generated by CoffeeScript 1.4.0 var isDefined, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __slice = [].slice, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; window.serious = {}; window.serious.Utils = {}; isDefined = function(obj) { return typeof obj !== 'undefined' && obj !== null; }; jQuery.fn.opacity = function(int) { return $(this).css({ opacity: int }); }; window.serious.Utils.clone = function(obj) { var flags, key, newInstance; if (!(obj != null) || typeof obj !== 'object') { return obj; } if (obj instanceof Date) { return new Date(obj.getTime()); } if (obj instanceof RegExp) { flags = ''; if (obj.global != null) { flags += 'g'; } if (obj.ignoreCase != null) { flags += 'i'; } if (obj.multiline != null) { flags += 'm'; } if (obj.sticky != null) { flags += 'y'; } return new RegExp(obj.source, flags); } newInstance = new obj.constructor(); for (key in obj) { newInstance[key] = window.serious.Utils.clone(obj[key]); } return newInstance; }; jQuery.fn.cloneTemplate = function(dict, removeUnusedField) { var klass, nui, value; if (removeUnusedField == null) { removeUnusedField = false; } nui = $(this[0]).clone(); nui = nui.removeClass("template hidden").addClass("actual"); if (typeof dict === "object") { for (klass in dict) { value = dict[klass]; if (value !== null) { nui.find(".out." + klass).html(value); } } if (removeUnusedField) { nui.find(".out").each(function() { if ($(this).html() === "") { return $(this).remove(); } }); } } return nui; }; Object.size = function(obj) { var key, size; size = 0; for (key in obj) { if (obj.hasOwnProperty(key)) { size++; } } return size; }; window.serious.States = (function() { function States() { this.states = {}; } States.prototype.set = function(state, value, scope) { if (value == null) { value = true; } if (scope == null) { scope = document; } this.states[state] = value; return this._showState(state, value); }; States.prototype._showState = function(state, value, scope) { if (value == null) { value = true; } if (scope == null) { scope = document; } $(".when-" + state, scope).each(function(idx, element) { var expected_value; element = $(element); expected_value = element.data('state') || true; return $(element).toggleClass('hidden', expected_value.toString() !== value.toString()); }); return $(".when-not-" + state, scope).each(function(idx, element) { var expected_value; element = $(element); expected_value = element.data('state') || true; return $(element).toggleClass('hidden', expected_value.toString() === value.toString()); }); }; return States; })(); window.serious.Widget = (function() { function Widget() { this.cloneTemplate = __bind(this.cloneTemplate, this); this.show = __bind(this.show, this); this.hide = __bind(this.hide, this); this.get = __bind(this.get, this); this.set = __bind(this.set, this); } Widget.bindAll = function() { var first, firsts, _i, _len; firsts = 1 <= arguments.length ? __slice.call(arguments, 0) : []; if (firsts) { for (_i = 0, _len = firsts.length; _i < _len; _i++) { first = firsts[_i]; Widget.ensureWidget($(first)); } } return $(".widget").each(function() { var self; self = $(this); if (!self.hasClass('template') && !self.parents().hasClass('template')) { return Widget.ensureWidget(self); } }); }; Widget.ensureWidget = function(ui) { var widget, widget_class; ui = $(ui); if (!ui.length) { return null; } else if (ui[0]._widget != null) { return ui[0]._widget; } else { widget_class = Widget.getWidgetClass(ui); if (widget_class != null) { widget = new widget_class(); widget.bindUI(ui); return widget; } else { console.warn("widget not found for", ui); return null; } } }; Widget.getWidgetClass = function(ui) { return eval("(" + $(ui).attr("data-widget") + ")"); }; Widget.prototype.bindUI = function(ui) { var action, key, nui, value, _i, _len, _ref, _ref1, _results; this.ui = $(ui); if (this.ui[0]._widget) { delete this.ui[0]._widget; } this.ui[0]._widget = this; this.uis = {}; if (typeof this.UIS !== "undefined") { _ref = this.UIS; for (key in _ref) { value = _ref[key]; nui = this.ui.find(value); if (nui.length < 1) { console.warn("uis", key, "not found in", ui); } this.uis[key] = nui; } } if (this.ACTIONS != null) { _ref1 = this.ACTIONS; _results = []; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { action = _ref1[_i]; _results.push(this._bindClick(this.ui.find(".do[data-action=" + action + "]"), action)); } return _results; } }; Widget.prototype.set = function(field, value, context) { /* Set a value to all tag with the given data-field attribute. Field can be a dict or a field name. If it is a dict, the second parameter should be a context. The default context is the widget itself. */ var name, _value; if (typeof field === "object") { context = value || this.ui; for (name in field) { _value = field[name]; context.find(".out[data-field=" + name + "]").html(_value); } } else { context = context || this.ui; context.find(".out[data-field=" + field + "]").html(value); } return context; }; Widget.prototype.get = function(form) { var data; form = $(form); data = {}; form.find('input.in').each(function() { var input; input = $(this); if (!input.hasClass('template') && !input.parents().hasClass('template')) { return data[input.attr('name')] = input.val(); } }); return data; }; Widget.prototype.hide = function() { return this.ui.addClass("hidden"); }; Widget.prototype.show = function() { return this.ui.removeClass("hidden"); }; Widget.prototype.cloneTemplate = function(template_nui, dict, removeUnusedField) { var action, klass, nui, value, _i, _len, _ref; if (removeUnusedField == null) { removeUnusedField = false; } nui = template_nui.clone(); nui = nui.removeClass("template hidden").addClass("actual"); if (typeof dict === "object") { for (klass in dict) { value = dict[klass]; if (value !== null) { nui.find(".out." + klass).html(value); } } if (removeUnusedField) { nui.find(".out").each(function() { if ($(this).html() === "") { return $(this).remove(); } }); } } if (this.ACTIONS != null) { _ref = this.ACTIONS; for (_i = 0, _len = _ref.length; _i < _len; _i++) { action = _ref[_i]; this._bindClick(nui.find(".do[data-action=" + action + "]"), action); } } return nui; }; Widget.prototype._bindClick = function(nui, action) { var _this = this; if ((action != null) && __indexOf.call(this.ACTIONS, action) >= 0) { return nui.click(function(e) { _this[action](e); return e.preventDefault(); }); } }; return Widget; })(); window.serious.URL = (function() { function URL() { this.toString = __bind(this.toString, this); this.fromString = __bind(this.fromString, this); this.enableDynamicLinks = __bind(this.enableDynamicLinks, this); this.updateUrl = __bind(this.updateUrl, this); this.hasBeenAdded = __bind(this.hasBeenAdded, this); this.hasChanged = __bind(this.hasChanged, this); this.remove = __bind(this.remove, this); this.update = __bind(this.update, this); this.set = __bind(this.set, this); this.onStateChanged = __bind(this.onStateChanged, this); this.get = __bind(this.get, this); var _this = this; this.previousHash = []; this.handlers = []; this.hash = this.fromString(location.hash); $(window).hashchange(function() { var handler, _i, _len, _ref, _results; _this.previousHash = window.serious.Utils.clone(_this.hash); _this.hash = _this.fromString(location.hash); _ref = _this.handlers; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { handler = _ref[_i]; _results.push(handler()); } return _results; }); } URL.prototype.get = function(field) { if (field == null) { field = null; } if (field) { return this.hash[field]; } else { return this.hash; } }; URL.prototype.onStateChanged = function(handler) { return this.handlers.push(handler); }; URL.prototype.set = function(fields, silent) { var hash, key, value; if (silent == null) { silent = false; } hash = silent ? this.hash : window.serious.Utils.clone(this.hash); hash = []; for (key in fields) { value = fields[key]; if (isDefined(value)) { hash[key] = value; } } return this.updateUrl(hash); }; URL.prototype.update = function(fields, silent) { var hash, key, value; if (silent == null) { silent = false; } hash = silent ? this.hash : window.serious.Utils.clone(this.hash); for (key in fields) { value = fields[key]; if (isDefined(value)) { hash[key] = value; } else { delete hash[key]; } } return this.updateUrl(hash); }; URL.prototype.remove = function(key, silent) { var hash; if (silent == null) { silent = false; } hash = silent ? this.hash : window.serious.Utils.clone(this.hash); if (hash[key]) { delete hash[key]; } return this.updateUrl(hash); }; URL.prototype.hasChanged = function(key) { if (this.hash[key] != null) { if (this.previousHash[key] != null) { return this.hash[key].toString() !== this.previousHash[key].toString(); } else { return true; } } else { if (this.previousHash[key] != null) { return true; } } return false; }; URL.prototype.hasBeenAdded = function(key) { return console.error("not implemented"); }; URL.prototype.updateUrl = function(hash) { if (hash == null) { hash = null; } if (!hash || Object.size(hash) === 0) { return location.hash = '_'; } else { return location.hash = this.toString(hash); } }; URL.prototype.enableDynamicLinks = function(context) { var _this = this; if (context == null) { context = null; } return $("a.internal[href]", context).click(function(e) { var href, link; link = $(e.currentTarget); href = link.attr("data-href") || link.attr("href"); if (href[0] === "#") { if (href.length > 1 && href[1] === "+") { _this.update(_this.fromString(href.slice(2))); } else if (href.length > 1 && href[1] === "-") { _this.remove(_this.fromString(href.slice(2))); } else { _this.set(_this.fromString(href.slice(1))); } } return false; }); }; URL.prototype.fromString = function(value) { var hash, hash_list, item, key, key_value, val, _i, _len; value = value || location.hash; hash = {}; value = value.replace('!', ''); hash_list = value.split("&"); for (_i = 0, _len = hash_list.length; _i < _len; _i++) { item = hash_list[_i]; if (item != null) { key_value = item.split("="); if (key_value.length === 2) { key = key_value[0].replace("#", ""); val = key_value[1].replace("#", ""); hash[key] = val; } } } return hash; }; URL.prototype.toString = function(hash_list) { var i, key, new_hash, value; if (hash_list == null) { hash_list = null; } hash_list = hash_list || this.hash; new_hash = "!"; i = 0; for (key in hash_list) { value = hash_list[key]; if (i > 0) { new_hash += "&"; } new_hash += key + "=" + value; i++; } return new_hash; }; return URL; })();
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'autoembed', 'pl', { embeddingInProgress: 'Osadzanie wklejonego adresu URL...', embeddingFailed: 'Ten adres URL multimediów nie może być automatycznie osadzony.' } );
'use strict'; // There's an example D script here to showcase a "slow" handler where it's // wildcard'd by the route name. In "real life" you'd probably start with a // d script that breaks down the route -start and -done, and then you'd want // to see which handler is taking longest from there. // // $ node demo.js // $ curl localhost:9080/foo/bar // $ sudo ./handler-timing.d // ^C // // handler-6 // value ------------- Distribution ------------- count // -1 | 0 // 0 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10 // 1 | 0 // // parseAccept // value ------------- Distribution ------------- count // -1 | 0 // 0 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10 // 1 | 0 // // parseAuthorization // value ------------- Distribution ------------- count // -1 | 0 // 0 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10 // 1 | 0 // // parseDate // value ------------- Distribution ------------- count // -1 | 0 // 0 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10 // 1 | 0 // // parseQueryString // value ------------- Distribution ------------- count // -1 | 0 // 0 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10 // 1 | 0 // // parseUrlEncodedBody // value ------------- Distribution ------------- count // -1 | 0 // 0 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10 // 1 | 0 // // sendResult // value ------------- Distribution ------------- count // 1 | 0 // 2 |@@@@ 1 // 4 | 0 // 8 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 9 // 16 | 0 // // slowHandler // value ------------- Distribution ------------- count // 64 | 0 // 128 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 9 // 256 |@@@@ 1 // 512 | 0 // // getfoo // value ------------- Distribution ------------- count // 64 | 0 // 128 |@@@@ 1 // 256 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 9 // 512 | 0 var restify = require('../../lib'); var Logger = require('bunyan'); ///--- Globals var NAME = 'exampleapp'; ///--- Mainline var log = new Logger({ name: NAME, level: 'trace', service: NAME, serializers: restify.bunyan.serializers }); var server = restify.createServer({ name: NAME, Logger: log, formatters: { 'application/foo': function (req, res, body, cb) { if (body instanceof Error) { body = body.stack; } else if (Buffer.isBuffer(body)) { body = body.toString('base64'); } else { switch (typeof body) { case 'boolean': case 'number': case 'string': body = body.toString(); break; case 'undefined': body = ''; break; default: body = body === null ? '' : 'Demoing application/foo formatter; ' + JSON.stringify(body); break; } } return cb(null, body); } } }); server.use(restify.acceptParser(server.acceptable)); server.use(restify.authorizationParser()); server.use(restify.dateParser()); server.use(restify.queryParser()); server.use(restify.urlEncodedBodyParser()); server.use(function slowHandler(req, res, next) { setTimeout(function () { next(); }, 250); }); server.get({url: '/foo/:id', name: 'GetFoo'}, function (req, res, next) { next(); }, function sendResult(req, res, next) { res.contentType = 'application/foo'; res.send({ hello: req.params.id }); next(); }); server.head('/foo/:id', function (req, res, next) { res.send({ hello: req.params.id }); next(); }); server.put('/foo/:id', function (req, res, next) { res.send({ hello: req.params.id }); next(); }); server.post('/foo/:id', function (req, res, next) { res.json(201, req.params); next(); }); server.del('/foo/:id', function (req, res, next) { res.send(204); next(); }); server.on('after', function (req, res, name) { req.log.info('%s just finished: %d.', name, res.code); }); server.on('NotFound', function (req, res) { res.send(404, req.url + ' was not found'); }); server.listen(9080, function () { log.info('listening: %s', server.url); });
var foo = arr.map(v => ({ x: v.bar, y: v.bar * 2 })); var fn = () => ({}).key;
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v12.0.1 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var gridOptionsWrapper_1 = require("../gridOptionsWrapper"); var columnController_1 = require("../columnController/columnController"); var gridPanel_1 = require("../gridPanel/gridPanel"); var column_1 = require("../entities/column"); var context_1 = require("../context/context"); var headerContainer_1 = require("./headerContainer"); var eventService_1 = require("../eventService"); var events_1 = require("../events"); var scrollVisibleService_1 = require("../gridPanel/scrollVisibleService"); var HeaderRenderer = (function () { function HeaderRenderer() { } HeaderRenderer.prototype.init = function () { var _this = this; this.eHeaderViewport = this.gridPanel.getHeaderViewport(); this.eRoot = this.gridPanel.getRoot(); this.eHeaderOverlay = this.gridPanel.getHeaderOverlay(); this.centerContainer = new headerContainer_1.HeaderContainer(this.gridPanel.getHeaderContainer(), this.gridPanel.getHeaderViewport(), this.eRoot, null); this.childContainers = [this.centerContainer]; if (!this.gridOptionsWrapper.isForPrint()) { this.pinnedLeftContainer = new headerContainer_1.HeaderContainer(this.gridPanel.getPinnedLeftHeader(), null, this.eRoot, column_1.Column.PINNED_LEFT); this.pinnedRightContainer = new headerContainer_1.HeaderContainer(this.gridPanel.getPinnedRightHeader(), null, this.eRoot, column_1.Column.PINNED_RIGHT); this.childContainers.push(this.pinnedLeftContainer); this.childContainers.push(this.pinnedRightContainer); } this.childContainers.forEach(function (container) { return _this.context.wireBean(container); }); // when grid columns change, it means the number of rows in the header has changed and it's all new columns this.eventService.addEventListener(events_1.Events.EVENT_GRID_COLUMNS_CHANGED, this.onGridColumnsChanged.bind(this)); // shotgun way to get labels to change, eg from sum(amount) to avg(amount) this.eventService.addEventListener(events_1.Events.EVENT_COLUMN_VALUE_CHANGED, this.refreshHeader.bind(this)); // for resized, the individual cells take care of this, so don't need to refresh everything this.eventService.addEventListener(events_1.Events.EVENT_COLUMN_RESIZED, this.setPinnedColContainerWidth.bind(this)); this.eventService.addEventListener(events_1.Events.EVENT_DISPLAYED_COLUMNS_CHANGED, this.setPinnedColContainerWidth.bind(this)); this.eventService.addEventListener(events_1.Events.EVENT_SCROLL_VISIBILITY_CHANGED, this.onScrollVisibilityChanged.bind(this)); if (this.columnController.isReady()) { this.refreshHeader(); } }; HeaderRenderer.prototype.onScrollVisibilityChanged = function () { this.setPinnedColContainerWidth(); }; HeaderRenderer.prototype.forEachHeaderElement = function (callback) { this.childContainers.forEach(function (childContainer) { return childContainer.forEachHeaderElement(callback); }); }; HeaderRenderer.prototype.destroy = function () { this.childContainers.forEach(function (container) { return container.destroy(); }); }; HeaderRenderer.prototype.onGridColumnsChanged = function () { this.setHeight(); }; HeaderRenderer.prototype.refreshHeader = function () { this.setHeight(); this.childContainers.forEach(function (container) { return container.refresh(); }); this.setPinnedColContainerWidth(); }; HeaderRenderer.prototype.setHeight = function () { // if forPrint, overlay is missing if (this.eHeaderOverlay) { var rowHeight = this.gridOptionsWrapper.getHeaderHeight(); // we can probably get rid of this when we no longer need the overlay var dept = this.columnController.getHeaderRowCount(); this.eHeaderOverlay.style.height = rowHeight + 'px'; this.eHeaderOverlay.style.top = ((dept - 1) * rowHeight) + 'px'; } }; HeaderRenderer.prototype.setPinnedColContainerWidth = function () { // pinned col doesn't exist when doing forPrint if (this.gridOptionsWrapper.isForPrint()) { return; } var pinnedLeftWidthWithScroll = this.scrollVisibleService.getPinnedLeftWithScrollWidth(); var pinnedRightWidthWithScroll = this.scrollVisibleService.getPinnedRightWithScrollWidth(); this.eHeaderViewport.style.marginLeft = pinnedLeftWidthWithScroll + 'px'; this.eHeaderViewport.style.marginRight = pinnedRightWidthWithScroll + 'px'; }; __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper) ], HeaderRenderer.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.Autowired('columnController'), __metadata("design:type", columnController_1.ColumnController) ], HeaderRenderer.prototype, "columnController", void 0); __decorate([ context_1.Autowired('gridPanel'), __metadata("design:type", gridPanel_1.GridPanel) ], HeaderRenderer.prototype, "gridPanel", void 0); __decorate([ context_1.Autowired('context'), __metadata("design:type", context_1.Context) ], HeaderRenderer.prototype, "context", void 0); __decorate([ context_1.Autowired('eventService'), __metadata("design:type", eventService_1.EventService) ], HeaderRenderer.prototype, "eventService", void 0); __decorate([ context_1.Autowired('scrollVisibleService'), __metadata("design:type", scrollVisibleService_1.ScrollVisibleService) ], HeaderRenderer.prototype, "scrollVisibleService", void 0); __decorate([ context_1.PostConstruct, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], HeaderRenderer.prototype, "init", null); __decorate([ context_1.PreDestroy, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], HeaderRenderer.prototype, "destroy", null); HeaderRenderer = __decorate([ context_1.Bean('headerRenderer') ], HeaderRenderer); return HeaderRenderer; }()); exports.HeaderRenderer = HeaderRenderer;
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Generator for unique element IDs. * */ goog.provide('goog.ui.IdGenerator'); /** * Creates a new id generator. * @constructor */ goog.ui.IdGenerator = function() { }; goog.addSingletonGetter(goog.ui.IdGenerator); /** * Next unique ID to use * @type {number} * @private */ goog.ui.IdGenerator.prototype.nextId_ = 0; /** * Gets the next unique ID. * @return {string} The next unique identifier. */ goog.ui.IdGenerator.prototype.getNextUniqueId = function() { return ':' + (this.nextId_++).toString(36); }; /** * Default instance for id generation. Done as an instance instead of statics * so it's possible to inject a mock for unit testing purposes. * @type {goog.ui.IdGenerator} * @deprecated Use goog.ui.IdGenerator.getInstance() instead and do not refer * to goog.ui.IdGenerator.instance anymore. */ goog.ui.IdGenerator.instance = goog.ui.IdGenerator.getInstance();
version https://git-lfs.github.com/spec/v1 oid sha256:df5a7287a63d8b28fe1df2552b7f2deaa719327f8aa49fef192f5fb72bbbbaad size 4023
'use strict'; var path = require('path'); var mergeTrees = require('broccoli-merge-trees'); var SassCompiler = require('../broccoli-sass'); function SASSPlugin() { this.name = 'ember-cli-sass'; this.ext = ['scss', 'sass']; } SASSPlugin.prototype.toTree = function(tree, inputPath, outputPath, inputOptions) { var options = inputOptions; var inputTrees = [tree]; if (options.includePaths) { inputTrees = inputTrees.concat(options.includePaths); } var ext = options.extension || 'scss'; var paths = options.outputPaths; var trees = Object.keys(paths).map(function(file) { var input = path.join(inputPath, file + '.' + ext); var output = paths[file]; return new SassCompiler(inputTrees, input, output, options); }); return mergeTrees(trees); }; module.exports = { name: 'ember-cli-sass', setupPreprocessorRegistry: function(type, registry) { registry.add('css', new SASSPlugin()); }, };
declare class X { a: number; static b: number; c: number; }
/* YUI 3.17.2 (build 9c3c78e) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('axis-time-base', function (Y, NAME) { /** * Provides functionality for the handling of time axis data for a chart. * * @module charts * @submodule axis-time-base */ var Y_Lang = Y.Lang; /** * TimeImpl contains logic for time data. TimeImpl is used by the following classes: * <ul> * <li>{{#crossLink "TimeAxisBase"}}{{/crossLink}}</li> * <li>{{#crossLink "TimeAxis"}}{{/crossLink}}</li> * </ul> * * @class TimeImpl * @constructor * @submodule axis-time-base */ function TimeImpl() { } TimeImpl.NAME = "timeImpl"; TimeImpl.ATTRS = { /** * Method used for formatting a label. This attribute allows for the default label formatting method to overridden. * The method use would need to implement the arguments below and return a `String` or an `HTMLElement`. The default * implementation of the method returns a `String`. The output of this method will be rendered to the DOM using * `appendChild`. If you override the `labelFunction` method and return an html string, you will also need to override * the Axis' `appendLabelFunction` to accept html as a `String`. * <dl> * <dt>val</dt><dd>Label to be formatted. (`String`)</dd> * <dt>format</dt><dd>STRFTime string used to format the label. (optional)</dd> * </dl> * * @attribute labelFunction * @type Function */ /** * Pattern used by the `labelFunction` to format a label. * * @attribute labelFormat * @type String */ labelFormat: { value: "%b %d, %y" } }; TimeImpl.prototype = { /** * Type of data used in `Data`. * * @property _type * @readOnly * @private */ _type: "time", /** * Getter method for maximum attribute. * * @method _maximumGetter * @return Number * @private */ _maximumGetter: function () { var max = this._getNumber(this._setMaximum); if(!Y_Lang.isNumber(max)) { max = this._getNumber(this.get("dataMaximum")); } return parseFloat(max); }, /** * Setter method for maximum attribute. * * @method _maximumSetter * @param {Object} value * @private */ _maximumSetter: function (value) { this._setMaximum = this._getNumber(value); return value; }, /** * Getter method for minimum attribute. * * @method _minimumGetter * @return Number * @private */ _minimumGetter: function () { var min = this._getNumber(this._setMinimum); if(!Y_Lang.isNumber(min)) { min = this._getNumber(this.get("dataMinimum")); } return parseFloat(min); }, /** * Setter method for minimum attribute. * * @method _minimumSetter * @param {Object} value * @private */ _minimumSetter: function (value) { this._setMinimum = this._getNumber(value); return value; }, /** * Indicates whether or not the maximum attribute has been explicitly set. * * @method _getSetMax * @return Boolean * @private */ _getSetMax: function() { var max = this._getNumber(this._setMaximum); return (Y_Lang.isNumber(max)); }, /** * Indicates whether or not the minimum attribute has been explicitly set. * * @method _getSetMin * @return Boolean * @private */ _getSetMin: function() { var min = this._getNumber(this._setMinimum); return (Y_Lang.isNumber(min)); }, /** * Formats a label based on the axis type and optionally specified format. * * @method formatLabel * @param {Object} value * @param {Object} format Pattern used to format the value. * @return String */ formatLabel: function(val, format) { val = Y.DataType.Date.parse(val); if(format) { return Y.DataType.Date.format(val, {format:format}); } return val; }, /** * Constant used to generate unique id. * * @property GUID * @type String * @private */ GUID: "yuitimeaxis", /** * Type of data used in `Axis`. * * @property _dataType * @readOnly * @private */ _dataType: "time", /** * Gets an array of values based on a key. * * @method _getKeyArray * @param {String} key Value key associated with the data array. * @param {Array} data Array in which the data resides. * @return Array * @private */ _getKeyArray: function(key, data) { var obj, keyArray = [], i = 0, val, len = data.length; for(; i < len; ++i) { obj = data[i][key]; if(Y_Lang.isDate(obj)) { val = obj.valueOf(); } else { val = new Date(obj); if(Y_Lang.isDate(val)) { val = val.valueOf(); } else if(!Y_Lang.isNumber(obj)) { if(Y_Lang.isNumber(parseFloat(obj))) { val = parseFloat(obj); } else { if(typeof obj !== "string") { obj = obj; } val = new Date(obj).valueOf(); } } else { val = obj; } } keyArray[i] = val; } return keyArray; }, /** * Calculates the maximum and minimum values for the `Axis`. * * @method _updateMinAndMax * @private */ _updateMinAndMax: function() { var data = this.get("data"), max = 0, min = 0, len, num, i; if(data && data.length && data.length > 0) { len = data.length; max = min = data[0]; if(len > 1) { for(i = 1; i < len; i++) { num = data[i]; if(isNaN(num)) { continue; } max = Math.max(num, max); min = Math.min(num, min); } } } this._dataMaximum = max; this._dataMinimum = min; }, /** * Returns a coordinate corresponding to a data values. * * @method _getCoordFromValue * @param {Number} min The minimum for the axis. * @param {Number} max The maximum for the axis. * @param {Number} length The distance that the axis spans. * @param {Number} dataValue A value used to ascertain the coordinate. * @param {Number} offset Value in which to offset the coordinates. * @param {Boolean} reverse Indicates whether the coordinates should start from * the end of an axis. Only used in the numeric implementation. * @return Number * @private */ _getCoordFromValue: function(min, max, length, dataValue, offset) { var range, multiplier, valuecoord, isNumber = Y_Lang.isNumber; dataValue = this._getNumber(dataValue); if(isNumber(dataValue)) { range = max - min; multiplier = length/range; valuecoord = (dataValue - min) * multiplier; valuecoord = offset + valuecoord; } else { valuecoord = NaN; } return valuecoord; }, /** * Parses value into a number. * * @method _getNumber * @param val {Object} Value to parse into a number * @return Number * @private */ _getNumber: function(val) { if(Y_Lang.isDate(val)) { val = val.valueOf(); } else if(!Y_Lang.isNumber(val) && val) { val = new Date(val).valueOf(); } return val; } }; Y.TimeImpl = TimeImpl; /** * TimeAxisBase manages time data for an axis. * * @class TimeAxisBase * @extends AxisBase * @uses TimeImpl * @constructor * @param {Object} config (optional) Configuration parameters. * @submodule axis-time-base */ Y.TimeAxisBase = Y.Base.create("timeAxisBase", Y.AxisBase, [Y.TimeImpl]); }, '3.17.2', {"requires": ["axis-base"]});
/** * sp-pnp-js v2.0.6-beta.1 - A JavaScript library for SharePoint development. * MIT (https://github.com/SharePoint/PnP-JS-Core/blob/master/LICENSE) * Copyright (c) 2017 Microsoft * docs: http://officedev.github.io/PnP-JS-Core * source: https://github.com/SharePoint/PnP-JS-Core * bugs: https://github.com/SharePoint/PnP-JS-Core/issues */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["$pnp"] = factory(); else root["$pnp"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/assets/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 41); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) { Object.defineProperty(exports, "__esModule", { value: true }); var pnplibconfig_1 = __webpack_require__(4); var Util = (function () { function Util() { } /** * Gets a callback function which will maintain context across async calls. * Allows for the calling pattern getCtxCallback(thisobj, method, methodarg1, methodarg2, ...) * * @param context The object that will be the 'this' value in the callback * @param method The method to which we will apply the context and parameters * @param params Optional, additional arguments to supply to the wrapped method when it is invoked */ Util.getCtxCallback = function (context, method) { var params = []; for (var _i = 2; _i < arguments.length; _i++) { params[_i - 2] = arguments[_i]; } return function () { method.apply(context, params); }; }; /** * Tests if a url param exists * * @param name The name of the url paramter to check */ Util.urlParamExists = function (name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"); return regex.test(location.search); }; /** * Gets a url param value by name * * @param name The name of the paramter for which we want the value */ Util.getUrlParamByName = function (name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"); var results = regex.exec(location.search); return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); }; /** * Gets a url param by name and attempts to parse a bool value * * @param name The name of the paramter for which we want the boolean value */ Util.getUrlParamBoolByName = function (name) { var p = this.getUrlParamByName(name); var isFalse = (p === "" || /false|0/i.test(p)); return !isFalse; }; /** * Inserts the string s into the string target as the index specified by index * * @param target The string into which we will insert s * @param index The location in target to insert s (zero based) * @param s The string to insert into target at position index */ Util.stringInsert = function (target, index, s) { if (index > 0) { return target.substring(0, index) + s + target.substring(index, target.length); } return s + target; }; /** * Adds a value to a date * * @param date The date to which we will add units, done in local time * @param interval The name of the interval to add, one of: ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second'] * @param units The amount to add to date of the given interval * * http://stackoverflow.com/questions/1197928/how-to-add-30-minutes-to-a-javascript-date-object */ Util.dateAdd = function (date, interval, units) { var ret = new Date(date.toLocaleString()); // don't change original date switch (interval.toLowerCase()) { case "year": ret.setFullYear(ret.getFullYear() + units); break; case "quarter": ret.setMonth(ret.getMonth() + 3 * units); break; case "month": ret.setMonth(ret.getMonth() + units); break; case "week": ret.setDate(ret.getDate() + 7 * units); break; case "day": ret.setDate(ret.getDate() + units); break; case "hour": ret.setTime(ret.getTime() + units * 3600000); break; case "minute": ret.setTime(ret.getTime() + units * 60000); break; case "second": ret.setTime(ret.getTime() + units * 1000); break; default: ret = undefined; break; } return ret; }; /** * Loads a stylesheet into the current page * * @param path The url to the stylesheet * @param avoidCache If true a value will be appended as a query string to avoid browser caching issues */ Util.loadStylesheet = function (path, avoidCache) { if (avoidCache) { path += "?" + encodeURIComponent((new Date()).getTime().toString()); } var head = document.getElementsByTagName("head"); if (head.length > 0) { var e = document.createElement("link"); head[0].appendChild(e); e.setAttribute("type", "text/css"); e.setAttribute("rel", "stylesheet"); e.setAttribute("href", path); } }; /** * Combines an arbitrary set of paths ensuring that the slashes are normalized * * @param paths 0 to n path parts to combine */ Util.combinePaths = function () { var paths = []; for (var _i = 0; _i < arguments.length; _i++) { paths[_i] = arguments[_i]; } return paths .filter(function (path) { return !Util.stringIsNullOrEmpty(path); }) .map(function (path) { return path.replace(/^[\\|\/]/, "").replace(/[\\|\/]$/, ""); }) .join("/") .replace(/\\/g, "/"); }; /** * Gets a random string of chars length * * @param chars The length of the random string to generate */ Util.getRandomString = function (chars) { var text = new Array(chars); var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i < chars; i++) { text[i] = possible.charAt(Math.floor(Math.random() * possible.length)); } return text.join(""); }; /** * Gets a random GUID value * * http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript */ /* tslint:disable no-bitwise */ Util.getGUID = function () { var d = new Date().getTime(); var guid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c === "x" ? r : (r & 0x3 | 0x8)).toString(16); }); return guid; }; /* tslint:enable */ /** * Determines if a given value is a function * * @param candidateFunction The thing to test for being a function */ Util.isFunction = function (candidateFunction) { return typeof candidateFunction === "function"; }; /** * @returns whether the provided parameter is a JavaScript Array or not. */ Util.isArray = function (array) { if (Array.isArray) { return Array.isArray(array); } return array && typeof array.length === "number" && array.constructor === Array; }; /** * Determines if a string is null or empty or undefined * * @param s The string to test */ Util.stringIsNullOrEmpty = function (s) { return typeof s === "undefined" || s === null || s.length < 1; }; /** * Provides functionality to extend the given object by doing a shallow copy * * @param target The object to which properties will be copied * @param source The source object from which properties will be copied * @param noOverwrite If true existing properties on the target are not overwritten from the source * */ Util.extend = function (target, source, noOverwrite) { if (noOverwrite === void 0) { noOverwrite = false; } if (source === null || typeof source === "undefined") { return target; } // ensure we don't overwrite things we don't want overwritten var check = noOverwrite ? function (o, i) { return !(i in o); } : function () { return true; }; return Object.getOwnPropertyNames(source) .filter(function (v) { return check(target, v); }) .reduce(function (t, v) { t[v] = source[v]; return t; }, target); }; /** * Determines if a given url is absolute * * @param url The url to check to see if it is absolute */ Util.isUrlAbsolute = function (url) { return /^https?:\/\/|^\/\//i.test(url); }; /** * Ensures that a given url is absolute for the current web based on context * * @param candidateUrl The url to make absolute * */ Util.toAbsoluteUrl = function (candidateUrl) { return new Promise(function (resolve) { if (Util.isUrlAbsolute(candidateUrl)) { // if we are already absolute, then just return the url return resolve(candidateUrl); } if (pnplibconfig_1.RuntimeConfig.baseUrl !== null) { // base url specified either with baseUrl of spfxContext config property return resolve(Util.combinePaths(pnplibconfig_1.RuntimeConfig.baseUrl, candidateUrl)); } if (typeof global._spPageContextInfo !== "undefined") { // operating in classic pages if (global._spPageContextInfo.hasOwnProperty("webAbsoluteUrl")) { return resolve(Util.combinePaths(global._spPageContextInfo.webAbsoluteUrl, candidateUrl)); } else if (global._spPageContextInfo.hasOwnProperty("webServerRelativeUrl")) { return resolve(Util.combinePaths(global._spPageContextInfo.webServerRelativeUrl, candidateUrl)); } } // does window.location exist and have _layouts in it? if (typeof global.location !== "undefined") { var index = global.location.toString().toLowerCase().indexOf("/_layouts/"); if (index > 0) { // we are likely in the workbench in /_layouts/ return resolve(Util.combinePaths(global.location.toString().substr(0, index), candidateUrl)); } } return resolve(candidateUrl); }); }; return Util; }()); exports.Util = Util; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(32))) /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = __webpack_require__(0); var collections_1 = __webpack_require__(6); var odata_1 = __webpack_require__(2); var pnplibconfig_1 = __webpack_require__(4); var exceptions_1 = __webpack_require__(3); var logging_1 = __webpack_require__(5); var pipeline_1 = __webpack_require__(45); /** * Queryable Base Class * */ var Queryable = (function () { /** * Creates a new instance of the Queryable class * * @constructor * @param baseUrl A string or Queryable that should form the base part of the url * */ function Queryable(baseUrl, path) { this._query = new collections_1.Dictionary(); this._batch = null; if (typeof baseUrl === "string") { // we need to do some extra parsing to get the parent url correct if we are // being created from just a string. var urlStr = baseUrl; if (util_1.Util.isUrlAbsolute(urlStr) || urlStr.lastIndexOf("/") < 0) { this._parentUrl = urlStr; this._url = util_1.Util.combinePaths(urlStr, path); } else if (urlStr.lastIndexOf("/") > urlStr.lastIndexOf("(")) { // .../items(19)/fields var index = urlStr.lastIndexOf("/"); this._parentUrl = urlStr.slice(0, index); path = util_1.Util.combinePaths(urlStr.slice(index), path); this._url = util_1.Util.combinePaths(this._parentUrl, path); } else { // .../items(19) var index = urlStr.lastIndexOf("("); this._parentUrl = urlStr.slice(0, index); this._url = util_1.Util.combinePaths(urlStr, path); } } else { var q = baseUrl; this._parentUrl = q._url; var target = q._query.get("@target"); if (target !== null) { this._query.add("@target", target); } this._url = util_1.Util.combinePaths(this._parentUrl, path); } } /** * Directly concatonates the supplied string to the current url, not normalizing "/" chars * * @param pathPart The string to concatonate to the url */ Queryable.prototype.concat = function (pathPart) { this._url += pathPart; return this; }; /** * Appends the given string and normalizes "/" chars * * @param pathPart The string to append */ Queryable.prototype.append = function (pathPart) { this._url = util_1.Util.combinePaths(this._url, pathPart); }; /** * Blocks a batch call from occuring, MUST be cleared by calling the returned function */ Queryable.prototype.addBatchDependency = function () { if (this.hasBatch) { return this._batch.addDependency(); } return function () { return null; }; }; Object.defineProperty(Queryable.prototype, "hasBatch", { /** * Indicates if the current query has a batch associated * */ get: function () { return this._batch !== null; }, enumerable: true, configurable: true }); Object.defineProperty(Queryable.prototype, "batch", { /** * The batch currently associated with this query or null * */ get: function () { return this.hasBatch ? this._batch : null; }, enumerable: true, configurable: true }); Object.defineProperty(Queryable.prototype, "parentUrl", { /** * Gets the parent url used when creating this instance * */ get: function () { return this._parentUrl; }, enumerable: true, configurable: true }); Object.defineProperty(Queryable.prototype, "query", { /** * Provides access to the query builder for this url * */ get: function () { return this._query; }, enumerable: true, configurable: true }); /** * Creates a new instance of the supplied factory and extends this into that new instance * * @param factory constructor for the new queryable */ Queryable.prototype.as = function (factory) { var o = new factory(this._url, null); return util_1.Util.extend(o, this, true); }; /** * Adds this query to the supplied batch * * @example * ``` * * let b = pnp.sp.createBatch(); * pnp.sp.web.inBatch(b).get().then(...); * b.execute().then(...) * ``` */ Queryable.prototype.inBatch = function (batch) { if (this._batch !== null) { throw new exceptions_1.AlreadyInBatchException(); } this._batch = batch; return this; }; /** * Enables caching for this request * * @param options Defines the options used when caching this request */ Queryable.prototype.usingCaching = function (options) { if (!pnplibconfig_1.RuntimeConfig.globalCacheDisable) { this._useCaching = true; this._cachingOptions = options; } return this; }; /** * Gets the currentl url, made absolute based on the availability of the _spPageContextInfo object * */ Queryable.prototype.toUrl = function () { return this._url; }; /** * Gets the full url with query information * */ Queryable.prototype.toUrlAndQuery = function () { var aliasedParams = new collections_1.Dictionary(); var url = this.toUrl().replace(/'!(@.*?)::(.*?)'/ig, function (match, labelName, value) { logging_1.Logger.write("Rewriting aliased parameter from match " + match + " to label: " + labelName + " value: " + value, logging_1.LogLevel.Verbose); aliasedParams.add(labelName, "'" + value + "'"); return labelName; }); // inlude our explicitly set query string params aliasedParams.merge(this._query); if (aliasedParams.count() > 0) { url += "?" + aliasedParams.getKeys().map(function (key) { return key + "=" + aliasedParams.get(key); }).join("&"); } return url; }; /** * Gets a parent for this instance as specified * * @param factory The contructor for the class to create */ Queryable.prototype.getParent = function (factory, baseUrl, path, batch) { if (baseUrl === void 0) { baseUrl = this.parentUrl; } var parent = new factory(baseUrl, path); var target = this.query.get("@target"); if (target !== null) { parent.query.add("@target", target); } if (typeof batch !== "undefined") { parent = parent.inBatch(batch); } return parent; }; /** * Clones this queryable into a new queryable instance of T * @param factory Constructor used to create the new instance * @param additionalPath Any additional path to include in the clone * @param includeBatch If true this instance's batch will be added to the cloned instance */ Queryable.prototype.clone = function (factory, additionalPath, includeBatch) { if (includeBatch === void 0) { includeBatch = false; } var clone = new factory(this, additionalPath); var target = this.query.get("@target"); if (target !== null) { clone.query.add("@target", target); } if (includeBatch && this.hasBatch) { clone = clone.inBatch(this.batch); } return clone; }; /** * Executes the currently built request * * @param parser Allows you to specify a parser to handle the result * @param getOptions The options used for this request */ Queryable.prototype.get = function (parser, getOptions) { if (parser === void 0) { parser = new odata_1.ODataDefaultParser(); } if (getOptions === void 0) { getOptions = {}; } return this.toRequestContext("GET", getOptions, parser).then(function (context) { return pipeline_1.pipe(context); }); }; Queryable.prototype.getAs = function (parser, getOptions) { if (parser === void 0) { parser = new odata_1.ODataDefaultParser(); } if (getOptions === void 0) { getOptions = {}; } return this.toRequestContext("GET", getOptions, parser).then(function (context) { return pipeline_1.pipe(context); }); }; Queryable.prototype.post = function (postOptions, parser) { if (postOptions === void 0) { postOptions = {}; } if (parser === void 0) { parser = new odata_1.ODataDefaultParser(); } return this.toRequestContext("POST", postOptions, parser).then(function (context) { return pipeline_1.pipe(context); }); }; Queryable.prototype.postAs = function (postOptions, parser) { if (postOptions === void 0) { postOptions = {}; } if (parser === void 0) { parser = new odata_1.ODataDefaultParser(); } return this.toRequestContext("POST", postOptions, parser).then(function (context) { return pipeline_1.pipe(context); }); }; Queryable.prototype.patch = function (patchOptions, parser) { if (patchOptions === void 0) { patchOptions = {}; } if (parser === void 0) { parser = new odata_1.ODataDefaultParser(); } return this.toRequestContext("PATCH", patchOptions, parser).then(function (context) { return pipeline_1.pipe(context); }); }; Queryable.prototype.delete = function (deleteOptions, parser) { if (deleteOptions === void 0) { deleteOptions = {}; } if (parser === void 0) { parser = new odata_1.ODataDefaultParser(); } return this.toRequestContext("DELETE", deleteOptions, parser).then(function (context) { return pipeline_1.pipe(context); }); }; /** * Converts the current instance to a request context * * @param verb The request verb * @param options The set of supplied request options * @param parser The supplied ODataParser instance * @param pipeline Optional request processing pipeline */ Queryable.prototype.toRequestContext = function (verb, options, parser, pipeline) { var _this = this; if (options === void 0) { options = {}; } if (pipeline === void 0) { pipeline = pipeline_1.PipelineMethods.default; } var dependencyDispose = this.hasBatch ? this.addBatchDependency() : function () { return; }; return util_1.Util.toAbsoluteUrl(this.toUrlAndQuery()).then(function (url) { // build our request context var context = { batch: _this._batch, batchDependency: dependencyDispose, cachingOptions: _this._cachingOptions, isBatched: _this.hasBatch, isCached: _this._useCaching, options: options, parser: parser, pipeline: pipeline, requestAbsoluteUrl: url, requestId: util_1.Util.getGUID(), verb: verb, }; return context; }); }; return Queryable; }()); exports.Queryable = Queryable; /** * Represents a REST collection which can be filtered, paged, and selected * */ var QueryableCollection = (function (_super) { __extends(QueryableCollection, _super); function QueryableCollection() { return _super !== null && _super.apply(this, arguments) || this; } /** * Filters the returned collection (https://msdn.microsoft.com/en-us/library/office/fp142385.aspx#bk_supported) * * @param filter The string representing the filter query */ QueryableCollection.prototype.filter = function (filter) { this._query.add("$filter", filter); return this; }; /** * Choose which fields to return * * @param selects One or more fields to return */ QueryableCollection.prototype.select = function () { var selects = []; for (var _i = 0; _i < arguments.length; _i++) { selects[_i] = arguments[_i]; } if (selects.length > 0) { this._query.add("$select", selects.join(",")); } return this; }; /** * Expands fields such as lookups to get additional data * * @param expands The Fields for which to expand the values */ QueryableCollection.prototype.expand = function () { var expands = []; for (var _i = 0; _i < arguments.length; _i++) { expands[_i] = arguments[_i]; } if (expands.length > 0) { this._query.add("$expand", expands.join(",")); } return this; }; /** * Orders based on the supplied fields ascending * * @param orderby The name of the field to sort on * @param ascending If false DESC is appended, otherwise ASC (default) */ QueryableCollection.prototype.orderBy = function (orderBy, ascending) { if (ascending === void 0) { ascending = true; } var keys = this._query.getKeys(); var query = []; var asc = ascending ? " asc" : " desc"; for (var i = 0; i < keys.length; i++) { if (keys[i] === "$orderby") { query.push(this._query.get("$orderby")); break; } } query.push("" + orderBy + asc); this._query.add("$orderby", query.join(",")); return this; }; /** * Skips the specified number of items * * @param skip The number of items to skip */ QueryableCollection.prototype.skip = function (skip) { this._query.add("$skip", skip.toString()); return this; }; /** * Limits the query to only return the specified number of items * * @param top The query row limit */ QueryableCollection.prototype.top = function (top) { this._query.add("$top", top.toString()); return this; }; return QueryableCollection; }(Queryable)); exports.QueryableCollection = QueryableCollection; /** * Represents an instance that can be selected * */ var QueryableInstance = (function (_super) { __extends(QueryableInstance, _super); function QueryableInstance() { return _super !== null && _super.apply(this, arguments) || this; } /** * Choose which fields to return * * @param selects One or more fields to return */ QueryableInstance.prototype.select = function () { var selects = []; for (var _i = 0; _i < arguments.length; _i++) { selects[_i] = arguments[_i]; } if (selects.length > 0) { this._query.add("$select", selects.join(",")); } return this; }; /** * Expands fields such as lookups to get additional data * * @param expands The Fields for which to expand the values */ QueryableInstance.prototype.expand = function () { var expands = []; for (var _i = 0; _i < arguments.length; _i++) { expands[_i] = arguments[_i]; } if (expands.length > 0) { this._query.add("$expand", expands.join(",")); } return this; }; return QueryableInstance; }(Queryable)); exports.QueryableInstance = QueryableInstance; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = __webpack_require__(0); var logging_1 = __webpack_require__(5); var httpclient_1 = __webpack_require__(15); var pnplibconfig_1 = __webpack_require__(4); var exceptions_1 = __webpack_require__(3); var exceptions_2 = __webpack_require__(3); function extractOdataId(candidate) { if (candidate.hasOwnProperty("odata.id")) { return candidate["odata.id"]; } else if (candidate.hasOwnProperty("__metadata") && candidate.__metadata.hasOwnProperty("id")) { return candidate.__metadata.id; } else { throw new exceptions_1.ODataIdException(candidate); } } exports.extractOdataId = extractOdataId; var ODataParserBase = (function () { function ODataParserBase() { } ODataParserBase.prototype.parse = function (r) { var _this = this; return new Promise(function (resolve, reject) { if (_this.handleError(r, reject)) { if ((r.headers.has("Content-Length") && parseFloat(r.headers.get("Content-Length")) === 0) || r.status === 204) { resolve({}); } else { r.json().then(function (json) { return resolve(_this.parseODataJSON(json)); }).catch(function (e) { return reject(e); }); } } }); }; ODataParserBase.prototype.handleError = function (r, reject) { if (!r.ok) { r.json().then(function (json) { // include the headers as they contain diagnostic information var data = { responseBody: json, responseHeaders: r.headers, }; reject(new exceptions_2.ProcessHttpClientResponseException(r.status, r.statusText, data)); }).catch(function (e) { // we failed to read the body - possibly it is empty. Let's report the original status that caused // the request to fail and log the error with parsing the body if anyone needs it for debugging logging_1.Logger.log({ data: e, level: logging_1.LogLevel.Warning, message: "There was an error parsing the error response body. See data for details.", }); // include the headers as they contain diagnostic information var data = { responseBody: "[[body not available]]", responseHeaders: r.headers, }; reject(new exceptions_2.ProcessHttpClientResponseException(r.status, r.statusText, data)); }); } return r.ok; }; ODataParserBase.prototype.parseODataJSON = function (json) { var result = json; if (json.hasOwnProperty("d")) { if (json.d.hasOwnProperty("results")) { result = json.d.results; } else { result = json.d; } } else if (json.hasOwnProperty("value")) { result = json.value; } return result; }; return ODataParserBase; }()); exports.ODataParserBase = ODataParserBase; var ODataDefaultParser = (function (_super) { __extends(ODataDefaultParser, _super); function ODataDefaultParser() { return _super !== null && _super.apply(this, arguments) || this; } return ODataDefaultParser; }(ODataParserBase)); exports.ODataDefaultParser = ODataDefaultParser; var ODataRawParserImpl = (function () { function ODataRawParserImpl() { } ODataRawParserImpl.prototype.parse = function (r) { return r.json(); }; return ODataRawParserImpl; }()); exports.ODataRawParserImpl = ODataRawParserImpl; var ODataValueParserImpl = (function (_super) { __extends(ODataValueParserImpl, _super); function ODataValueParserImpl() { return _super !== null && _super.apply(this, arguments) || this; } ODataValueParserImpl.prototype.parse = function (r) { return _super.prototype.parse.call(this, r).then(function (d) { return d; }); }; return ODataValueParserImpl; }(ODataParserBase)); var ODataEntityParserImpl = (function (_super) { __extends(ODataEntityParserImpl, _super); function ODataEntityParserImpl(factory) { var _this = _super.call(this) || this; _this.factory = factory; return _this; } ODataEntityParserImpl.prototype.parse = function (r) { var _this = this; return _super.prototype.parse.call(this, r).then(function (d) { var o = new _this.factory(getEntityUrl(d), null); return util_1.Util.extend(o, d); }); }; return ODataEntityParserImpl; }(ODataParserBase)); var ODataEntityArrayParserImpl = (function (_super) { __extends(ODataEntityArrayParserImpl, _super); function ODataEntityArrayParserImpl(factory) { var _this = _super.call(this) || this; _this.factory = factory; return _this; } ODataEntityArrayParserImpl.prototype.parse = function (r) { var _this = this; return _super.prototype.parse.call(this, r).then(function (d) { return d.map(function (v) { var o = new _this.factory(getEntityUrl(v), null); return util_1.Util.extend(o, v); }); }); }; return ODataEntityArrayParserImpl; }(ODataParserBase)); function getEntityUrl(entity) { if (entity.hasOwnProperty("odata.editLink")) { // we are dealign with minimal metadata (default) return util_1.Util.combinePaths("_api", entity["odata.editLink"]); } else if (entity.hasOwnProperty("__metadata")) { // we are dealing with verbose, which has an absolute uri return entity.__metadata.uri; } else { // we are likely dealing with nometadata, so don't error but we won't be able to // chain off these objects logging_1.Logger.write("No uri information found in ODataEntity parsing, chaining will fail for this object.", logging_1.LogLevel.Warning); return ""; } } exports.getEntityUrl = getEntityUrl; exports.ODataRaw = new ODataRawParserImpl(); function ODataValue() { return new ODataValueParserImpl(); } exports.ODataValue = ODataValue; function ODataEntity(factory) { return new ODataEntityParserImpl(factory); } exports.ODataEntity = ODataEntity; function ODataEntityArray(factory) { return new ODataEntityArrayParserImpl(factory); } exports.ODataEntityArray = ODataEntityArray; /** * Manages a batch of OData operations */ var ODataBatch = (function () { function ODataBatch(baseUrl, _batchId) { if (_batchId === void 0) { _batchId = util_1.Util.getGUID(); } this.baseUrl = baseUrl; this._batchId = _batchId; this._requests = []; this._dependencies = []; } Object.defineProperty(ODataBatch.prototype, "batchId", { get: function () { return this._batchId; }, enumerable: true, configurable: true }); /** * Adds a request to a batch (not designed for public use) * * @param url The full url of the request * @param method The http method GET, POST, etc * @param options Any options to include in the request * @param parser The parser that will hadle the results of the request */ ODataBatch.prototype.add = function (url, method, options, parser) { var info = { method: method.toUpperCase(), options: options, parser: parser, reject: null, resolve: null, url: url, }; var p = new Promise(function (resolve, reject) { info.resolve = resolve; info.reject = reject; }); this._requests.push(info); return p; }; /** * Adds a dependency insuring that some set of actions will occur before a batch is processed. * MUST be cleared using the returned resolve delegate to allow batches to run */ ODataBatch.prototype.addDependency = function () { var resolver; var promise = new Promise(function (resolve) { resolver = resolve; }); this._dependencies.push(promise); return resolver; }; /** * Execute the current batch and resolve the associated promises * * @returns A promise which will be resolved once all of the batch's child promises have resolved */ ODataBatch.prototype.execute = function () { var _this = this; // we need to check the dependencies twice due to how different engines handle things. // We can get a second set of promises added after the first set resolve return Promise.all(this._dependencies).then(function () { return Promise.all(_this._dependencies); }).then(function () { return _this.executeImpl(); }); }; ODataBatch.prototype.executeImpl = function () { var _this = this; logging_1.Logger.write("[" + this.batchId + "] (" + (new Date()).getTime() + ") Executing batch with " + this._requests.length + " requests.", logging_1.LogLevel.Info); // if we don't have any requests, don't bother sending anything // this could be due to caching further upstream, or just an empty batch if (this._requests.length < 1) { logging_1.Logger.write("Resolving empty batch.", logging_1.LogLevel.Info); return Promise.resolve(); } // creating the client here allows the url to be populated for nodejs client as well as potentially // any other hacks needed for other types of clients. Essentially allows the absoluteRequestUrl // below to be correct var client = new httpclient_1.HttpClient(); // due to timing we need to get the absolute url here so we can use it for all the individual requests // and for sending the entire batch return util_1.Util.toAbsoluteUrl(this.baseUrl).then(function (absoluteRequestUrl) { // build all the requests, send them, pipe results in order to parsers var batchBody = []; var currentChangeSetId = ""; for (var i = 0; i < _this._requests.length; i++) { var reqInfo = _this._requests[i]; if (reqInfo.method === "GET") { if (currentChangeSetId.length > 0) { // end an existing change set batchBody.push("--changeset_" + currentChangeSetId + "--\n\n"); currentChangeSetId = ""; } batchBody.push("--batch_" + _this._batchId + "\n"); } else { if (currentChangeSetId.length < 1) { // start new change set currentChangeSetId = util_1.Util.getGUID(); batchBody.push("--batch_" + _this._batchId + "\n"); batchBody.push("Content-Type: multipart/mixed; boundary=\"changeset_" + currentChangeSetId + "\"\n\n"); } batchBody.push("--changeset_" + currentChangeSetId + "\n"); } // common batch part prefix batchBody.push("Content-Type: application/http\n"); batchBody.push("Content-Transfer-Encoding: binary\n\n"); var headers = { "Accept": "application/json;", }; // this is the url of the individual request within the batch var url = util_1.Util.isUrlAbsolute(reqInfo.url) ? reqInfo.url : util_1.Util.combinePaths(absoluteRequestUrl, reqInfo.url); logging_1.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Adding request " + reqInfo.method + " " + url + " to batch.", logging_1.LogLevel.Verbose); if (reqInfo.method !== "GET") { var method = reqInfo.method; if (reqInfo.hasOwnProperty("options") && reqInfo.options.hasOwnProperty("headers") && typeof reqInfo.options.headers["X-HTTP-Method"] !== "undefined") { method = reqInfo.options.headers["X-HTTP-Method"]; delete reqInfo.options.headers["X-HTTP-Method"]; } batchBody.push(method + " " + url + " HTTP/1.1\n"); headers = util_1.Util.extend(headers, { "Content-Type": "application/json;odata=verbose;charset=utf-8" }); } else { batchBody.push(reqInfo.method + " " + url + " HTTP/1.1\n"); } if (typeof pnplibconfig_1.RuntimeConfig.headers !== "undefined") { headers = util_1.Util.extend(headers, pnplibconfig_1.RuntimeConfig.headers); } if (reqInfo.options && reqInfo.options.headers) { headers = util_1.Util.extend(headers, reqInfo.options.headers); } for (var name_1 in headers) { if (headers.hasOwnProperty(name_1)) { batchBody.push(name_1 + ": " + headers[name_1] + "\n"); } } batchBody.push("\n"); if (reqInfo.options.body) { batchBody.push(reqInfo.options.body + "\n\n"); } } if (currentChangeSetId.length > 0) { // Close the changeset batchBody.push("--changeset_" + currentChangeSetId + "--\n\n"); currentChangeSetId = ""; } batchBody.push("--batch_" + _this._batchId + "--\n"); var batchHeaders = { "Content-Type": "multipart/mixed; boundary=batch_" + _this._batchId, }; var batchOptions = { "body": batchBody.join(""), "headers": batchHeaders, }; logging_1.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Sending batch request.", logging_1.LogLevel.Info); return client.post(util_1.Util.combinePaths(absoluteRequestUrl, "/_api/$batch"), batchOptions) .then(function (r) { return r.text(); }) .then(_this._parseResponse) .then(function (responses) { if (responses.length !== _this._requests.length) { throw new exceptions_1.BatchParseException("Could not properly parse responses to match requests in batch."); } logging_1.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Resolving batched requests.", logging_1.LogLevel.Info); return responses.reduce(function (chain, response, index) { var request = _this._requests[index]; logging_1.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Resolving batched request " + request.method + " " + request.url + ".", logging_1.LogLevel.Verbose); return chain.then(function (_) { return request.parser.parse(response).then(request.resolve).catch(request.reject); }); }, Promise.resolve()); }); }); }; /** * Parses the response from a batch request into an array of Response instances * * @param body Text body of the response from the batch request */ ODataBatch.prototype._parseResponse = function (body) { return new Promise(function (resolve, reject) { var responses = []; var header = "--batchresponse_"; // Ex. "HTTP/1.1 500 Internal Server Error" var statusRegExp = new RegExp("^HTTP/[0-9.]+ +([0-9]+) +(.*)", "i"); var lines = body.split("\n"); var state = "batch"; var status; var statusText; for (var i = 0; i < lines.length; ++i) { var line = lines[i]; switch (state) { case "batch": if (line.substr(0, header.length) === header) { state = "batchHeaders"; } else { if (line.trim() !== "") { throw new exceptions_1.BatchParseException("Invalid response, line " + i); } } break; case "batchHeaders": if (line.trim() === "") { state = "status"; } break; case "status": var parts = statusRegExp.exec(line); if (parts.length !== 3) { throw new exceptions_1.BatchParseException("Invalid status, line " + i); } status = parseInt(parts[1], 10); statusText = parts[2]; state = "statusHeaders"; break; case "statusHeaders": if (line.trim() === "") { state = "body"; } break; case "body": responses.push((status === 204) ? new Response() : new Response(line, { status: status, statusText: statusText })); state = "batch"; break; } } if (state !== "status") { reject(new exceptions_1.BatchParseException("Unexpected end of input")); } resolve(responses); }); }; return ODataBatch; }()); exports.ODataBatch = ODataBatch; var TextFileParser = (function () { function TextFileParser() { } TextFileParser.prototype.parse = function (r) { return r.text(); }; return TextFileParser; }()); exports.TextFileParser = TextFileParser; var BlobFileParser = (function () { function BlobFileParser() { } BlobFileParser.prototype.parse = function (r) { return r.blob(); }; return BlobFileParser; }()); exports.BlobFileParser = BlobFileParser; var JSONFileParser = (function () { function JSONFileParser() { } JSONFileParser.prototype.parse = function (r) { return r.json(); }; return JSONFileParser; }()); exports.JSONFileParser = JSONFileParser; var BufferFileParser = (function () { function BufferFileParser() { } BufferFileParser.prototype.parse = function (r) { if (util_1.Util.isFunction(r.arrayBuffer)) { return r.arrayBuffer(); } return r.buffer(); }; return BufferFileParser; }()); exports.BufferFileParser = BufferFileParser; /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var logging_1 = __webpack_require__(5); function defaultLog(error) { logging_1.Logger.log({ data: {}, level: logging_1.LogLevel.Error, message: "[" + error.name + "]::" + error.message }); } /** * Represents an exception with an HttpClient request * */ var ProcessHttpClientResponseException = (function (_super) { __extends(ProcessHttpClientResponseException, _super); function ProcessHttpClientResponseException(status, statusText, data) { var _this = _super.call(this, "Error making HttpClient request in queryable: [" + status + "] " + statusText) || this; _this.status = status; _this.statusText = statusText; _this.data = data; _this.name = "ProcessHttpClientResponseException"; logging_1.Logger.log({ data: _this.data, level: logging_1.LogLevel.Error, message: _this.message }); return _this; } return ProcessHttpClientResponseException; }(Error)); exports.ProcessHttpClientResponseException = ProcessHttpClientResponseException; var NoCacheAvailableException = (function (_super) { __extends(NoCacheAvailableException, _super); function NoCacheAvailableException(msg) { if (msg === void 0) { msg = "Cannot create a caching configuration provider since cache is not available."; } var _this = _super.call(this, msg) || this; _this.name = "NoCacheAvailableException"; defaultLog(_this); return _this; } return NoCacheAvailableException; }(Error)); exports.NoCacheAvailableException = NoCacheAvailableException; var APIUrlException = (function (_super) { __extends(APIUrlException, _super); function APIUrlException(msg) { if (msg === void 0) { msg = "Unable to determine API url."; } var _this = _super.call(this, msg) || this; _this.name = "APIUrlException"; defaultLog(_this); return _this; } return APIUrlException; }(Error)); exports.APIUrlException = APIUrlException; var AuthUrlException = (function (_super) { __extends(AuthUrlException, _super); function AuthUrlException(data, msg) { if (msg === void 0) { msg = "Auth URL Endpoint could not be determined from data. Data logged."; } var _this = _super.call(this, msg) || this; _this.name = "APIUrlException"; logging_1.Logger.log({ data: data, level: logging_1.LogLevel.Error, message: _this.message }); return _this; } return AuthUrlException; }(Error)); exports.AuthUrlException = AuthUrlException; var NodeFetchClientUnsupportedException = (function (_super) { __extends(NodeFetchClientUnsupportedException, _super); function NodeFetchClientUnsupportedException(msg) { if (msg === void 0) { msg = "Using NodeFetchClient in the browser is not supported."; } var _this = _super.call(this, msg) || this; _this.name = "NodeFetchClientUnsupportedException"; defaultLog(_this); return _this; } return NodeFetchClientUnsupportedException; }(Error)); exports.NodeFetchClientUnsupportedException = NodeFetchClientUnsupportedException; var SPRequestExecutorUndefinedException = (function (_super) { __extends(SPRequestExecutorUndefinedException, _super); function SPRequestExecutorUndefinedException() { var _this = this; var msg = [ "SP.RequestExecutor is undefined. ", "Load the SP.RequestExecutor.js library (/_layouts/15/SP.RequestExecutor.js) before loading the PnP JS Core library.", ].join(" "); _this = _super.call(this, msg) || this; _this.name = "SPRequestExecutorUndefinedException"; defaultLog(_this); return _this; } return SPRequestExecutorUndefinedException; }(Error)); exports.SPRequestExecutorUndefinedException = SPRequestExecutorUndefinedException; var MaxCommentLengthException = (function (_super) { __extends(MaxCommentLengthException, _super); function MaxCommentLengthException(msg) { if (msg === void 0) { msg = "The maximum comment length is 1023 characters."; } var _this = _super.call(this, msg) || this; _this.name = "MaxCommentLengthException"; defaultLog(_this); return _this; } return MaxCommentLengthException; }(Error)); exports.MaxCommentLengthException = MaxCommentLengthException; var NotSupportedInBatchException = (function (_super) { __extends(NotSupportedInBatchException, _super); function NotSupportedInBatchException(operation) { if (operation === void 0) { operation = "This operation"; } var _this = _super.call(this, operation + " is not supported as part of a batch.") || this; _this.name = "NotSupportedInBatchException"; defaultLog(_this); return _this; } return NotSupportedInBatchException; }(Error)); exports.NotSupportedInBatchException = NotSupportedInBatchException; var ODataIdException = (function (_super) { __extends(ODataIdException, _super); function ODataIdException(data, msg) { if (msg === void 0) { msg = "Could not extract odata id in object, you may be using nometadata. Object data logged to logger."; } var _this = _super.call(this, msg) || this; _this.name = "ODataIdException"; logging_1.Logger.log({ data: data, level: logging_1.LogLevel.Error, message: _this.message }); return _this; } return ODataIdException; }(Error)); exports.ODataIdException = ODataIdException; var BatchParseException = (function (_super) { __extends(BatchParseException, _super); function BatchParseException(msg) { var _this = _super.call(this, msg) || this; _this.name = "BatchParseException"; defaultLog(_this); return _this; } return BatchParseException; }(Error)); exports.BatchParseException = BatchParseException; var AlreadyInBatchException = (function (_super) { __extends(AlreadyInBatchException, _super); function AlreadyInBatchException(msg) { if (msg === void 0) { msg = "This query is already part of a batch."; } var _this = _super.call(this, msg) || this; _this.name = "AlreadyInBatchException"; defaultLog(_this); return _this; } return AlreadyInBatchException; }(Error)); exports.AlreadyInBatchException = AlreadyInBatchException; var FunctionExpectedException = (function (_super) { __extends(FunctionExpectedException, _super); function FunctionExpectedException(msg) { if (msg === void 0) { msg = "This query is already part of a batch."; } var _this = _super.call(this, msg) || this; _this.name = "FunctionExpectedException"; defaultLog(_this); return _this; } return FunctionExpectedException; }(Error)); exports.FunctionExpectedException = FunctionExpectedException; var UrlException = (function (_super) { __extends(UrlException, _super); function UrlException(msg) { var _this = _super.call(this, msg) || this; _this.name = "UrlException"; defaultLog(_this); return _this; } return UrlException; }(Error)); exports.UrlException = UrlException; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var fetchclient_1 = __webpack_require__(21); var RuntimeConfigImpl = (function () { function RuntimeConfigImpl() { // these are our default values for the library this._headers = null; this._defaultCachingStore = "session"; this._defaultCachingTimeoutSeconds = 60; this._globalCacheDisable = false; this._fetchClientFactory = function () { return new fetchclient_1.FetchClient(); }; this._baseUrl = null; this._spfxContext = null; } RuntimeConfigImpl.prototype.set = function (config) { if (config.hasOwnProperty("headers")) { this._headers = config.headers; } if (config.hasOwnProperty("globalCacheDisable")) { this._globalCacheDisable = config.globalCacheDisable; } if (config.hasOwnProperty("defaultCachingStore")) { this._defaultCachingStore = config.defaultCachingStore; } if (config.hasOwnProperty("defaultCachingTimeoutSeconds")) { this._defaultCachingTimeoutSeconds = config.defaultCachingTimeoutSeconds; } if (config.hasOwnProperty("fetchClientFactory")) { this._fetchClientFactory = config.fetchClientFactory; } if (config.hasOwnProperty("baseUrl")) { this._baseUrl = config.baseUrl; } if (config.hasOwnProperty("spfxContext")) { this._spfxContext = config.spfxContext; } }; Object.defineProperty(RuntimeConfigImpl.prototype, "headers", { get: function () { return this._headers; }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "defaultCachingStore", { get: function () { return this._defaultCachingStore; }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "defaultCachingTimeoutSeconds", { get: function () { return this._defaultCachingTimeoutSeconds; }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "globalCacheDisable", { get: function () { return this._globalCacheDisable; }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "fetchClientFactory", { get: function () { return this._fetchClientFactory; }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "baseUrl", { get: function () { if (this._baseUrl !== null) { return this._baseUrl; } else if (this._spfxContext !== null) { return this._spfxContext.pageContext.web.absoluteUrl; } return null; }, enumerable: true, configurable: true }); return RuntimeConfigImpl; }()); exports.RuntimeConfigImpl = RuntimeConfigImpl; var _runtimeConfig = new RuntimeConfigImpl(); exports.RuntimeConfig = _runtimeConfig; function setRuntimeConfig(config) { _runtimeConfig.set(config); } exports.setRuntimeConfig = setRuntimeConfig; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * A set of logging levels * */ var LogLevel; (function (LogLevel) { LogLevel[LogLevel["Verbose"] = 0] = "Verbose"; LogLevel[LogLevel["Info"] = 1] = "Info"; LogLevel[LogLevel["Warning"] = 2] = "Warning"; LogLevel[LogLevel["Error"] = 3] = "Error"; LogLevel[LogLevel["Off"] = 99] = "Off"; })(LogLevel = exports.LogLevel || (exports.LogLevel = {})); /** * Class used to subscribe ILogListener and log messages throughout an application * */ var Logger = (function () { function Logger() { } Object.defineProperty(Logger, "activeLogLevel", { get: function () { return Logger.instance.activeLogLevel; }, set: function (value) { Logger.instance.activeLogLevel = value; }, enumerable: true, configurable: true }); Object.defineProperty(Logger, "instance", { get: function () { if (typeof Logger._instance === "undefined" || Logger._instance === null) { Logger._instance = new LoggerImpl(); } return Logger._instance; }, enumerable: true, configurable: true }); /** * Adds ILogListener instances to the set of subscribed listeners * * @param listeners One or more listeners to subscribe to this log */ Logger.subscribe = function () { var listeners = []; for (var _i = 0; _i < arguments.length; _i++) { listeners[_i] = arguments[_i]; } listeners.map(function (listener) { return Logger.instance.subscribe(listener); }); }; /** * Clears the subscribers collection, returning the collection before modifiction */ Logger.clearSubscribers = function () { return Logger.instance.clearSubscribers(); }; Object.defineProperty(Logger, "count", { /** * Gets the current subscriber count */ get: function () { return Logger.instance.count; }, enumerable: true, configurable: true }); /** * Writes the supplied string to the subscribed listeners * * @param message The message to write * @param level [Optional] if supplied will be used as the level of the entry (Default: LogLevel.Verbose) */ Logger.write = function (message, level) { if (level === void 0) { level = LogLevel.Verbose; } Logger.instance.log({ level: level, message: message }); }; /** * Writes the supplied string to the subscribed listeners * * @param json The json object to stringify and write * @param level [Optional] if supplied will be used as the level of the entry (Default: LogLevel.Verbose) */ Logger.writeJSON = function (json, level) { if (level === void 0) { level = LogLevel.Verbose; } Logger.instance.log({ level: level, message: JSON.stringify(json) }); }; /** * Logs the supplied entry to the subscribed listeners * * @param entry The message to log */ Logger.log = function (entry) { Logger.instance.log(entry); }; /** * Logs performance tracking data for the the execution duration of the supplied function using console.profile * * @param name The name of this profile boundary * @param f The function to execute and track within this performance boundary */ Logger.measure = function (name, f) { return Logger.instance.measure(name, f); }; return Logger; }()); exports.Logger = Logger; var LoggerImpl = (function () { function LoggerImpl(activeLogLevel, subscribers) { if (activeLogLevel === void 0) { activeLogLevel = LogLevel.Warning; } if (subscribers === void 0) { subscribers = []; } this.activeLogLevel = activeLogLevel; this.subscribers = subscribers; } LoggerImpl.prototype.subscribe = function (listener) { this.subscribers.push(listener); }; LoggerImpl.prototype.clearSubscribers = function () { var s = this.subscribers.slice(0); this.subscribers.length = 0; return s; }; Object.defineProperty(LoggerImpl.prototype, "count", { get: function () { return this.subscribers.length; }, enumerable: true, configurable: true }); LoggerImpl.prototype.write = function (message, level) { if (level === void 0) { level = LogLevel.Verbose; } this.log({ level: level, message: message }); }; LoggerImpl.prototype.log = function (entry) { if (typeof entry === "undefined" || entry.level < this.activeLogLevel) { return; } this.subscribers.map(function (subscriber) { return subscriber.log(entry); }); }; LoggerImpl.prototype.measure = function (name, f) { console.profile(name); try { return f(); } finally { console.profileEnd(); } }; return LoggerImpl; }()); /** * Implementation of ILogListener which logs to the browser console * */ var ConsoleListener = (function () { function ConsoleListener() { } /** * Any associated data that a given logging listener may choose to log or ignore * * @param entry The information to be logged */ ConsoleListener.prototype.log = function (entry) { var msg = this.format(entry); switch (entry.level) { case LogLevel.Verbose: case LogLevel.Info: console.log(msg); break; case LogLevel.Warning: console.warn(msg); break; case LogLevel.Error: console.error(msg); break; } }; /** * Formats the message * * @param entry The information to format into a string */ ConsoleListener.prototype.format = function (entry) { return "Message: " + entry.message + " Data: " + JSON.stringify(entry.data); }; return ConsoleListener; }()); exports.ConsoleListener = ConsoleListener; /** * Implementation of ILogListener which logs to the supplied function * */ var FunctionListener = (function () { /** * Creates a new instance of the FunctionListener class * * @constructor * @param method The method to which any logging data will be passed */ function FunctionListener(method) { this.method = method; } /** * Any associated data that a given logging listener may choose to log or ignore * * @param entry The information to be logged */ FunctionListener.prototype.log = function (entry) { this.method(entry); }; return FunctionListener; }()); exports.FunctionListener = FunctionListener; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Generic dictionary */ var Dictionary = (function () { /** * Creates a new instance of the Dictionary<T> class * * @constructor */ function Dictionary(keys, values) { if (keys === void 0) { keys = []; } if (values === void 0) { values = []; } this.keys = keys; this.values = values; } /** * Gets a value from the collection using the specified key * * @param key The key whose value we want to return, returns null if the key does not exist */ Dictionary.prototype.get = function (key) { var index = this.keys.indexOf(key); if (index < 0) { return null; } return this.values[index]; }; /** * Adds the supplied key and value to the dictionary * * @param key The key to add * @param o The value to add */ Dictionary.prototype.add = function (key, o) { var index = this.keys.indexOf(key); if (index > -1) { this.values[index] = o; } else { this.keys.push(key); this.values.push(o); } }; /** * Merges the supplied typed hash into this dictionary instance. Existing values are updated and new ones are created as appropriate. */ Dictionary.prototype.merge = function (source) { var _this = this; if ("getKeys" in source) { var sourceAsDictionary_1 = source; sourceAsDictionary_1.getKeys().map(function (key) { _this.add(key, sourceAsDictionary_1.get(key)); }); } else { var sourceAsHash = source; for (var key in sourceAsHash) { if (sourceAsHash.hasOwnProperty(key)) { this.add(key, sourceAsHash[key]); } } } }; /** * Removes a value from the dictionary * * @param key The key of the key/value pair to remove. Returns null if the key was not found. */ Dictionary.prototype.remove = function (key) { var index = this.keys.indexOf(key); if (index < 0) { return null; } var val = this.values[index]; this.keys.splice(index, 1); this.values.splice(index, 1); return val; }; /** * Returns all the keys currently in the dictionary as an array */ Dictionary.prototype.getKeys = function () { return this.keys; }; /** * Returns all the values currently in the dictionary as an array */ Dictionary.prototype.getValues = function () { return this.values; }; /** * Clears the current dictionary */ Dictionary.prototype.clear = function () { this.keys = []; this.values = []; }; /** * Gets a count of the items currently in the dictionary */ Dictionary.prototype.count = function () { return this.keys.length; }; return Dictionary; }()); exports.Dictionary = Dictionary; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var odata_1 = __webpack_require__(2); var util_1 = __webpack_require__(0); var exceptions_1 = __webpack_require__(3); var webparts_1 = __webpack_require__(50); var items_1 = __webpack_require__(10); var queryableshareable_1 = __webpack_require__(12); var odata_2 = __webpack_require__(2); /** * Describes a collection of File objects * */ var Files = (function (_super) { __extends(Files, _super); /** * Creates a new instance of the Files class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Files(baseUrl, path) { if (path === void 0) { path = "files"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a File by filename * * @param name The name of the file, including extension. */ Files.prototype.getByName = function (name) { var f = new File(this); f.concat("('" + name + "')"); return f; }; /** * Uploads a file. Not supported for batching * * @param url The folder-relative url of the file. * @param content The file contents blob. * @param shouldOverWrite Should a file with the same name in the same location be overwritten? (default: true) * @returns The new File and the raw response. */ Files.prototype.add = function (url, content, shouldOverWrite) { var _this = this; if (shouldOverWrite === void 0) { shouldOverWrite = true; } return new Files(this, "add(overwrite=" + shouldOverWrite + ",url='" + url + "')") .post({ body: content, }).then(function (response) { return { data: response, file: _this.getByName(url), }; }); }; /** * Uploads a file. Not supported for batching * * @param url The folder-relative url of the file. * @param content The Blob file content to add * @param progress A callback function which can be used to track the progress of the upload * @param shouldOverWrite Should a file with the same name in the same location be overwritten? (default: true) * @param chunkSize The size of each file slice, in bytes (default: 10485760) * @returns The new File and the raw response. */ Files.prototype.addChunked = function (url, content, progress, shouldOverWrite, chunkSize) { var _this = this; if (shouldOverWrite === void 0) { shouldOverWrite = true; } if (chunkSize === void 0) { chunkSize = 10485760; } var adder = this.clone(Files, "add(overwrite=" + shouldOverWrite + ",url='" + url + "')"); return adder.post().then(function () { return _this.getByName(url); }).then(function (file) { return file.setContentChunked(content, progress, chunkSize); }).then(function (response) { return { data: response, file: _this.getByName(url), }; }); }; /** * Adds a ghosted file to an existing list or document library. Not supported for batching. * * @param fileUrl The server-relative url where you want to save the file. * @param templateFileType The type of use to create the file. * @returns The template file that was added and the raw response. */ Files.prototype.addTemplateFile = function (fileUrl, templateFileType) { var _this = this; return this.clone(Files, "addTemplateFile(urloffile='" + fileUrl + "',templatefiletype=" + templateFileType + ")") .post().then(function (response) { return { data: response, file: _this.getByName(fileUrl), }; }); }; return Files; }(queryable_1.QueryableCollection)); exports.Files = Files; /** * Describes a single File instance * */ var File = (function (_super) { __extends(File, _super); function File() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(File.prototype, "listItemAllFields", { /** * Gets a value that specifies the list item field values for the list item corresponding to the file. * */ get: function () { return new queryable_1.QueryableCollection(this, "listItemAllFields"); }, enumerable: true, configurable: true }); Object.defineProperty(File.prototype, "versions", { /** * Gets a collection of versions * */ get: function () { return new Versions(this); }, enumerable: true, configurable: true }); /** * Approves the file submitted for content approval with the specified comment. * Only documents in lists that are enabled for content approval can be approved. * * @param comment The comment for the approval. */ File.prototype.approve = function (comment) { if (comment === void 0) { comment = ""; } return this.clone(File, "approve(comment='" + comment + "')", true).post(); }; /** * Stops the chunk upload session without saving the uploaded data. Does not support batching. * If the file doesn’t already exist in the library, the partially uploaded file will be deleted. * Use this in response to user action (as in a request to cancel an upload) or an error or exception. * Use the uploadId value that was passed to the StartUpload method that started the upload session. * This method is currently available only on Office 365. * * @param uploadId The unique identifier of the upload session. */ File.prototype.cancelUpload = function (uploadId) { return this.clone(File, "cancelUpload(uploadId=guid'" + uploadId + "')", false).post(); }; /** * Checks the file in to a document library based on the check-in type. * * @param comment A comment for the check-in. Its length must be <= 1023. * @param checkinType The check-in type for the file. */ File.prototype.checkin = function (comment, checkinType) { if (comment === void 0) { comment = ""; } if (checkinType === void 0) { checkinType = CheckinType.Major; } if (comment.length > 1023) { throw new exceptions_1.MaxCommentLengthException(); } return this.clone(File, "checkin(comment='" + comment + "',checkintype=" + checkinType + ")", true).post(); }; /** * Checks out the file from a document library. */ File.prototype.checkout = function () { return this.clone(File, "checkout", true).post(); }; /** * Copies the file to the destination url. * * @param url The absolute url or server relative url of the destination file path to copy to. * @param shouldOverWrite Should a file with the same name in the same location be overwritten? */ File.prototype.copyTo = function (url, shouldOverWrite) { if (shouldOverWrite === void 0) { shouldOverWrite = true; } return this.clone(File, "copyTo(strnewurl='" + url + "',boverwrite=" + shouldOverWrite + ")", true).post(); }; /** * Delete this file. * * @param eTag Value used in the IF-Match header, by default "*" */ File.prototype.delete = function (eTag) { if (eTag === void 0) { eTag = "*"; } return this.clone(File, null, true).post({ headers: { "IF-Match": eTag, "X-HTTP-Method": "DELETE", }, }); }; /** * Denies approval for a file that was submitted for content approval. * Only documents in lists that are enabled for content approval can be denied. * * @param comment The comment for the denial. */ File.prototype.deny = function (comment) { if (comment === void 0) { comment = ""; } if (comment.length > 1023) { throw new exceptions_1.MaxCommentLengthException(); } return this.clone(File, "deny(comment='" + comment + "')", true).post(); }; /** * Specifies the control set used to access, modify, or add Web Parts associated with this Web Part Page and view. * An exception is thrown if the file is not an ASPX page. * * @param scope The WebPartsPersonalizationScope view on the Web Parts page. */ File.prototype.getLimitedWebPartManager = function (scope) { if (scope === void 0) { scope = WebPartsPersonalizationScope.Shared; } return new webparts_1.LimitedWebPartManager(this, "getLimitedWebPartManager(scope=" + scope + ")"); }; /** * Moves the file to the specified destination url. * * @param url The absolute url or server relative url of the destination file path to move to. * @param moveOperations The bitwise MoveOperations value for how to move the file. */ File.prototype.moveTo = function (url, moveOperations) { if (moveOperations === void 0) { moveOperations = MoveOperations.Overwrite; } return this.clone(File, "moveTo(newurl='" + url + "',flags=" + moveOperations + ")", true).post(); }; /** * Submits the file for content approval with the specified comment. * * @param comment The comment for the published file. Its length must be <= 1023. */ File.prototype.publish = function (comment) { if (comment === void 0) { comment = ""; } if (comment.length > 1023) { throw new exceptions_1.MaxCommentLengthException(); } return this.clone(File, "publish(comment='" + comment + "')", true).post(); }; /** * Moves the file to the Recycle Bin and returns the identifier of the new Recycle Bin item. * * @returns The GUID of the recycled file. */ File.prototype.recycle = function () { return this.clone(File, "recycle", true).post(); }; /** * Reverts an existing checkout for the file. * */ File.prototype.undoCheckout = function () { return this.clone(File, "undoCheckout", true).post(); }; /** * Removes the file from content approval or unpublish a major version. * * @param comment The comment for the unpublish operation. Its length must be <= 1023. */ File.prototype.unpublish = function (comment) { if (comment === void 0) { comment = ""; } if (comment.length > 1023) { throw new exceptions_1.MaxCommentLengthException(); } return this.clone(File, "unpublish(comment='" + comment + "')", true).post(); }; /** * Gets the contents of the file as text. Not supported in batching. * */ File.prototype.getText = function () { return this.clone(File, "$value").get(new odata_1.TextFileParser(), { headers: { "binaryStringResponseBody": "true" } }); }; /** * Gets the contents of the file as a blob, does not work in Node.js. Not supported in batching. * */ File.prototype.getBlob = function () { return this.clone(File, "$value").get(new odata_1.BlobFileParser(), { headers: { "binaryStringResponseBody": "true" } }); }; /** * Gets the contents of a file as an ArrayBuffer, works in Node.js. Not supported in batching. */ File.prototype.getBuffer = function () { return this.clone(File, "$value").get(new odata_1.BufferFileParser(), { headers: { "binaryStringResponseBody": "true" } }); }; /** * Gets the contents of a file as an ArrayBuffer, works in Node.js. Not supported in batching. */ File.prototype.getJSON = function () { return this.clone(File, "$value").get(new odata_1.JSONFileParser(), { headers: { "binaryStringResponseBody": "true" } }); }; /** * Sets the content of a file, for large files use setContentChunked. Not supported in batching. * * @param content The file content * */ File.prototype.setContent = function (content) { var _this = this; return this.clone(File, "$value").post({ body: content, headers: { "X-HTTP-Method": "PUT", }, }).then(function (_) { return new File(_this); }); }; /** * Gets the associated list item for this folder, loading the default properties */ File.prototype.getItem = function () { var selects = []; for (var _i = 0; _i < arguments.length; _i++) { selects[_i] = arguments[_i]; } var q = this.listItemAllFields; return q.select.apply(q, selects).get().then(function (d) { return util_1.Util.extend(new items_1.Item(odata_2.getEntityUrl(d)), d); }); }; /** * Sets the contents of a file using a chunked upload approach. Not supported in batching. * * @param file The file to upload * @param progress A callback function which can be used to track the progress of the upload * @param chunkSize The size of each file slice, in bytes (default: 10485760) */ File.prototype.setContentChunked = function (file, progress, chunkSize) { if (chunkSize === void 0) { chunkSize = 10485760; } if (typeof progress === "undefined") { progress = function () { return null; }; } var self = this; var fileSize = file.size; var blockCount = parseInt((file.size / chunkSize).toString(), 10) + ((file.size % chunkSize === 0) ? 1 : 0); var uploadId = util_1.Util.getGUID(); // start the chain with the first fragment progress({ blockNumber: 1, chunkSize: chunkSize, currentPointer: 0, fileSize: fileSize, stage: "starting", totalBlocks: blockCount }); var chain = self.startUpload(uploadId, file.slice(0, chunkSize)); var _loop_1 = function (i) { chain = chain.then(function (pointer) { progress({ blockNumber: i, chunkSize: chunkSize, currentPointer: pointer, fileSize: fileSize, stage: "continue", totalBlocks: blockCount }); return self.continueUpload(uploadId, pointer, file.slice(pointer, pointer + chunkSize)); }); }; // skip the first and last blocks for (var i = 2; i < blockCount; i++) { _loop_1(i); } return chain.then(function (pointer) { progress({ blockNumber: blockCount, chunkSize: chunkSize, currentPointer: pointer, fileSize: fileSize, stage: "finishing", totalBlocks: blockCount }); return self.finishUpload(uploadId, pointer, file.slice(pointer)); }).then(function (_) { return self; }); }; /** * Starts a new chunk upload session and uploads the first fragment. * The current file content is not changed when this method completes. * The method is idempotent (and therefore does not change the result) as long as you use the same values for uploadId and stream. * The upload session ends either when you use the CancelUpload method or when you successfully * complete the upload session by passing the rest of the file contents through the ContinueUpload and FinishUpload methods. * The StartUpload and ContinueUpload methods return the size of the running total of uploaded data in bytes, * so you can pass those return values to subsequent uses of ContinueUpload and FinishUpload. * This method is currently available only on Office 365. * * @param uploadId The unique identifier of the upload session. * @param fragment The file contents. * @returns The size of the total uploaded data in bytes. */ File.prototype.startUpload = function (uploadId, fragment) { return this.clone(File, "startUpload(uploadId=guid'" + uploadId + "')").postAs({ body: fragment }).then(function (n) { return parseFloat(n); }); }; /** * Continues the chunk upload session with an additional fragment. * The current file content is not changed. * Use the uploadId value that was passed to the StartUpload method that started the upload session. * This method is currently available only on Office 365. * * @param uploadId The unique identifier of the upload session. * @param fileOffset The size of the offset into the file where the fragment starts. * @param fragment The file contents. * @returns The size of the total uploaded data in bytes. */ File.prototype.continueUpload = function (uploadId, fileOffset, fragment) { return this.clone(File, "continueUpload(uploadId=guid'" + uploadId + "',fileOffset=" + fileOffset + ")").postAs({ body: fragment }).then(function (n) { return parseFloat(n); }); }; /** * Uploads the last file fragment and commits the file. The current file content is changed when this method completes. * Use the uploadId value that was passed to the StartUpload method that started the upload session. * This method is currently available only on Office 365. * * @param uploadId The unique identifier of the upload session. * @param fileOffset The size of the offset into the file where the fragment starts. * @param fragment The file contents. * @returns The newly uploaded file. */ File.prototype.finishUpload = function (uploadId, fileOffset, fragment) { return this.clone(File, "finishUpload(uploadId=guid'" + uploadId + "',fileOffset=" + fileOffset + ")") .postAs({ body: fragment }).then(function (response) { return { data: response, file: new File(response.ServerRelativeUrl), }; }); }; return File; }(queryableshareable_1.QueryableShareableFile)); exports.File = File; /** * Describes a collection of Version objects * */ var Versions = (function (_super) { __extends(Versions, _super); /** * Creates a new instance of the File class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Versions(baseUrl, path) { if (path === void 0) { path = "versions"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a version by id * * @param versionId The id of the version to retrieve */ Versions.prototype.getById = function (versionId) { var v = new Version(this); v.concat("(" + versionId + ")"); return v; }; /** * Deletes all the file version objects in the collection. * */ Versions.prototype.deleteAll = function () { return new Versions(this, "deleteAll").post(); }; /** * Deletes the specified version of the file. * * @param versionId The ID of the file version to delete. */ Versions.prototype.deleteById = function (versionId) { return this.clone(Versions, "deleteById(vid=" + versionId + ")", true).post(); }; /** * Deletes the file version object with the specified version label. * * @param label The version label of the file version to delete, for example: 1.2 */ Versions.prototype.deleteByLabel = function (label) { return this.clone(Versions, "deleteByLabel(versionlabel='" + label + "')", true).post(); }; /** * Creates a new file version from the file specified by the version label. * * @param label The version label of the file version to restore, for example: 1.2 */ Versions.prototype.restoreByLabel = function (label) { return this.clone(Versions, "restoreByLabel(versionlabel='" + label + "')", true).post(); }; return Versions; }(queryable_1.QueryableCollection)); exports.Versions = Versions; /** * Describes a single Version instance * */ var Version = (function (_super) { __extends(Version, _super); function Version() { return _super !== null && _super.apply(this, arguments) || this; } /** * Delete a specific version of a file. * * @param eTag Value used in the IF-Match header, by default "*" */ Version.prototype.delete = function (eTag) { if (eTag === void 0) { eTag = "*"; } return this.post({ headers: { "IF-Match": eTag, "X-HTTP-Method": "DELETE", }, }); }; return Version; }(queryable_1.QueryableInstance)); exports.Version = Version; var CheckinType; (function (CheckinType) { CheckinType[CheckinType["Minor"] = 0] = "Minor"; CheckinType[CheckinType["Major"] = 1] = "Major"; CheckinType[CheckinType["Overwrite"] = 2] = "Overwrite"; })(CheckinType = exports.CheckinType || (exports.CheckinType = {})); var WebPartsPersonalizationScope; (function (WebPartsPersonalizationScope) { WebPartsPersonalizationScope[WebPartsPersonalizationScope["User"] = 0] = "User"; WebPartsPersonalizationScope[WebPartsPersonalizationScope["Shared"] = 1] = "Shared"; })(WebPartsPersonalizationScope = exports.WebPartsPersonalizationScope || (exports.WebPartsPersonalizationScope = {})); var MoveOperations; (function (MoveOperations) { MoveOperations[MoveOperations["Overwrite"] = 1] = "Overwrite"; MoveOperations[MoveOperations["AllowBrokenThickets"] = 8] = "AllowBrokenThickets"; })(MoveOperations = exports.MoveOperations || (exports.MoveOperations = {})); var TemplateFileType; (function (TemplateFileType) { TemplateFileType[TemplateFileType["StandardPage"] = 0] = "StandardPage"; TemplateFileType[TemplateFileType["WikiPage"] = 1] = "WikiPage"; TemplateFileType[TemplateFileType["FormPage"] = 2] = "FormPage"; })(TemplateFileType = exports.TemplateFileType || (exports.TemplateFileType = {})); /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var lists_1 = __webpack_require__(11); var fields_1 = __webpack_require__(24); var navigation_1 = __webpack_require__(25); var sitegroups_1 = __webpack_require__(18); var contenttypes_1 = __webpack_require__(16); var folders_1 = __webpack_require__(9); var roles_1 = __webpack_require__(17); var files_1 = __webpack_require__(7); var util_1 = __webpack_require__(0); var lists_2 = __webpack_require__(11); var siteusers_1 = __webpack_require__(30); var usercustomactions_1 = __webpack_require__(19); var odata_1 = __webpack_require__(2); var features_1 = __webpack_require__(23); var decorators_1 = __webpack_require__(51); var queryableshareable_1 = __webpack_require__(12); var relateditems_1 = __webpack_require__(46); var Webs = (function (_super) { __extends(Webs, _super); function Webs(baseUrl, webPath) { if (webPath === void 0) { webPath = "webs"; } return _super.call(this, baseUrl, webPath) || this; } /** * Adds a new web to the collection * * @param title The new web's title * @param url The new web's relative url * @param description The web web's description * @param template The web's template * @param language The language code to use for this web * @param inheritPermissions If true permissions will be inherited from the partent web * @param additionalSettings Will be passed as part of the web creation body */ Webs.prototype.add = function (title, url, description, template, language, inheritPermissions, additionalSettings) { if (description === void 0) { description = ""; } if (template === void 0) { template = "STS"; } if (language === void 0) { language = 1033; } if (inheritPermissions === void 0) { inheritPermissions = true; } if (additionalSettings === void 0) { additionalSettings = {}; } var props = util_1.Util.extend({ Description: description, Language: language, Title: title, Url: url, UseSamePermissionsAsParentSite: inheritPermissions, WebTemplate: template, }, additionalSettings); var postBody = JSON.stringify({ "parameters": util_1.Util.extend({ "__metadata": { "type": "SP.WebCreationInformation" }, }, props), }); return this.clone(Webs, "add", true).post({ body: postBody }).then(function (data) { return { data: data, web: new Web(odata_1.extractOdataId(data).replace(/_api\/web\/?/i, "")), }; }); }; return Webs; }(queryable_1.QueryableCollection)); exports.Webs = Webs; var WebInfos = (function (_super) { __extends(WebInfos, _super); function WebInfos(baseUrl, webPath) { if (webPath === void 0) { webPath = "webinfos"; } return _super.call(this, baseUrl, webPath) || this; } return WebInfos; }(queryable_1.QueryableCollection)); exports.WebInfos = WebInfos; /** * Describes a web * */ var Web = (function (_super) { __extends(Web, _super); function Web(baseUrl, path) { if (path === void 0) { path = "_api/web"; } return _super.call(this, baseUrl, path) || this; } /** * Creates a new web instance from the given url by indexing the location of the /_api/ * segment. If this is not found the method creates a new web with the entire string as * supplied. * * @param url */ Web.fromUrl = function (url, path) { if (url === null) { return new Web(""); } var index = url.indexOf("_api/"); if (index > -1) { return new Web(url.substr(0, index), path); } return new Web(url, path); }; Object.defineProperty(Web.prototype, "webs", { get: function () { return new Webs(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "webinfos", { get: function () { return new WebInfos(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "contentTypes", { /** * Get the content types available in this web * */ get: function () { return new contenttypes_1.ContentTypes(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "lists", { /** * Get the lists in this web * */ get: function () { return new lists_1.Lists(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "fields", { /** * Gets the fields in this web * */ get: function () { return new fields_1.Fields(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "features", { /** * Gets the active features for this web * */ get: function () { return new features_1.Features(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "availablefields", { /** * Gets the available fields in this web * */ get: function () { return new fields_1.Fields(this, "availablefields"); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "navigation", { /** * Get the navigation options in this web * */ get: function () { return new navigation_1.Navigation(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "siteUsers", { /** * Gets the site users * */ get: function () { return new siteusers_1.SiteUsers(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "siteGroups", { /** * Gets the site groups * */ get: function () { return new sitegroups_1.SiteGroups(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "currentUser", { /** * Gets the current user */ get: function () { return new siteusers_1.CurrentUser(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "folders", { /** * Get the folders in this web * */ get: function () { return new folders_1.Folders(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "userCustomActions", { /** * Get all custom actions on a site * */ get: function () { return new usercustomactions_1.UserCustomActions(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "roleDefinitions", { /** * Gets the collection of RoleDefinition resources. * */ get: function () { return new roles_1.RoleDefinitions(this); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "relatedItems", { /** * Provides an interface to manage related items * */ get: function () { return relateditems_1.RelatedItemManagerImpl.FromUrl(this.toUrl()); }, enumerable: true, configurable: true }); /** * Creates a new batch for requests within the context of context this web * */ Web.prototype.createBatch = function () { return new odata_1.ODataBatch(this.parentUrl); }; Object.defineProperty(Web.prototype, "rootFolder", { /** * The root folder of the web */ get: function () { return new folders_1.Folder(this, "rootFolder"); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "associatedOwnerGroup", { get: function () { return new sitegroups_1.SiteGroup(this, "associatedownergroup"); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "associatedMemberGroup", { get: function () { return new sitegroups_1.SiteGroup(this, "associatedmembergroup"); }, enumerable: true, configurable: true }); Object.defineProperty(Web.prototype, "associatedVisitorGroup", { get: function () { return new sitegroups_1.SiteGroup(this, "associatedvisitorgroup"); }, enumerable: true, configurable: true }); /** * Get a folder by server relative url * * @param folderRelativeUrl the server relative path to the folder (including /sites/ if applicable) */ Web.prototype.getFolderByServerRelativeUrl = function (folderRelativeUrl) { return new folders_1.Folder(this, "getFolderByServerRelativeUrl('" + folderRelativeUrl + "')"); }; /** * Get a file by server relative url * * @param fileRelativeUrl the server relative path to the file (including /sites/ if applicable) */ Web.prototype.getFileByServerRelativeUrl = function (fileRelativeUrl) { return new files_1.File(this, "getFileByServerRelativeUrl('" + fileRelativeUrl + "')"); }; /** * Get a list by server relative url (list's root folder) * * @param listRelativeUrl the server relative path to the list's root folder (including /sites/ if applicable) */ Web.prototype.getList = function (listRelativeUrl) { return new lists_2.List(this, "getList('" + listRelativeUrl + "')"); }; /** * Updates this web intance with the supplied properties * * @param properties A plain object hash of values to update for the web */ Web.prototype.update = function (properties) { var _this = this; var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.Web" }, }, properties)); return this.post({ body: postBody, headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { return { data: data, web: _this, }; }); }; /** * Delete this web * */ Web.prototype.delete = function () { return _super.prototype.delete.call(this); }; /** * Applies the theme specified by the contents of each of the files specified in the arguments to the site. * * @param colorPaletteUrl Server-relative URL of the color palette file. * @param fontSchemeUrl Server-relative URL of the font scheme. * @param backgroundImageUrl Server-relative URL of the background image. * @param shareGenerated true to store the generated theme files in the root site, or false to store them in this site. */ Web.prototype.applyTheme = function (colorPaletteUrl, fontSchemeUrl, backgroundImageUrl, shareGenerated) { var postBody = JSON.stringify({ backgroundImageUrl: backgroundImageUrl, colorPaletteUrl: colorPaletteUrl, fontSchemeUrl: fontSchemeUrl, shareGenerated: shareGenerated, }); return this.clone(Web, "applytheme", true).post({ body: postBody }); }; /** * Applies the specified site definition or site template to the Web site that has no template applied to it. * * @param template Name of the site definition or the name of the site template */ Web.prototype.applyWebTemplate = function (template) { var q = this.clone(Web, "applywebtemplate", true); q.concat("(@t)"); q.query.add("@t", template); return q.post(); }; /** * Returns whether the current user has the given set of permissions. * * @param perms The high and low permission range. */ Web.prototype.doesUserHavePermissions = function (perms) { var q = this.clone(Web, "doesuserhavepermissions", true); q.concat("(@p)"); q.query.add("@p", JSON.stringify(perms)); return q.get(); }; /** * Checks whether the specified login name belongs to a valid user in the site. If the user doesn't exist, adds the user to the site. * * @param loginName The login name of the user (ex: i:0#.f|membership|[email protected]) */ Web.prototype.ensureUser = function (loginName) { var postBody = JSON.stringify({ logonName: loginName, }); return this.clone(Web, "ensureuser", true).post({ body: postBody }).then(function (data) { return { data: data, user: new siteusers_1.SiteUser(odata_1.extractOdataId(data)), }; }); }; /** * Returns a collection of site templates available for the site. * * @param language The LCID of the site templates to get. * @param true to include language-neutral site templates; otherwise false */ Web.prototype.availableWebTemplates = function (language, includeCrossLanugage) { if (language === void 0) { language = 1033; } if (includeCrossLanugage === void 0) { includeCrossLanugage = true; } return new queryable_1.QueryableCollection(this, "getavailablewebtemplates(lcid=" + language + ", doincludecrosslanguage=" + includeCrossLanugage + ")"); }; /** * Returns the list gallery on the site. * * @param type The gallery type - WebTemplateCatalog = 111, WebPartCatalog = 113 ListTemplateCatalog = 114, * MasterPageCatalog = 116, SolutionCatalog = 121, ThemeCatalog = 123, DesignCatalog = 124, AppDataCatalog = 125 */ Web.prototype.getCatalog = function (type) { return this.clone(Web, "getcatalog(" + type + ")", true).select("Id").get().then(function (data) { return new lists_2.List(odata_1.extractOdataId(data)); }); }; /** * Returns the collection of changes from the change log that have occurred within the list, based on the specified query. */ Web.prototype.getChanges = function (query) { var postBody = JSON.stringify({ "query": util_1.Util.extend({ "__metadata": { "type": "SP.ChangeQuery" } }, query) }); return this.clone(Web, "getchanges", true).post({ body: postBody }); }; Object.defineProperty(Web.prototype, "customListTemplate", { /** * Gets the custom list templates for the site. * */ get: function () { return new queryable_1.QueryableCollection(this, "getcustomlisttemplates"); }, enumerable: true, configurable: true }); /** * Returns the user corresponding to the specified member identifier for the current site. * * @param id The ID of the user. */ Web.prototype.getUserById = function (id) { return new siteusers_1.SiteUser(this, "getUserById(" + id + ")"); }; /** * Returns the name of the image file for the icon that is used to represent the specified file. * * @param filename The file name. If this parameter is empty, the server returns an empty string. * @param size The size of the icon: 16x16 pixels = 0, 32x32 pixels = 1. * @param progId The ProgID of the application that was used to create the file, in the form OLEServerName.ObjectName */ Web.prototype.mapToIcon = function (filename, size, progId) { if (size === void 0) { size = 0; } if (progId === void 0) { progId = ""; } return this.clone(Web, "maptoicon(filename='" + filename + "', progid='" + progId + "', size=" + size + ")", true).get(); }; return Web; }(queryableshareable_1.QueryableShareableWeb)); __decorate([ decorators_1.deprecated("This method will be removed in future releases. Please use the methods found in queryable securable.") ], Web.prototype, "doesUserHavePermissions", null); exports.Web = Web; /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var queryableshareable_1 = __webpack_require__(12); var files_1 = __webpack_require__(7); var util_1 = __webpack_require__(0); var odata_1 = __webpack_require__(2); var items_1 = __webpack_require__(10); /** * Describes a collection of Folder objects * */ var Folders = (function (_super) { __extends(Folders, _super); /** * Creates a new instance of the Folders class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Folders(baseUrl, path) { if (path === void 0) { path = "folders"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a folder by folder name * */ Folders.prototype.getByName = function (name) { var f = new Folder(this); f.concat("('" + name + "')"); return f; }; /** * Adds a new folder to the current folder (relative) or any folder (absolute) * * @param url The relative or absolute url where the new folder will be created. Urls starting with a forward slash are absolute. * @returns The new Folder and the raw response. */ Folders.prototype.add = function (url) { var _this = this; return this.clone(Folders, "add('" + url + "')", true).post().then(function (response) { return { data: response, folder: _this.getByName(url), }; }); }; return Folders; }(queryable_1.QueryableCollection)); exports.Folders = Folders; /** * Describes a single Folder instance * */ var Folder = (function (_super) { __extends(Folder, _super); function Folder() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(Folder.prototype, "contentTypeOrder", { /** * Specifies the sequence in which content types are displayed. * */ get: function () { return new queryable_1.QueryableCollection(this, "contentTypeOrder"); }, enumerable: true, configurable: true }); Object.defineProperty(Folder.prototype, "files", { /** * Gets this folder's files * */ get: function () { return new files_1.Files(this); }, enumerable: true, configurable: true }); Object.defineProperty(Folder.prototype, "folders", { /** * Gets this folder's sub folders * */ get: function () { return new Folders(this); }, enumerable: true, configurable: true }); Object.defineProperty(Folder.prototype, "listItemAllFields", { /** * Gets this folder's list item field values * */ get: function () { return new queryable_1.QueryableCollection(this, "listItemAllFields"); }, enumerable: true, configurable: true }); Object.defineProperty(Folder.prototype, "parentFolder", { /** * Gets the parent folder, if available * */ get: function () { return new Folder(this, "parentFolder"); }, enumerable: true, configurable: true }); Object.defineProperty(Folder.prototype, "properties", { /** * Gets this folder's properties * */ get: function () { return new queryable_1.QueryableInstance(this, "properties"); }, enumerable: true, configurable: true }); Object.defineProperty(Folder.prototype, "serverRelativeUrl", { /** * Gets this folder's server relative url * */ get: function () { return new queryable_1.Queryable(this, "serverRelativeUrl"); }, enumerable: true, configurable: true }); Object.defineProperty(Folder.prototype, "uniqueContentTypeOrder", { /** * Gets a value that specifies the content type order. * */ get: function () { return new queryable_1.QueryableCollection(this, "uniqueContentTypeOrder"); }, enumerable: true, configurable: true }); Folder.prototype.update = function (properties) { var _this = this; var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.Folder" }, }, properties)); return this.post({ body: postBody, headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { return { data: data, folder: _this, }; }); }; /** * Delete this folder * * @param eTag Value used in the IF-Match header, by default "*" */ Folder.prototype.delete = function (eTag) { if (eTag === void 0) { eTag = "*"; } return this.clone(Folder, null, true).post({ headers: { "IF-Match": eTag, "X-HTTP-Method": "DELETE", }, }); }; /** * Moves the folder to the Recycle Bin and returns the identifier of the new Recycle Bin item. */ Folder.prototype.recycle = function () { return this.clone(Folder, "recycle", true).post(); }; /** * Gets the associated list item for this folder, loading the default properties */ Folder.prototype.getItem = function () { var selects = []; for (var _i = 0; _i < arguments.length; _i++) { selects[_i] = arguments[_i]; } var q = this.listItemAllFields; return q.select.apply(q, selects).get().then(function (d) { return util_1.Util.extend(new items_1.Item(odata_1.getEntityUrl(d)), d); }); }; return Folder; }(queryableshareable_1.QueryableShareableFolder)); exports.Folder = Folder; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var queryableshareable_1 = __webpack_require__(12); var folders_1 = __webpack_require__(9); var files_1 = __webpack_require__(7); var contenttypes_1 = __webpack_require__(16); var util_1 = __webpack_require__(0); var odata_1 = __webpack_require__(2); var attachmentfiles_1 = __webpack_require__(42); var lists_1 = __webpack_require__(11); /** * Describes a collection of Item objects * */ var Items = (function (_super) { __extends(Items, _super); /** * Creates a new instance of the Items class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Items(baseUrl, path) { if (path === void 0) { path = "items"; } return _super.call(this, baseUrl, path) || this; } /** * Gets an Item by id * * @param id The integer id of the item to retrieve */ Items.prototype.getById = function (id) { var i = new Item(this); i.concat("(" + id + ")"); return i; }; /** * Skips the specified number of items (https://msdn.microsoft.com/en-us/library/office/fp142385.aspx#sectionSection6) * * @param skip The starting id where the page should start, use with top to specify pages */ Items.prototype.skip = function (skip) { this._query.add("$skiptoken", encodeURIComponent("Paged=TRUE&p_ID=" + skip)); return this; }; /** * Gets a collection designed to aid in paging through data * */ Items.prototype.getPaged = function () { return this.getAs(new PagedItemCollectionParser()); }; // /** * Adds a new item to the collection * * @param properties The new items's properties */ Items.prototype.add = function (properties, listItemEntityTypeFullName) { var _this = this; if (properties === void 0) { properties = {}; } if (listItemEntityTypeFullName === void 0) { listItemEntityTypeFullName = null; } var removeDependency = this.addBatchDependency(); return this.ensureListItemEntityTypeName(listItemEntityTypeFullName).then(function (listItemEntityType) { var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": listItemEntityType }, }, properties)); var promise = _this.clone(Items, null, true).postAs({ body: postBody }).then(function (data) { return { data: data, item: _this.getById(data.Id), }; }); removeDependency(); return promise; }); }; /** * Ensures we have the proper list item entity type name, either from the value provided or from the list * * @param candidatelistItemEntityTypeFullName The potential type name */ Items.prototype.ensureListItemEntityTypeName = function (candidatelistItemEntityTypeFullName) { return candidatelistItemEntityTypeFullName ? Promise.resolve(candidatelistItemEntityTypeFullName) : this.getParent(lists_1.List).getListItemEntityTypeFullName(); }; return Items; }(queryable_1.QueryableCollection)); exports.Items = Items; /** * Descrines a single Item instance * */ var Item = (function (_super) { __extends(Item, _super); function Item() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(Item.prototype, "attachmentFiles", { /** * Gets the set of attachments for this item * */ get: function () { return new attachmentfiles_1.AttachmentFiles(this); }, enumerable: true, configurable: true }); Object.defineProperty(Item.prototype, "contentType", { /** * Gets the content type for this item * */ get: function () { return new contenttypes_1.ContentType(this, "ContentType"); }, enumerable: true, configurable: true }); Object.defineProperty(Item.prototype, "effectiveBasePermissions", { /** * Gets the effective base permissions for the item * */ get: function () { return new queryable_1.Queryable(this, "EffectiveBasePermissions"); }, enumerable: true, configurable: true }); Object.defineProperty(Item.prototype, "effectiveBasePermissionsForUI", { /** * Gets the effective base permissions for the item in a UI context * */ get: function () { return new queryable_1.Queryable(this, "EffectiveBasePermissionsForUI"); }, enumerable: true, configurable: true }); Object.defineProperty(Item.prototype, "fieldValuesAsHTML", { /** * Gets the field values for this list item in their HTML representation * */ get: function () { return new queryable_1.QueryableInstance(this, "FieldValuesAsHTML"); }, enumerable: true, configurable: true }); Object.defineProperty(Item.prototype, "fieldValuesAsText", { /** * Gets the field values for this list item in their text representation * */ get: function () { return new queryable_1.QueryableInstance(this, "FieldValuesAsText"); }, enumerable: true, configurable: true }); Object.defineProperty(Item.prototype, "fieldValuesForEdit", { /** * Gets the field values for this list item for use in editing controls * */ get: function () { return new queryable_1.QueryableInstance(this, "FieldValuesForEdit"); }, enumerable: true, configurable: true }); Object.defineProperty(Item.prototype, "folder", { /** * Gets the folder associated with this list item (if this item represents a folder) * */ get: function () { return new folders_1.Folder(this, "folder"); }, enumerable: true, configurable: true }); Object.defineProperty(Item.prototype, "file", { /** * Gets the folder associated with this list item (if this item represents a folder) * */ get: function () { return new files_1.File(this, "file"); }, enumerable: true, configurable: true }); /** * Updates this list intance with the supplied properties * * @param properties A plain object hash of values to update for the list * @param eTag Value used in the IF-Match header, by default "*" */ Item.prototype.update = function (properties, eTag) { var _this = this; if (eTag === void 0) { eTag = "*"; } return new Promise(function (resolve, reject) { var removeDependency = _this.addBatchDependency(); var parentList = _this.getParent(queryable_1.QueryableInstance, _this.parentUrl.substr(0, _this.parentUrl.lastIndexOf("/"))); parentList.select("ListItemEntityTypeFullName").getAs().then(function (d) { var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": d.ListItemEntityTypeFullName }, }, properties)); removeDependency(); return _this.post({ body: postBody, headers: { "IF-Match": eTag, "X-HTTP-Method": "MERGE", }, }, new ItemUpdatedParser()).then(function (data) { resolve({ data: data, item: _this, }); }); }).catch(function (e) { return reject(e); }); }); }; /** * Delete this item * * @param eTag Value used in the IF-Match header, by default "*" */ Item.prototype.delete = function (eTag) { if (eTag === void 0) { eTag = "*"; } return this.post({ headers: { "IF-Match": eTag, "X-HTTP-Method": "DELETE", }, }); }; /** * Moves the list item to the Recycle Bin and returns the identifier of the new Recycle Bin item. */ Item.prototype.recycle = function () { return this.clone(Item, "recycle", true).post(); }; /** * Gets a string representation of the full URL to the WOPI frame. * If there is no associated WOPI application, or no associated action, an empty string is returned. * * @param action Display mode: 0: view, 1: edit, 2: mobileView, 3: interactivePreview */ Item.prototype.getWopiFrameUrl = function (action) { if (action === void 0) { action = 0; } var i = this.clone(Item, "getWOPIFrameUrl(@action)", true); i._query.add("@action", action); return i.post().then(function (data) { return data.GetWOPIFrameUrl; }); }; /** * Validates and sets the values of the specified collection of fields for the list item. * * @param formValues The fields to change and their new values. * @param newDocumentUpdate true if the list item is a document being updated after upload; otherwise false. */ Item.prototype.validateUpdateListItem = function (formValues, newDocumentUpdate) { if (newDocumentUpdate === void 0) { newDocumentUpdate = false; } return this.clone(Item, "validateupdatelistitem", true).post({ body: JSON.stringify({ "formValues": formValues, bNewDocumentUpdate: newDocumentUpdate }), }); }; return Item; }(queryableshareable_1.QueryableShareableItem)); exports.Item = Item; /** * Provides paging functionality for list items */ var PagedItemCollection = (function () { function PagedItemCollection(nextUrl, results) { this.nextUrl = nextUrl; this.results = results; } Object.defineProperty(PagedItemCollection.prototype, "hasNext", { /** * If true there are more results available in the set, otherwise there are not */ get: function () { return typeof this.nextUrl === "string" && this.nextUrl.length > 0; }, enumerable: true, configurable: true }); /** * Gets the next set of results, or resolves to null if no results are available */ PagedItemCollection.prototype.getNext = function () { if (this.hasNext) { var items = new Items(this.nextUrl, null); return items.getPaged(); } return new Promise(function (r) { return r(null); }); }; return PagedItemCollection; }()); exports.PagedItemCollection = PagedItemCollection; var PagedItemCollectionParser = (function (_super) { __extends(PagedItemCollectionParser, _super); function PagedItemCollectionParser() { return _super !== null && _super.apply(this, arguments) || this; } PagedItemCollectionParser.prototype.parse = function (r) { var _this = this; return new Promise(function (resolve, reject) { if (_this.handleError(r, reject)) { r.json().then(function (json) { var nextUrl = json.hasOwnProperty("d") && json.d.hasOwnProperty("__next") ? json.d.__next : json["odata.nextLink"]; resolve(new PagedItemCollection(nextUrl, _this.parseODataJSON(json))); }); } }); }; return PagedItemCollectionParser; }(odata_1.ODataParserBase)); var ItemUpdatedParser = (function (_super) { __extends(ItemUpdatedParser, _super); function ItemUpdatedParser() { return _super !== null && _super.apply(this, arguments) || this; } ItemUpdatedParser.prototype.parse = function (r) { var _this = this; return new Promise(function (resolve, reject) { if (_this.handleError(r, reject)) { resolve({ "odata.etag": r.headers.get("etag"), }); } }); }; return ItemUpdatedParser; }(odata_1.ODataParserBase)); /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var items_1 = __webpack_require__(10); var views_1 = __webpack_require__(49); var contenttypes_1 = __webpack_require__(16); var fields_1 = __webpack_require__(24); var forms_1 = __webpack_require__(43); var subscriptions_1 = __webpack_require__(47); var queryable_1 = __webpack_require__(1); var queryablesecurable_1 = __webpack_require__(26); var util_1 = __webpack_require__(0); var usercustomactions_1 = __webpack_require__(19); var odata_1 = __webpack_require__(2); var exceptions_1 = __webpack_require__(3); var folders_1 = __webpack_require__(9); /** * Describes a collection of List objects * */ var Lists = (function (_super) { __extends(Lists, _super); /** * Creates a new instance of the Lists class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Lists(baseUrl, path) { if (path === void 0) { path = "lists"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a list from the collection by title * * @param title The title of the list */ Lists.prototype.getByTitle = function (title) { return new List(this, "getByTitle('" + title + "')"); }; /** * Gets a list from the collection by guid id * * @param id The Id of the list (GUID) */ Lists.prototype.getById = function (id) { var list = new List(this); list.concat("('" + id + "')"); return list; }; /** * Adds a new list to the collection * * @param title The new list's title * @param description The new list's description * @param template The list template value * @param enableContentTypes If true content types will be allowed and enabled, otherwise they will be disallowed and not enabled * @param additionalSettings Will be passed as part of the list creation body */ Lists.prototype.add = function (title, description, template, enableContentTypes, additionalSettings) { var _this = this; if (description === void 0) { description = ""; } if (template === void 0) { template = 100; } if (enableContentTypes === void 0) { enableContentTypes = false; } if (additionalSettings === void 0) { additionalSettings = {}; } var addSettings = util_1.Util.extend({ "AllowContentTypes": enableContentTypes, "BaseTemplate": template, "ContentTypesEnabled": enableContentTypes, "Description": description, "Title": title, "__metadata": { "type": "SP.List" }, }, additionalSettings); return this.post({ body: JSON.stringify(addSettings) }).then(function (data) { return { data: data, list: _this.getByTitle(addSettings.Title) }; }); }; /** * Ensures that the specified list exists in the collection (note: this method not supported for batching) * * @param title The new list's title * @param description The new list's description * @param template The list template value * @param enableContentTypes If true content types will be allowed and enabled, otherwise they will be disallowed and not enabled * @param additionalSettings Will be passed as part of the list creation body or used to update an existing list */ Lists.prototype.ensure = function (title, description, template, enableContentTypes, additionalSettings) { var _this = this; if (description === void 0) { description = ""; } if (template === void 0) { template = 100; } if (enableContentTypes === void 0) { enableContentTypes = false; } if (additionalSettings === void 0) { additionalSettings = {}; } if (this.hasBatch) { throw new exceptions_1.NotSupportedInBatchException("The ensure list method"); } return new Promise(function (resolve, reject) { var addOrUpdateSettings = util_1.Util.extend(additionalSettings, { Title: title, Description: description, ContentTypesEnabled: enableContentTypes }, true); var list = _this.getByTitle(addOrUpdateSettings.Title); list.get().then(function (_) { list.update(addOrUpdateSettings).then(function (d) { resolve({ created: false, data: d, list: _this.getByTitle(addOrUpdateSettings.Title) }); }).catch(function (e) { return reject(e); }); }).catch(function (_) { _this.add(title, description, template, enableContentTypes, addOrUpdateSettings).then(function (r) { resolve({ created: true, data: r.data, list: _this.getByTitle(addOrUpdateSettings.Title) }); }).catch(function (e) { return reject(e); }); }); }); }; /** * Gets a list that is the default asset location for images or other files, which the users upload to their wiki pages. */ Lists.prototype.ensureSiteAssetsLibrary = function () { return this.clone(Lists, "ensuresiteassetslibrary", true).post().then(function (json) { return new List(odata_1.extractOdataId(json)); }); }; /** * Gets a list that is the default location for wiki pages. */ Lists.prototype.ensureSitePagesLibrary = function () { return this.clone(Lists, "ensuresitepageslibrary", true).post().then(function (json) { return new List(odata_1.extractOdataId(json)); }); }; return Lists; }(queryable_1.QueryableCollection)); exports.Lists = Lists; /** * Describes a single List instance * */ var List = (function (_super) { __extends(List, _super); function List() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(List.prototype, "contentTypes", { /** * Gets the content types in this list * */ get: function () { return new contenttypes_1.ContentTypes(this); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "items", { /** * Gets the items in this list * */ get: function () { return new items_1.Items(this); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "views", { /** * Gets the views in this list * */ get: function () { return new views_1.Views(this); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "fields", { /** * Gets the fields in this list * */ get: function () { return new fields_1.Fields(this); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "forms", { /** * Gets the forms in this list * */ get: function () { return new forms_1.Forms(this); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "defaultView", { /** * Gets the default view of this list * */ get: function () { return new queryable_1.QueryableInstance(this, "DefaultView"); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "userCustomActions", { /** * Get all custom actions on a site collection * */ get: function () { return new usercustomactions_1.UserCustomActions(this); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "effectiveBasePermissions", { /** * Gets the effective base permissions of this list * */ get: function () { return new queryable_1.Queryable(this, "EffectiveBasePermissions"); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "eventReceivers", { /** * Gets the event receivers attached to this list * */ get: function () { return new queryable_1.QueryableCollection(this, "EventReceivers"); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "relatedFields", { /** * Gets the related fields of this list * */ get: function () { return new queryable_1.Queryable(this, "getRelatedFields"); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "informationRightsManagementSettings", { /** * Gets the IRM settings for this list * */ get: function () { return new queryable_1.Queryable(this, "InformationRightsManagementSettings"); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "subscriptions", { /** * Gets the webhook subscriptions of this list * */ get: function () { return new subscriptions_1.Subscriptions(this); }, enumerable: true, configurable: true }); Object.defineProperty(List.prototype, "rootFolder", { /** * The root folder of the list */ get: function () { return new folders_1.Folder(this, "rootFolder"); }, enumerable: true, configurable: true }); /** * Gets a view by view guid id * */ List.prototype.getView = function (viewId) { return new views_1.View(this, "getView('" + viewId + "')"); }; /** * Updates this list intance with the supplied properties * * @param properties A plain object hash of values to update for the list * @param eTag Value used in the IF-Match header, by default "*" */ /* tslint:disable no-string-literal */ List.prototype.update = function (properties, eTag) { var _this = this; if (eTag === void 0) { eTag = "*"; } var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.List" }, }, properties)); return this.post({ body: postBody, headers: { "IF-Match": eTag, "X-HTTP-Method": "MERGE", }, }).then(function (data) { var retList = _this; if (properties.hasOwnProperty("Title")) { retList = _this.getParent(List, _this.parentUrl, "getByTitle('" + properties["Title"] + "')"); } return { data: data, list: retList, }; }); }; /* tslint:enable */ /** * Delete this list * * @param eTag Value used in the IF-Match header, by default "*" */ List.prototype.delete = function (eTag) { if (eTag === void 0) { eTag = "*"; } return this.post({ headers: { "IF-Match": eTag, "X-HTTP-Method": "DELETE", }, }); }; /** * Returns the collection of changes from the change log that have occurred within the list, based on the specified query. */ List.prototype.getChanges = function (query) { return this.clone(List, "getchanges", true).post({ body: JSON.stringify({ "query": util_1.Util.extend({ "__metadata": { "type": "SP.ChangeQuery" } }, query) }), }); }; /** * Returns a collection of items from the list based on the specified query. * * @param CamlQuery The Query schema of Collaborative Application Markup * Language (CAML) is used in various ways within the context of Microsoft SharePoint Foundation * to define queries against list data. * see: * * https://msdn.microsoft.com/en-us/library/office/ms467521.aspx * * @param expands A URI with a $expand System Query Option indicates that Entries associated with * the Entry or Collection of Entries identified by the Resource Path * section of the URI must be represented inline (i.e. eagerly loaded). * see: * * https://msdn.microsoft.com/en-us/library/office/fp142385.aspx * * http://www.odata.org/documentation/odata-version-2-0/uri-conventions/#ExpandSystemQueryOption */ List.prototype.getItemsByCAMLQuery = function (query) { var expands = []; for (var _i = 1; _i < arguments.length; _i++) { expands[_i - 1] = arguments[_i]; } var q = this.clone(List, "getitems", true); return q.expand.apply(q, expands).post({ body: JSON.stringify({ "query": util_1.Util.extend({ "__metadata": { "type": "SP.CamlQuery" } }, query) }), }); }; /** * See: https://msdn.microsoft.com/en-us/library/office/dn292554.aspx */ List.prototype.getListItemChangesSinceToken = function (query) { return this.clone(List, "getlistitemchangessincetoken", true).post({ body: JSON.stringify({ "query": util_1.Util.extend({ "__metadata": { "type": "SP.ChangeLogItemQuery" } }, query) }), }, { parse: function (r) { return r.text(); } }); }; /** * Moves the list to the Recycle Bin and returns the identifier of the new Recycle Bin item. */ List.prototype.recycle = function () { return this.clone(List, "recycle", true).post().then(function (data) { if (data.hasOwnProperty("Recycle")) { return data.Recycle; } else { return data; } }); }; /** * Renders list data based on the view xml provided */ List.prototype.renderListData = function (viewXml) { var q = this.clone(List, "renderlistdata(@viewXml)"); q.query.add("@viewXml", "'" + viewXml + "'"); return q.post().then(function (data) { // data will be a string, so we parse it again data = JSON.parse(data); if (data.hasOwnProperty("RenderListData")) { return data.RenderListData; } else { return data; } }); }; /** * Gets the field values and field schema attributes for a list item. */ List.prototype.renderListFormData = function (itemId, formId, mode) { return this.clone(List, "renderlistformdata(itemid=" + itemId + ", formid='" + formId + "', mode='" + mode + "')", true).post().then(function (data) { // data will be a string, so we parse it again data = JSON.parse(data); if (data.hasOwnProperty("ListData")) { return data.ListData; } else { return data; } }); }; /** * Reserves a list item ID for idempotent list item creation. */ List.prototype.reserveListItemId = function () { return this.clone(List, "reservelistitemid", true).post().then(function (data) { if (data.hasOwnProperty("ReserveListItemId")) { return data.ReserveListItemId; } else { return data; } }); }; /** * Returns the ListItemEntityTypeFullName for this list, used when adding/updating list items. Does not support batching. * */ List.prototype.getListItemEntityTypeFullName = function () { return this.clone(List, null).select("ListItemEntityTypeFullName").getAs().then(function (o) { return o.ListItemEntityTypeFullName; }); }; return List; }(queryablesecurable_1.QueryableSecurable)); exports.List = List; /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = __webpack_require__(0); var webs_1 = __webpack_require__(8); var odata_1 = __webpack_require__(2); var queryable_1 = __webpack_require__(1); var queryablesecurable_1 = __webpack_require__(26); var types_1 = __webpack_require__(13); /** * Internal helper class used to augment classes to include sharing functionality */ var QueryableShareable = (function (_super) { __extends(QueryableShareable, _super); function QueryableShareable() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets a sharing link for the supplied * * @param kind The kind of link to share * @param expiration The optional expiration for this link */ QueryableShareable.prototype.getShareLink = function (kind, expiration) { if (expiration === void 0) { expiration = null; } // date needs to be an ISO string or null var expString = expiration !== null ? expiration.toISOString() : null; // clone using the factory and send the request return this.clone(QueryableShareable, "shareLink", true).postAs({ body: JSON.stringify({ request: { createLink: true, emailData: null, settings: { expiration: expString, linkKind: kind, }, }, }), }); }; /** * Shares this instance with the supplied users * * @param loginNames Resolved login names to share * @param role The role * @param requireSignin True to require the user is authenticated, otherwise false * @param propagateAcl True to apply this share to all children * @param emailData If supplied an email will be sent with the indicated properties */ QueryableShareable.prototype.shareWith = function (loginNames, role, requireSignin, propagateAcl, emailData) { var _this = this; if (requireSignin === void 0) { requireSignin = true; } if (propagateAcl === void 0) { propagateAcl = false; } // handle the multiple input types if (!Array.isArray(loginNames)) { loginNames = [loginNames]; } var userStr = JSON.stringify(loginNames.map(function (login) { return { Key: login }; })); var roleFilter = role === types_1.SharingRole.Edit ? types_1.RoleType.Contributor : types_1.RoleType.Reader; // start by looking up the role definition id we need to set the roleValue return webs_1.Web.fromUrl(this.toUrl()).roleDefinitions.select("Id").filter("RoleTypeKind eq " + roleFilter).get().then(function (def) { if (!Array.isArray(def) || def.length < 1) { throw new Error("Could not locate a role defintion with RoleTypeKind " + roleFilter); } var postBody = { includeAnonymousLinkInEmail: requireSignin, peoplePickerInput: userStr, propagateAcl: propagateAcl, roleValue: "role:" + def[0].Id, useSimplifiedRoles: true, }; if (typeof emailData !== "undefined") { postBody = util_1.Util.extend(postBody, { emailBody: emailData.body, emailSubject: typeof emailData.subject !== "undefined" ? emailData.subject : "", sendEmail: true, }); } return _this.clone(QueryableShareable, "shareObject", true).postAs({ body: JSON.stringify(postBody), }); }); }; /** * Shares an object based on the supplied options * * @param options The set of options to send to the ShareObject method * @param bypass If true any processing is skipped and the options are sent directly to the ShareObject method */ QueryableShareable.prototype.shareObject = function (options, bypass) { var _this = this; if (bypass === void 0) { bypass = false; } if (bypass) { // if the bypass flag is set send the supplied parameters directly to the service return this.sendShareObjectRequest(options); } // extend our options with some defaults options = util_1.Util.extend(options, { group: null, includeAnonymousLinkInEmail: false, propagateAcl: false, useSimplifiedRoles: true, }, true); return this.getRoleValue(options.role, options.group).then(function (roleValue) { // handle the multiple input types if (!Array.isArray(options.loginNames)) { options.loginNames = [options.loginNames]; } var userStr = JSON.stringify(options.loginNames.map(function (login) { return { Key: login }; })); var postBody = { peoplePickerInput: userStr, roleValue: roleValue, url: options.url, }; if (typeof options.emailData !== "undefined" && options.emailData !== null) { postBody = util_1.Util.extend(postBody, { emailBody: options.emailData.body, emailSubject: typeof options.emailData.subject !== "undefined" ? options.emailData.subject : "Shared with you.", sendEmail: true, }); } return _this.sendShareObjectRequest(postBody); }); }; /** * Calls the web's UnshareObject method * * @param url The url of the object to unshare */ QueryableShareable.prototype.unshareObjectWeb = function (url) { return this.clone(QueryableShareable, "unshareObject", true).postAs({ body: JSON.stringify({ url: url, }), }); }; /** * Checks Permissions on the list of Users and returns back role the users have on the Item. * * @param recipients The array of Entities for which Permissions need to be checked. */ QueryableShareable.prototype.checkPermissions = function (recipients) { return this.clone(QueryableShareable, "checkPermissions", true).postAs({ body: JSON.stringify({ recipients: recipients, }), }); }; /** * Get Sharing Information. * * @param request The SharingInformationRequest Object. */ QueryableShareable.prototype.getSharingInformation = function (request) { if (request === void 0) { request = null; } return this.clone(QueryableShareable, "getSharingInformation", true).postAs({ body: JSON.stringify({ request: request, }), }); }; /** * Gets the sharing settings of an item. * * @param useSimplifiedRoles Determines whether to use simplified roles. */ QueryableShareable.prototype.getObjectSharingSettings = function (useSimplifiedRoles) { if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; } return this.clone(QueryableShareable, "getObjectSharingSettings", true).postAs({ body: JSON.stringify({ useSimplifiedRoles: useSimplifiedRoles, }), }); }; /** * Unshares this object */ QueryableShareable.prototype.unshareObject = function () { return this.clone(QueryableShareable, "unshareObject", true).postAs(); }; /** * Deletes a link by type * * @param kind Deletes a sharing link by the kind of link */ QueryableShareable.prototype.deleteLinkByKind = function (kind) { return this.clone(QueryableShareable, "deleteLinkByKind", true).post({ body: JSON.stringify({ linkKind: kind }), }); }; /** * Removes the specified link to the item. * * @param kind The kind of link to be deleted. * @param shareId */ QueryableShareable.prototype.unshareLink = function (kind, shareId) { if (shareId === void 0) { shareId = "00000000-0000-0000-0000-000000000000"; } return this.clone(QueryableShareable, "unshareLink", true).post({ body: JSON.stringify({ linkKind: kind, shareId: shareId }), }); }; /** * Calculates the roleValue string used in the sharing query * * @param role The Sharing Role * @param group The Group type */ QueryableShareable.prototype.getRoleValue = function (role, group) { // we will give group precedence, because we had to make a choice if (typeof group !== "undefined" && group !== null) { switch (group) { case types_1.RoleType.Contributor: return webs_1.Web.fromUrl(this.toUrl()).associatedMemberGroup.select("Id").getAs().then(function (g) { return "group: " + g.Id; }); case types_1.RoleType.Reader: case types_1.RoleType.Guest: return webs_1.Web.fromUrl(this.toUrl()).associatedVisitorGroup.select("Id").getAs().then(function (g) { return "group: " + g.Id; }); default: throw new Error("Could not determine role value for supplied value. Contributor, Reader, and Guest are supported"); } } else { var roleFilter = role === types_1.SharingRole.Edit ? types_1.RoleType.Contributor : types_1.RoleType.Reader; return webs_1.Web.fromUrl(this.toUrl()).roleDefinitions.select("Id").top(1).filter("RoleTypeKind eq " + roleFilter).getAs().then(function (def) { if (def.length < 1) { throw new Error("Could not locate associated role definition for supplied role. Edit and View are supported"); } return "role: " + def[0].Id; }); } }; QueryableShareable.prototype.getShareObjectWeb = function (candidate) { return Promise.resolve(webs_1.Web.fromUrl(candidate, "/_api/SP.Web.ShareObject")); }; QueryableShareable.prototype.sendShareObjectRequest = function (options) { return this.getShareObjectWeb(this.toUrl()).then(function (web) { return web.expand("UsersWithAccessRequests", "GroupsSharedWith").as(QueryableShareable).post({ body: JSON.stringify(options), }); }); }; return QueryableShareable; }(queryable_1.Queryable)); exports.QueryableShareable = QueryableShareable; var QueryableShareableWeb = (function (_super) { __extends(QueryableShareableWeb, _super); function QueryableShareableWeb() { return _super !== null && _super.apply(this, arguments) || this; } /** * Shares this web with the supplied users * @param loginNames The resolved login names to share * @param role The role to share this web * @param emailData Optional email data */ QueryableShareableWeb.prototype.shareWith = function (loginNames, role, emailData) { var _this = this; if (role === void 0) { role = types_1.SharingRole.View; } var dependency = this.addBatchDependency(); return webs_1.Web.fromUrl(this.toUrl(), "/_api/web/url").get().then(function (url) { dependency(); return _this.shareObject(util_1.Util.combinePaths(url, "/_layouts/15/aclinv.aspx?forSharing=1&mbypass=1"), loginNames, role, emailData); }); }; /** * Provides direct access to the static web.ShareObject method * * @param url The url to share * @param loginNames Resolved loginnames string[] of a single login name string * @param roleValue Role value * @param emailData Optional email data * @param groupId Optional group id * @param propagateAcl * @param includeAnonymousLinkInEmail * @param useSimplifiedRoles */ QueryableShareableWeb.prototype.shareObject = function (url, loginNames, role, emailData, group, propagateAcl, includeAnonymousLinkInEmail, useSimplifiedRoles) { if (propagateAcl === void 0) { propagateAcl = false; } if (includeAnonymousLinkInEmail === void 0) { includeAnonymousLinkInEmail = false; } if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; } return this.clone(QueryableShareable, null, true).shareObject({ emailData: emailData, group: group, includeAnonymousLinkInEmail: includeAnonymousLinkInEmail, loginNames: loginNames, propagateAcl: propagateAcl, role: role, url: url, useSimplifiedRoles: useSimplifiedRoles, }); }; /** * Supplies a method to pass any set of arguments to ShareObject * * @param options The set of options to send to ShareObject */ QueryableShareableWeb.prototype.shareObjectRaw = function (options) { return this.clone(QueryableShareable, null, true).shareObject(options, true); }; /** * Unshares the object * * @param url The url of the object to stop sharing */ QueryableShareableWeb.prototype.unshareObject = function (url) { return this.clone(QueryableShareable, null, true).unshareObjectWeb(url); }; return QueryableShareableWeb; }(queryablesecurable_1.QueryableSecurable)); exports.QueryableShareableWeb = QueryableShareableWeb; var QueryableShareableItem = (function (_super) { __extends(QueryableShareableItem, _super); function QueryableShareableItem() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets a link suitable for sharing for this item * * @param kind The type of link to share * @param expiration The optional expiration date */ QueryableShareableItem.prototype.getShareLink = function (kind, expiration) { if (kind === void 0) { kind = types_1.SharingLinkKind.OrganizationView; } if (expiration === void 0) { expiration = null; } return this.clone(QueryableShareable, null, true).getShareLink(kind, expiration); }; /** * Shares this item with one or more users * * @param loginNames string or string[] of resolved login names to which this item will be shared * @param role The role (View | Edit) applied to the share * @param emailData Optional, if inlucded an email will be sent. Note subject currently has no effect. */ QueryableShareableItem.prototype.shareWith = function (loginNames, role, requireSignin, emailData) { if (role === void 0) { role = types_1.SharingRole.View; } if (requireSignin === void 0) { requireSignin = true; } return this.clone(QueryableShareable, null, true).shareWith(loginNames, role, requireSignin, false, emailData); }; /** * Checks Permissions on the list of Users and returns back role the users have on the Item. * * @param recipients The array of Entities for which Permissions need to be checked. */ QueryableShareableItem.prototype.checkSharingPermissions = function (recipients) { return this.clone(QueryableShareable, null, true).checkPermissions(recipients); }; /** * Get Sharing Information. * * @param request The SharingInformationRequest Object. */ QueryableShareableItem.prototype.getSharingInformation = function (request) { if (request === void 0) { request = null; } return this.clone(QueryableShareable, null, true).getSharingInformation(request); }; /** * Gets the sharing settings of an item. * * @param useSimplifiedRoles Determines whether to use simplified roles. */ QueryableShareableItem.prototype.getObjectSharingSettings = function (useSimplifiedRoles) { if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; } return this.clone(QueryableShareable, null, true).getObjectSharingSettings(useSimplifiedRoles); }; /** * Unshare this item */ QueryableShareableItem.prototype.unshare = function () { return this.clone(QueryableShareable, null, true).unshareObject(); }; /** * Deletes a sharing link by kind * * @param kind Deletes a sharing link by the kind of link */ QueryableShareableItem.prototype.deleteSharingLinkByKind = function (kind) { return this.clone(QueryableShareable, null, true).deleteLinkByKind(kind); }; /** * Removes the specified link to the item. * * @param kind The kind of link to be deleted. * @param shareId */ QueryableShareableItem.prototype.unshareLink = function (kind, shareId) { return this.clone(QueryableShareable, null, true).unshareLink(kind, shareId); }; return QueryableShareableItem; }(queryablesecurable_1.QueryableSecurable)); exports.QueryableShareableItem = QueryableShareableItem; var FileFolderShared = (function (_super) { __extends(FileFolderShared, _super); function FileFolderShared() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets a link suitable for sharing * * @param kind The kind of link to get * @param expiration Optional, an expiration for this link */ FileFolderShared.prototype.getShareLink = function (kind, expiration) { if (kind === void 0) { kind = types_1.SharingLinkKind.OrganizationView; } if (expiration === void 0) { expiration = null; } var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.getShareLink(kind, expiration); }); }; /** * Checks Permissions on the list of Users and returns back role the users have on the Item. * * @param recipients The array of Entities for which Permissions need to be checked. */ FileFolderShared.prototype.checkSharingPermissions = function (recipients) { var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.checkPermissions(recipients); }); }; /** * Get Sharing Information. * * @param request The SharingInformationRequest Object. */ FileFolderShared.prototype.getSharingInformation = function (request) { if (request === void 0) { request = null; } var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.getSharingInformation(request); }); }; /** * Gets the sharing settings of an item. * * @param useSimplifiedRoles Determines whether to use simplified roles. */ FileFolderShared.prototype.getObjectSharingSettings = function (useSimplifiedRoles) { if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; } var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.getObjectSharingSettings(useSimplifiedRoles); }); }; /** * Unshare this item */ FileFolderShared.prototype.unshare = function () { var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.unshareObject(); }); }; /** * Deletes a sharing link by the kind of link * * @param kind The kind of link to be deleted. */ FileFolderShared.prototype.deleteSharingLinkByKind = function (kind) { var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.deleteLinkByKind(kind); }); }; /** * Removes the specified link to the item. * * @param kind The kind of link to be deleted. * @param shareId The share id to delete */ FileFolderShared.prototype.unshareLink = function (kind, shareId) { var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.unshareLink(kind, shareId); }); }; /** * For files and folders we need to use the associated item end point */ FileFolderShared.prototype.getShareable = function () { var _this = this; // sharing only works on the item end point, not the file one - so we create a folder instance with the item url internally return this.clone(QueryableShareableFile, "listItemAllFields", false).select("odata.editlink").get().then(function (d) { var shareable = new QueryableShareable(odata_1.getEntityUrl(d)); // we need to handle batching if (_this.hasBatch) { shareable = shareable.inBatch(_this.batch); } return shareable; }); }; return FileFolderShared; }(queryable_1.QueryableInstance)); exports.FileFolderShared = FileFolderShared; var QueryableShareableFile = (function (_super) { __extends(QueryableShareableFile, _super); function QueryableShareableFile() { return _super !== null && _super.apply(this, arguments) || this; } /** * Shares this item with one or more users * * @param loginNames string or string[] of resolved login names to which this item will be shared * @param role The role (View | Edit) applied to the share * @param shareEverything Share everything in this folder, even items with unique permissions. * @param requireSignin If true the user must signin to view link, otherwise anyone with the link can access the resource * @param emailData Optional, if inlucded an email will be sent. Note subject currently has no effect. */ QueryableShareableFile.prototype.shareWith = function (loginNames, role, requireSignin, emailData) { if (role === void 0) { role = types_1.SharingRole.View; } if (requireSignin === void 0) { requireSignin = true; } var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.shareWith(loginNames, role, requireSignin, false, emailData); }); }; return QueryableShareableFile; }(FileFolderShared)); exports.QueryableShareableFile = QueryableShareableFile; var QueryableShareableFolder = (function (_super) { __extends(QueryableShareableFolder, _super); function QueryableShareableFolder() { return _super !== null && _super.apply(this, arguments) || this; } /** * Shares this item with one or more users * * @param loginNames string or string[] of resolved login names to which this item will be shared * @param role The role (View | Edit) applied to the share * @param shareEverything Share everything in this folder, even items with unique permissions. * @param requireSignin If true the user must signin to view link, otherwise anyone with the link can access the resource * @param emailData Optional, if inlucded an email will be sent. Note subject currently has no effect. */ QueryableShareableFolder.prototype.shareWith = function (loginNames, role, requireSignin, shareEverything, emailData) { if (role === void 0) { role = types_1.SharingRole.View; } if (requireSignin === void 0) { requireSignin = true; } if (shareEverything === void 0) { shareEverything = false; } var dependency = this.addBatchDependency(); return this.getShareable().then(function (shareable) { dependency(); return shareable.shareWith(loginNames, role, requireSignin, shareEverything, emailData); }); }; return QueryableShareableFolder; }(FileFolderShared)); exports.QueryableShareableFolder = QueryableShareableFolder; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // reference: https://msdn.microsoft.com/en-us/library/office/dn600183.aspx Object.defineProperty(exports, "__esModule", { value: true }); /** * Determines the display mode of the given control or view */ var ControlMode; (function (ControlMode) { ControlMode[ControlMode["Display"] = 1] = "Display"; ControlMode[ControlMode["Edit"] = 2] = "Edit"; ControlMode[ControlMode["New"] = 3] = "New"; })(ControlMode = exports.ControlMode || (exports.ControlMode = {})); /** * Specifies the type of the field. */ var FieldTypes; (function (FieldTypes) { FieldTypes[FieldTypes["Invalid"] = 0] = "Invalid"; FieldTypes[FieldTypes["Integer"] = 1] = "Integer"; FieldTypes[FieldTypes["Text"] = 2] = "Text"; FieldTypes[FieldTypes["Note"] = 3] = "Note"; FieldTypes[FieldTypes["DateTime"] = 4] = "DateTime"; FieldTypes[FieldTypes["Counter"] = 5] = "Counter"; FieldTypes[FieldTypes["Choice"] = 6] = "Choice"; FieldTypes[FieldTypes["Lookup"] = 7] = "Lookup"; FieldTypes[FieldTypes["Boolean"] = 8] = "Boolean"; FieldTypes[FieldTypes["Number"] = 9] = "Number"; FieldTypes[FieldTypes["Currency"] = 10] = "Currency"; FieldTypes[FieldTypes["URL"] = 11] = "URL"; FieldTypes[FieldTypes["Computed"] = 12] = "Computed"; FieldTypes[FieldTypes["Threading"] = 13] = "Threading"; FieldTypes[FieldTypes["Guid"] = 14] = "Guid"; FieldTypes[FieldTypes["MultiChoice"] = 15] = "MultiChoice"; FieldTypes[FieldTypes["GridChoice"] = 16] = "GridChoice"; FieldTypes[FieldTypes["Calculated"] = 17] = "Calculated"; FieldTypes[FieldTypes["File"] = 18] = "File"; FieldTypes[FieldTypes["Attachments"] = 19] = "Attachments"; FieldTypes[FieldTypes["User"] = 20] = "User"; FieldTypes[FieldTypes["Recurrence"] = 21] = "Recurrence"; FieldTypes[FieldTypes["CrossProjectLink"] = 22] = "CrossProjectLink"; FieldTypes[FieldTypes["ModStat"] = 23] = "ModStat"; FieldTypes[FieldTypes["Error"] = 24] = "Error"; FieldTypes[FieldTypes["ContentTypeId"] = 25] = "ContentTypeId"; FieldTypes[FieldTypes["PageSeparator"] = 26] = "PageSeparator"; FieldTypes[FieldTypes["ThreadIndex"] = 27] = "ThreadIndex"; FieldTypes[FieldTypes["WorkflowStatus"] = 28] = "WorkflowStatus"; FieldTypes[FieldTypes["AllDayEvent"] = 29] = "AllDayEvent"; FieldTypes[FieldTypes["WorkflowEventType"] = 30] = "WorkflowEventType"; })(FieldTypes = exports.FieldTypes || (exports.FieldTypes = {})); var DateTimeFieldFormatType; (function (DateTimeFieldFormatType) { DateTimeFieldFormatType[DateTimeFieldFormatType["DateOnly"] = 0] = "DateOnly"; DateTimeFieldFormatType[DateTimeFieldFormatType["DateTime"] = 1] = "DateTime"; })(DateTimeFieldFormatType = exports.DateTimeFieldFormatType || (exports.DateTimeFieldFormatType = {})); /** * Specifies the control settings while adding a field. */ var AddFieldOptions; (function (AddFieldOptions) { /** * Specify that a new field added to the list must also be added to the default content type in the site collection */ AddFieldOptions[AddFieldOptions["DefaultValue"] = 0] = "DefaultValue"; /** * Specify that a new field added to the list must also be added to the default content type in the site collection. */ AddFieldOptions[AddFieldOptions["AddToDefaultContentType"] = 1] = "AddToDefaultContentType"; /** * Specify that a new field must not be added to any other content type */ AddFieldOptions[AddFieldOptions["AddToNoContentType"] = 2] = "AddToNoContentType"; /** * Specify that a new field that is added to the specified list must also be added to all content types in the site collection */ AddFieldOptions[AddFieldOptions["AddToAllContentTypes"] = 4] = "AddToAllContentTypes"; /** * Specify adding an internal field name hint for the purpose of avoiding possible database locking or field renaming operations */ AddFieldOptions[AddFieldOptions["AddFieldInternalNameHint"] = 8] = "AddFieldInternalNameHint"; /** * Specify that a new field that is added to the specified list must also be added to the default list view */ AddFieldOptions[AddFieldOptions["AddFieldToDefaultView"] = 16] = "AddFieldToDefaultView"; /** * Specify to confirm that no other field has the same display name */ AddFieldOptions[AddFieldOptions["AddFieldCheckDisplayName"] = 32] = "AddFieldCheckDisplayName"; })(AddFieldOptions = exports.AddFieldOptions || (exports.AddFieldOptions = {})); var CalendarType; (function (CalendarType) { CalendarType[CalendarType["Gregorian"] = 1] = "Gregorian"; CalendarType[CalendarType["Japan"] = 3] = "Japan"; CalendarType[CalendarType["Taiwan"] = 4] = "Taiwan"; CalendarType[CalendarType["Korea"] = 5] = "Korea"; CalendarType[CalendarType["Hijri"] = 6] = "Hijri"; CalendarType[CalendarType["Thai"] = 7] = "Thai"; CalendarType[CalendarType["Hebrew"] = 8] = "Hebrew"; CalendarType[CalendarType["GregorianMEFrench"] = 9] = "GregorianMEFrench"; CalendarType[CalendarType["GregorianArabic"] = 10] = "GregorianArabic"; CalendarType[CalendarType["GregorianXLITEnglish"] = 11] = "GregorianXLITEnglish"; CalendarType[CalendarType["GregorianXLITFrench"] = 12] = "GregorianXLITFrench"; CalendarType[CalendarType["KoreaJapanLunar"] = 14] = "KoreaJapanLunar"; CalendarType[CalendarType["ChineseLunar"] = 15] = "ChineseLunar"; CalendarType[CalendarType["SakaEra"] = 16] = "SakaEra"; CalendarType[CalendarType["UmAlQura"] = 23] = "UmAlQura"; })(CalendarType = exports.CalendarType || (exports.CalendarType = {})); var UrlFieldFormatType; (function (UrlFieldFormatType) { UrlFieldFormatType[UrlFieldFormatType["Hyperlink"] = 0] = "Hyperlink"; UrlFieldFormatType[UrlFieldFormatType["Image"] = 1] = "Image"; })(UrlFieldFormatType = exports.UrlFieldFormatType || (exports.UrlFieldFormatType = {})); var PermissionKind; (function (PermissionKind) { /** * Has no permissions on the Site. Not available through the user interface. */ PermissionKind[PermissionKind["EmptyMask"] = 0] = "EmptyMask"; /** * View items in lists, documents in document libraries, and Web discussion comments. */ PermissionKind[PermissionKind["ViewListItems"] = 1] = "ViewListItems"; /** * Add items to lists, documents to document libraries, and Web discussion comments. */ PermissionKind[PermissionKind["AddListItems"] = 2] = "AddListItems"; /** * Edit items in lists, edit documents in document libraries, edit Web discussion comments * in documents, and customize Web Part Pages in document libraries. */ PermissionKind[PermissionKind["EditListItems"] = 3] = "EditListItems"; /** * Delete items from a list, documents from a document library, and Web discussion * comments in documents. */ PermissionKind[PermissionKind["DeleteListItems"] = 4] = "DeleteListItems"; /** * Approve a minor version of a list item or document. */ PermissionKind[PermissionKind["ApproveItems"] = 5] = "ApproveItems"; /** * View the source of documents with server-side file handlers. */ PermissionKind[PermissionKind["OpenItems"] = 6] = "OpenItems"; /** * View past versions of a list item or document. */ PermissionKind[PermissionKind["ViewVersions"] = 7] = "ViewVersions"; /** * Delete past versions of a list item or document. */ PermissionKind[PermissionKind["DeleteVersions"] = 8] = "DeleteVersions"; /** * Discard or check in a document which is checked out to another user. */ PermissionKind[PermissionKind["CancelCheckout"] = 9] = "CancelCheckout"; /** * Create, change, and delete personal views of lists. */ PermissionKind[PermissionKind["ManagePersonalViews"] = 10] = "ManagePersonalViews"; /** * Create and delete lists, add or remove columns in a list, and add or remove public views of a list. */ PermissionKind[PermissionKind["ManageLists"] = 12] = "ManageLists"; /** * View forms, views, and application pages, and enumerate lists. */ PermissionKind[PermissionKind["ViewFormPages"] = 13] = "ViewFormPages"; /** * Make content of a list or document library retrieveable for anonymous users through SharePoint search. * The list permissions in the site do not change. */ PermissionKind[PermissionKind["AnonymousSearchAccessList"] = 14] = "AnonymousSearchAccessList"; /** * Allow users to open a Site, list, or folder to access items inside that container. */ PermissionKind[PermissionKind["Open"] = 17] = "Open"; /** * View pages in a Site. */ PermissionKind[PermissionKind["ViewPages"] = 18] = "ViewPages"; /** * Add, change, or delete HTML pages or Web Part Pages, and edit the Site using * a Windows SharePoint Services compatible editor. */ PermissionKind[PermissionKind["AddAndCustomizePages"] = 19] = "AddAndCustomizePages"; /** * Apply a theme or borders to the entire Site. */ PermissionKind[PermissionKind["ApplyThemeAndBorder"] = 20] = "ApplyThemeAndBorder"; /** * Apply a style sheet (.css file) to the Site. */ PermissionKind[PermissionKind["ApplyStyleSheets"] = 21] = "ApplyStyleSheets"; /** * View reports on Site usage. */ PermissionKind[PermissionKind["ViewUsageData"] = 22] = "ViewUsageData"; /** * Create a Site using Self-Service Site Creation. */ PermissionKind[PermissionKind["CreateSSCSite"] = 23] = "CreateSSCSite"; /** * Create subsites such as team sites, Meeting Workspace sites, and Document Workspace sites. */ PermissionKind[PermissionKind["ManageSubwebs"] = 24] = "ManageSubwebs"; /** * Create a group of users that can be used anywhere within the site collection. */ PermissionKind[PermissionKind["CreateGroups"] = 25] = "CreateGroups"; /** * Create and change permission levels on the Site and assign permissions to users * and groups. */ PermissionKind[PermissionKind["ManagePermissions"] = 26] = "ManagePermissions"; /** * Enumerate files and folders in a Site using Microsoft Office SharePoint Designer * and WebDAV interfaces. */ PermissionKind[PermissionKind["BrowseDirectories"] = 27] = "BrowseDirectories"; /** * View information about users of the Site. */ PermissionKind[PermissionKind["BrowseUserInfo"] = 28] = "BrowseUserInfo"; /** * Add or remove personal Web Parts on a Web Part Page. */ PermissionKind[PermissionKind["AddDelPrivateWebParts"] = 29] = "AddDelPrivateWebParts"; /** * Update Web Parts to display personalized information. */ PermissionKind[PermissionKind["UpdatePersonalWebParts"] = 30] = "UpdatePersonalWebParts"; /** * Grant the ability to perform all administration tasks for the Site as well as * manage content, activate, deactivate, or edit properties of Site scoped Features * through the object model or through the user interface (UI). When granted on the * root Site of a Site Collection, activate, deactivate, or edit properties of * site collection scoped Features through the object model. To browse to the Site * Collection Features page and activate or deactivate Site Collection scoped Features * through the UI, you must be a Site Collection administrator. */ PermissionKind[PermissionKind["ManageWeb"] = 31] = "ManageWeb"; /** * Content of lists and document libraries in the Web site will be retrieveable for anonymous users through * SharePoint search if the list or document library has AnonymousSearchAccessList set. */ PermissionKind[PermissionKind["AnonymousSearchAccessWebLists"] = 32] = "AnonymousSearchAccessWebLists"; /** * Use features that launch client applications. Otherwise, users must work on documents * locally and upload changes. */ PermissionKind[PermissionKind["UseClientIntegration"] = 37] = "UseClientIntegration"; /** * Use SOAP, WebDAV, or Microsoft Office SharePoint Designer interfaces to access the Site. */ PermissionKind[PermissionKind["UseRemoteAPIs"] = 38] = "UseRemoteAPIs"; /** * Manage alerts for all users of the Site. */ PermissionKind[PermissionKind["ManageAlerts"] = 39] = "ManageAlerts"; /** * Create e-mail alerts. */ PermissionKind[PermissionKind["CreateAlerts"] = 40] = "CreateAlerts"; /** * Allows a user to change his or her user information, such as adding a picture. */ PermissionKind[PermissionKind["EditMyUserInfo"] = 41] = "EditMyUserInfo"; /** * Enumerate permissions on Site, list, folder, document, or list item. */ PermissionKind[PermissionKind["EnumeratePermissions"] = 63] = "EnumeratePermissions"; /** * Has all permissions on the Site. Not available through the user interface. */ PermissionKind[PermissionKind["FullMask"] = 65] = "FullMask"; })(PermissionKind = exports.PermissionKind || (exports.PermissionKind = {})); var PrincipalType; (function (PrincipalType) { PrincipalType[PrincipalType["None"] = 0] = "None"; PrincipalType[PrincipalType["User"] = 1] = "User"; PrincipalType[PrincipalType["DistributionList"] = 2] = "DistributionList"; PrincipalType[PrincipalType["SecurityGroup"] = 4] = "SecurityGroup"; PrincipalType[PrincipalType["SharePointGroup"] = 8] = "SharePointGroup"; PrincipalType[PrincipalType["All"] = 15] = "All"; })(PrincipalType = exports.PrincipalType || (exports.PrincipalType = {})); var PrincipalSource; (function (PrincipalSource) { PrincipalSource[PrincipalSource["None"] = 0] = "None"; PrincipalSource[PrincipalSource["UserInfoList"] = 1] = "UserInfoList"; PrincipalSource[PrincipalSource["Windows"] = 2] = "Windows"; PrincipalSource[PrincipalSource["MembershipProvider"] = 4] = "MembershipProvider"; PrincipalSource[PrincipalSource["RoleProvider"] = 8] = "RoleProvider"; PrincipalSource[PrincipalSource["All"] = 15] = "All"; })(PrincipalSource = exports.PrincipalSource || (exports.PrincipalSource = {})); var RoleType; (function (RoleType) { RoleType[RoleType["None"] = 0] = "None"; RoleType[RoleType["Guest"] = 1] = "Guest"; RoleType[RoleType["Reader"] = 2] = "Reader"; RoleType[RoleType["Contributor"] = 3] = "Contributor"; RoleType[RoleType["WebDesigner"] = 4] = "WebDesigner"; RoleType[RoleType["Administrator"] = 5] = "Administrator"; })(RoleType = exports.RoleType || (exports.RoleType = {})); var PageType; (function (PageType) { PageType[PageType["Invalid"] = -1] = "Invalid"; PageType[PageType["DefaultView"] = 0] = "DefaultView"; PageType[PageType["NormalView"] = 1] = "NormalView"; PageType[PageType["DialogView"] = 2] = "DialogView"; PageType[PageType["View"] = 3] = "View"; PageType[PageType["DisplayForm"] = 4] = "DisplayForm"; PageType[PageType["DisplayFormDialog"] = 5] = "DisplayFormDialog"; PageType[PageType["EditForm"] = 6] = "EditForm"; PageType[PageType["EditFormDialog"] = 7] = "EditFormDialog"; PageType[PageType["NewForm"] = 8] = "NewForm"; PageType[PageType["NewFormDialog"] = 9] = "NewFormDialog"; PageType[PageType["SolutionForm"] = 10] = "SolutionForm"; PageType[PageType["PAGE_MAXITEMS"] = 11] = "PAGE_MAXITEMS"; })(PageType = exports.PageType || (exports.PageType = {})); var SharingLinkKind; (function (SharingLinkKind) { /** * Uninitialized link */ SharingLinkKind[SharingLinkKind["Uninitialized"] = 0] = "Uninitialized"; /** * Direct link to the object being shared */ SharingLinkKind[SharingLinkKind["Direct"] = 1] = "Direct"; /** * Organization-shareable link to the object being shared with view permissions */ SharingLinkKind[SharingLinkKind["OrganizationView"] = 2] = "OrganizationView"; /** * Organization-shareable link to the object being shared with edit permissions */ SharingLinkKind[SharingLinkKind["OrganizationEdit"] = 3] = "OrganizationEdit"; /** * View only anonymous link */ SharingLinkKind[SharingLinkKind["AnonymousView"] = 4] = "AnonymousView"; /** * Read/Write anonymous link */ SharingLinkKind[SharingLinkKind["AnonymousEdit"] = 5] = "AnonymousEdit"; /** * Flexible sharing Link where properties can change without affecting link URL */ SharingLinkKind[SharingLinkKind["Flexible"] = 6] = "Flexible"; })(SharingLinkKind = exports.SharingLinkKind || (exports.SharingLinkKind = {})); ; /** * Indicates the role of the sharing link */ var SharingRole; (function (SharingRole) { SharingRole[SharingRole["None"] = 0] = "None"; SharingRole[SharingRole["View"] = 1] = "View"; SharingRole[SharingRole["Edit"] = 2] = "Edit"; SharingRole[SharingRole["Owner"] = 3] = "Owner"; })(SharingRole = exports.SharingRole || (exports.SharingRole = {})); var SharingOperationStatusCode; (function (SharingOperationStatusCode) { /** * The share operation completed without errors. */ SharingOperationStatusCode[SharingOperationStatusCode["CompletedSuccessfully"] = 0] = "CompletedSuccessfully"; /** * The share operation completed and generated requests for access. */ SharingOperationStatusCode[SharingOperationStatusCode["AccessRequestsQueued"] = 1] = "AccessRequestsQueued"; /** * The share operation failed as there were no resolved users. */ SharingOperationStatusCode[SharingOperationStatusCode["NoResolvedUsers"] = -1] = "NoResolvedUsers"; /** * The share operation failed due to insufficient permissions. */ SharingOperationStatusCode[SharingOperationStatusCode["AccessDenied"] = -2] = "AccessDenied"; /** * The share operation failed when attempting a cross site share, which is not supported. */ SharingOperationStatusCode[SharingOperationStatusCode["CrossSiteRequestNotSupported"] = -3] = "CrossSiteRequestNotSupported"; /** * The sharing operation failed due to an unknown error. */ SharingOperationStatusCode[SharingOperationStatusCode["UnknowError"] = -4] = "UnknowError"; /** * The text you typed is too long. Please shorten it. */ SharingOperationStatusCode[SharingOperationStatusCode["EmailBodyTooLong"] = -5] = "EmailBodyTooLong"; /** * The maximum number of unique scopes in the list has been exceeded. */ SharingOperationStatusCode[SharingOperationStatusCode["ListUniqueScopesExceeded"] = -6] = "ListUniqueScopesExceeded"; /** * The share operation failed because a sharing capability is disabled in the site. */ SharingOperationStatusCode[SharingOperationStatusCode["CapabilityDisabled"] = -7] = "CapabilityDisabled"; /** * The specified object for the share operation is not supported. */ SharingOperationStatusCode[SharingOperationStatusCode["ObjectNotSupported"] = -8] = "ObjectNotSupported"; /** * A SharePoint group cannot contain another SharePoint group. */ SharingOperationStatusCode[SharingOperationStatusCode["NestedGroupsNotSupported"] = -9] = "NestedGroupsNotSupported"; })(SharingOperationStatusCode = exports.SharingOperationStatusCode || (exports.SharingOperationStatusCode = {})); var SPSharedObjectType; (function (SPSharedObjectType) { SPSharedObjectType[SPSharedObjectType["Unknown"] = 0] = "Unknown"; SPSharedObjectType[SPSharedObjectType["File"] = 1] = "File"; SPSharedObjectType[SPSharedObjectType["Folder"] = 2] = "Folder"; SPSharedObjectType[SPSharedObjectType["Item"] = 3] = "Item"; SPSharedObjectType[SPSharedObjectType["List"] = 4] = "List"; SPSharedObjectType[SPSharedObjectType["Web"] = 5] = "Web"; SPSharedObjectType[SPSharedObjectType["Max"] = 6] = "Max"; })(SPSharedObjectType = exports.SPSharedObjectType || (exports.SPSharedObjectType = {})); var SharingDomainRestrictionMode; (function (SharingDomainRestrictionMode) { SharingDomainRestrictionMode[SharingDomainRestrictionMode["None"] = 0] = "None"; SharingDomainRestrictionMode[SharingDomainRestrictionMode["AllowList"] = 1] = "AllowList"; SharingDomainRestrictionMode[SharingDomainRestrictionMode["BlockList"] = 2] = "BlockList"; })(SharingDomainRestrictionMode = exports.SharingDomainRestrictionMode || (exports.SharingDomainRestrictionMode = {})); ; /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = __webpack_require__(0); var collections_1 = __webpack_require__(6); var pnplibconfig_1 = __webpack_require__(4); /** * A wrapper class to provide a consistent interface to browser based storage * */ var PnPClientStorageWrapper = (function () { /** * Creates a new instance of the PnPClientStorageWrapper class * * @constructor */ function PnPClientStorageWrapper(store, defaultTimeoutMinutes) { this.store = store; this.defaultTimeoutMinutes = defaultTimeoutMinutes; this.defaultTimeoutMinutes = (defaultTimeoutMinutes === void 0) ? -1 : defaultTimeoutMinutes; this.enabled = this.test(); } /** * Get a value from storage, or null if that value does not exist * * @param key The key whose value we want to retrieve */ PnPClientStorageWrapper.prototype.get = function (key) { if (!this.enabled) { return null; } var o = this.store.getItem(key); if (o == null) { return null; } var persistable = JSON.parse(o); if (new Date(persistable.expiration) <= new Date()) { this.delete(key); return null; } else { return persistable.value; } }; /** * Adds a value to the underlying storage * * @param key The key to use when storing the provided value * @param o The value to store * @param expire Optional, if provided the expiration of the item, otherwise the default is used */ PnPClientStorageWrapper.prototype.put = function (key, o, expire) { if (this.enabled) { this.store.setItem(key, this.createPersistable(o, expire)); } }; /** * Deletes a value from the underlying storage * * @param key The key of the pair we want to remove from storage */ PnPClientStorageWrapper.prototype.delete = function (key) { if (this.enabled) { this.store.removeItem(key); } }; /** * Gets an item from the underlying storage, or adds it if it does not exist using the supplied getter function * * @param key The key to use when storing the provided value * @param getter A function which will upon execution provide the desired value * @param expire Optional, if provided the expiration of the item, otherwise the default is used */ PnPClientStorageWrapper.prototype.getOrPut = function (key, getter, expire) { var _this = this; if (!this.enabled) { return getter(); } return new Promise(function (resolve) { var o = _this.get(key); if (o == null) { getter().then(function (d) { _this.put(key, d, expire); resolve(d); }); } else { resolve(o); } }); }; /** * Used to determine if the wrapped storage is available currently */ PnPClientStorageWrapper.prototype.test = function () { var str = "test"; try { this.store.setItem(str, str); this.store.removeItem(str); return true; } catch (e) { return false; } }; /** * Creates the persistable to store */ PnPClientStorageWrapper.prototype.createPersistable = function (o, expire) { if (typeof expire === "undefined") { // ensure we are by default inline with the global library setting var defaultTimeout = pnplibconfig_1.RuntimeConfig.defaultCachingTimeoutSeconds; if (this.defaultTimeoutMinutes > 0) { defaultTimeout = this.defaultTimeoutMinutes * 60; } expire = util_1.Util.dateAdd(new Date(), "second", defaultTimeout); } return JSON.stringify({ expiration: expire, value: o }); }; return PnPClientStorageWrapper; }()); exports.PnPClientStorageWrapper = PnPClientStorageWrapper; /** * A thin implementation of in-memory storage for use in nodejs */ var MemoryStorage = (function () { function MemoryStorage(_store) { if (_store === void 0) { _store = new collections_1.Dictionary(); } this._store = _store; } Object.defineProperty(MemoryStorage.prototype, "length", { get: function () { return this._store.count(); }, enumerable: true, configurable: true }); MemoryStorage.prototype.clear = function () { this._store.clear(); }; MemoryStorage.prototype.getItem = function (key) { return this._store.get(key); }; MemoryStorage.prototype.key = function (index) { return this._store.getKeys()[index]; }; MemoryStorage.prototype.removeItem = function (key) { this._store.remove(key); }; MemoryStorage.prototype.setItem = function (key, data) { this._store.add(key, data); }; return MemoryStorage; }()); /** * A class that will establish wrappers for both local and session storage */ var PnPClientStorage = (function () { /** * Creates a new instance of the PnPClientStorage class * * @constructor */ function PnPClientStorage() { this.local = typeof localStorage !== "undefined" ? new PnPClientStorageWrapper(localStorage) : new PnPClientStorageWrapper(new MemoryStorage()); this.session = typeof sessionStorage !== "undefined" ? new PnPClientStorageWrapper(sessionStorage) : new PnPClientStorageWrapper(new MemoryStorage()); } return PnPClientStorage; }()); exports.PnPClientStorage = PnPClientStorage; /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var digestcache_1 = __webpack_require__(38); var util_1 = __webpack_require__(0); var pnplibconfig_1 = __webpack_require__(4); var exceptions_1 = __webpack_require__(3); var HttpClient = (function () { function HttpClient() { this._impl = pnplibconfig_1.RuntimeConfig.fetchClientFactory(); this._digestCache = new digestcache_1.DigestCache(this); } HttpClient.prototype.fetch = function (url, options) { var _this = this; if (options === void 0) { options = {}; } var opts = util_1.Util.extend(options, { cache: "no-cache", credentials: "same-origin" }, true); var headers = new Headers(); // first we add the global headers so they can be overwritten by any passed in locally to this call this.mergeHeaders(headers, pnplibconfig_1.RuntimeConfig.headers); // second we add the local options so we can overwrite the globals this.mergeHeaders(headers, options.headers); // lastly we apply any default headers we need that may not exist if (!headers.has("Accept")) { headers.append("Accept", "application/json"); } if (!headers.has("Content-Type")) { headers.append("Content-Type", "application/json;odata=verbose;charset=utf-8"); } if (!headers.has("X-ClientService-ClientTag")) { headers.append("X-ClientService-ClientTag", "PnPCoreJS:2.0.6-beta.1"); } opts = util_1.Util.extend(opts, { headers: headers }); if (opts.method && opts.method.toUpperCase() !== "GET") { if (!headers.has("X-RequestDigest")) { var index = url.indexOf("_api/"); if (index < 0) { throw new exceptions_1.APIUrlException(); } var webUrl = url.substr(0, index); return this._digestCache.getDigest(webUrl) .then(function (digest) { headers.append("X-RequestDigest", digest); return _this.fetchRaw(url, opts); }); } } return this.fetchRaw(url, opts); }; HttpClient.prototype.fetchRaw = function (url, options) { var _this = this; if (options === void 0) { options = {}; } // here we need to normalize the headers var rawHeaders = new Headers(); this.mergeHeaders(rawHeaders, options.headers); options = util_1.Util.extend(options, { headers: rawHeaders }); var retry = function (ctx) { _this._impl.fetch(url, options).then(function (response) { return ctx.resolve(response); }).catch(function (response) { // grab our current delay var delay = ctx.delay; // Check if request was throttled - http status code 429 // Check is request failed due to server unavailable - http status code 503 if (response.status !== 429 && response.status !== 503) { ctx.reject(response); } // Increment our counters. ctx.delay *= 2; ctx.attempts++; // If we have exceeded the retry count, reject. if (ctx.retryCount <= ctx.attempts) { ctx.reject(response); } // Set our retry timeout for {delay} milliseconds. setTimeout(util_1.Util.getCtxCallback(_this, retry, ctx), delay); }); }; return new Promise(function (resolve, reject) { var retryContext = { attempts: 0, delay: 100, reject: reject, resolve: resolve, retryCount: 7, }; retry.call(_this, retryContext); }); }; HttpClient.prototype.get = function (url, options) { if (options === void 0) { options = {}; } var opts = util_1.Util.extend(options, { method: "GET" }); return this.fetch(url, opts); }; HttpClient.prototype.post = function (url, options) { if (options === void 0) { options = {}; } var opts = util_1.Util.extend(options, { method: "POST" }); return this.fetch(url, opts); }; HttpClient.prototype.patch = function (url, options) { if (options === void 0) { options = {}; } var opts = util_1.Util.extend(options, { method: "PATCH" }); return this.fetch(url, opts); }; HttpClient.prototype.delete = function (url, options) { if (options === void 0) { options = {}; } var opts = util_1.Util.extend(options, { method: "DELETE" }); return this.fetch(url, opts); }; HttpClient.prototype.mergeHeaders = function (target, source) { if (typeof source !== "undefined" && source !== null) { var temp = new Request("", { headers: source }); temp.headers.forEach(function (value, name) { target.append(name, value); }); } }; return HttpClient; }()); exports.HttpClient = HttpClient; ; /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = __webpack_require__(0); var queryable_1 = __webpack_require__(1); /** * Describes a collection of content types * */ var ContentTypes = (function (_super) { __extends(ContentTypes, _super); /** * Creates a new instance of the ContentTypes class * * @param baseUrl The url or Queryable which forms the parent of this content types collection */ function ContentTypes(baseUrl, path) { if (path === void 0) { path = "contenttypes"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a ContentType by content type id */ ContentTypes.prototype.getById = function (id) { var ct = new ContentType(this); ct.concat("('" + id + "')"); return ct; }; /** * Adds an existing contenttype to a content type collection * * @param contentTypeId in the following format, for example: 0x010102 */ ContentTypes.prototype.addAvailableContentType = function (contentTypeId) { var _this = this; var postBody = JSON.stringify({ "contentTypeId": contentTypeId, }); return this.clone(ContentTypes, "addAvailableContentType", true).postAs({ body: postBody }).then(function (data) { return { contentType: _this.getById(data.id), data: data, }; }); }; /** * Adds a new content type to the collection * * @param id The desired content type id for the new content type (also determines the parent content type) * @param name The name of the content type * @param description The description of the content type * @param group The group in which to add the content type * @param additionalSettings Any additional settings to provide when creating the content type * */ ContentTypes.prototype.add = function (id, name, description, group, additionalSettings) { var _this = this; if (description === void 0) { description = ""; } if (group === void 0) { group = "Custom Content Types"; } if (additionalSettings === void 0) { additionalSettings = {}; } var postBody = JSON.stringify(util_1.Util.extend({ "Description": description, "Group": group, "Id": { "StringValue": id }, "Name": name, "__metadata": { "type": "SP.ContentType" }, }, additionalSettings)); return this.post({ body: postBody }).then(function (data) { return { contentType: _this.getById(data.id), data: data }; }); }; return ContentTypes; }(queryable_1.QueryableCollection)); exports.ContentTypes = ContentTypes; /** * Describes a single ContentType instance * */ var ContentType = (function (_super) { __extends(ContentType, _super); function ContentType() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(ContentType.prototype, "fieldLinks", { /** * Gets the column (also known as field) references in the content type. */ get: function () { return new FieldLinks(this); }, enumerable: true, configurable: true }); Object.defineProperty(ContentType.prototype, "fields", { /** * Gets a value that specifies the collection of fields for the content type. */ get: function () { return new queryable_1.QueryableCollection(this, "fields"); }, enumerable: true, configurable: true }); Object.defineProperty(ContentType.prototype, "parent", { /** * Gets the parent content type of the content type. */ get: function () { return new ContentType(this, "parent"); }, enumerable: true, configurable: true }); Object.defineProperty(ContentType.prototype, "workflowAssociations", { /** * Gets a value that specifies the collection of workflow associations for the content type. */ get: function () { return new queryable_1.QueryableCollection(this, "workflowAssociations"); }, enumerable: true, configurable: true }); /** * Delete this content type */ ContentType.prototype.delete = function () { return this.post({ headers: { "X-HTTP-Method": "DELETE", }, }); }; return ContentType; }(queryable_1.QueryableInstance)); exports.ContentType = ContentType; /** * Represents a collection of field link instances */ var FieldLinks = (function (_super) { __extends(FieldLinks, _super); /** * Creates a new instance of the ContentType class * * @param baseUrl The url or Queryable which forms the parent of this content type instance */ function FieldLinks(baseUrl, path) { if (path === void 0) { path = "fieldlinks"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a FieldLink by GUID id * * @param id The GUID id of the field link */ FieldLinks.prototype.getById = function (id) { var fl = new FieldLink(this); fl.concat("(guid'" + id + "')"); return fl; }; return FieldLinks; }(queryable_1.QueryableCollection)); exports.FieldLinks = FieldLinks; /** * Represents a field link instance */ var FieldLink = (function (_super) { __extends(FieldLink, _super); function FieldLink() { return _super !== null && _super.apply(this, arguments) || this; } return FieldLink; }(queryable_1.QueryableInstance)); exports.FieldLink = FieldLink; /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var sitegroups_1 = __webpack_require__(18); var util_1 = __webpack_require__(0); /** * Describes a set of role assignments for the current scope * */ var RoleAssignments = (function (_super) { __extends(RoleAssignments, _super); /** * Creates a new instance of the RoleAssignments class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function RoleAssignments(baseUrl, path) { if (path === void 0) { path = "roleassignments"; } return _super.call(this, baseUrl, path) || this; } /** * Adds a new role assignment with the specified principal and role definitions to the collection. * * @param principalId The ID of the user or group to assign permissions to * @param roleDefId The ID of the role definition that defines the permissions to assign * */ RoleAssignments.prototype.add = function (principalId, roleDefId) { return this.clone(RoleAssignments, "addroleassignment(principalid=" + principalId + ", roledefid=" + roleDefId + ")", true).post(); }; /** * Removes the role assignment with the specified principal and role definition from the collection * * @param principalId The ID of the user or group in the role assignment. * @param roleDefId The ID of the role definition in the role assignment * */ RoleAssignments.prototype.remove = function (principalId, roleDefId) { return this.clone(RoleAssignments, "removeroleassignment(principalid=" + principalId + ", roledefid=" + roleDefId + ")", true).post(); }; /** * Gets the role assignment associated with the specified principal ID from the collection. * * @param id The id of the role assignment */ RoleAssignments.prototype.getById = function (id) { var ra = new RoleAssignment(this); ra.concat("(" + id + ")"); return ra; }; return RoleAssignments; }(queryable_1.QueryableCollection)); exports.RoleAssignments = RoleAssignments; var RoleAssignment = (function (_super) { __extends(RoleAssignment, _super); function RoleAssignment() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(RoleAssignment.prototype, "groups", { get: function () { return new sitegroups_1.SiteGroups(this, "groups"); }, enumerable: true, configurable: true }); Object.defineProperty(RoleAssignment.prototype, "bindings", { /** * Get the role definition bindings for this role assignment * */ get: function () { return new RoleDefinitionBindings(this); }, enumerable: true, configurable: true }); /** * Delete this role assignment * */ RoleAssignment.prototype.delete = function () { return this.post({ headers: { "X-HTTP-Method": "DELETE", }, }); }; return RoleAssignment; }(queryable_1.QueryableInstance)); exports.RoleAssignment = RoleAssignment; var RoleDefinitions = (function (_super) { __extends(RoleDefinitions, _super); /** * Creates a new instance of the RoleDefinitions class * * @param baseUrl The url or Queryable which forms the parent of this fields collection * @param path * */ function RoleDefinitions(baseUrl, path) { if (path === void 0) { path = "roledefinitions"; } return _super.call(this, baseUrl, path) || this; } /** * Gets the role definition with the specified ID from the collection. * * @param id The ID of the role definition. * */ RoleDefinitions.prototype.getById = function (id) { return new RoleDefinition(this, "getById(" + id + ")"); }; /** * Gets the role definition with the specified name. * * @param name The name of the role definition. * */ RoleDefinitions.prototype.getByName = function (name) { return new RoleDefinition(this, "getbyname('" + name + "')"); }; /** * Gets the role definition with the specified type. * * @param name The name of the role definition. * */ RoleDefinitions.prototype.getByType = function (roleTypeKind) { return new RoleDefinition(this, "getbytype(" + roleTypeKind + ")"); }; /** * Create a role definition * * @param name The new role definition's name * @param description The new role definition's description * @param order The order in which the role definition appears * @param basePermissions The permissions mask for this role definition * */ RoleDefinitions.prototype.add = function (name, description, order, basePermissions) { var _this = this; var postBody = JSON.stringify({ BasePermissions: util_1.Util.extend({ __metadata: { type: "SP.BasePermissions" } }, basePermissions), Description: description, Name: name, Order: order, __metadata: { "type": "SP.RoleDefinition" }, }); return this.post({ body: postBody }).then(function (data) { return { data: data, definition: _this.getById(data.Id), }; }); }; return RoleDefinitions; }(queryable_1.QueryableCollection)); exports.RoleDefinitions = RoleDefinitions; var RoleDefinition = (function (_super) { __extends(RoleDefinition, _super); function RoleDefinition() { return _super !== null && _super.apply(this, arguments) || this; } /** * Updates this web intance with the supplied properties * * @param properties A plain object hash of values to update for the web */ /* tslint:disable no-string-literal */ RoleDefinition.prototype.update = function (properties) { var _this = this; if (typeof properties.hasOwnProperty("BasePermissions") !== "undefined") { properties["BasePermissions"] = util_1.Util.extend({ __metadata: { type: "SP.BasePermissions" } }, properties["BasePermissions"]); } var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.RoleDefinition" }, }, properties)); return this.post({ body: postBody, headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { var retDef = _this; if (properties.hasOwnProperty("Name")) { var parent_1 = _this.getParent(RoleDefinitions, _this.parentUrl, ""); retDef = parent_1.getByName(properties["Name"]); } return { data: data, definition: retDef, }; }); }; /* tslint:enable */ /** * Delete this role definition * */ RoleDefinition.prototype.delete = function () { return this.post({ headers: { "X-HTTP-Method": "DELETE", }, }); }; return RoleDefinition; }(queryable_1.QueryableInstance)); exports.RoleDefinition = RoleDefinition; var RoleDefinitionBindings = (function (_super) { __extends(RoleDefinitionBindings, _super); function RoleDefinitionBindings(baseUrl, path) { if (path === void 0) { path = "roledefinitionbindings"; } return _super.call(this, baseUrl, path) || this; } return RoleDefinitionBindings; }(queryable_1.QueryableCollection)); exports.RoleDefinitionBindings = RoleDefinitionBindings; /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var siteusers_1 = __webpack_require__(30); var util_1 = __webpack_require__(0); /** * Principal Type enum * */ var PrincipalType; (function (PrincipalType) { PrincipalType[PrincipalType["None"] = 0] = "None"; PrincipalType[PrincipalType["User"] = 1] = "User"; PrincipalType[PrincipalType["DistributionList"] = 2] = "DistributionList"; PrincipalType[PrincipalType["SecurityGroup"] = 4] = "SecurityGroup"; PrincipalType[PrincipalType["SharePointGroup"] = 8] = "SharePointGroup"; PrincipalType[PrincipalType["All"] = 15] = "All"; })(PrincipalType = exports.PrincipalType || (exports.PrincipalType = {})); /** * Describes a collection of site groups * */ var SiteGroups = (function (_super) { __extends(SiteGroups, _super); /** * Creates a new instance of the SiteGroups class * * @param baseUrl The url or Queryable which forms the parent of this group collection */ function SiteGroups(baseUrl, path) { if (path === void 0) { path = "sitegroups"; } return _super.call(this, baseUrl, path) || this; } /** * Adds a new group to the site collection * * @param props The group properties object of property names and values to be set for the group */ SiteGroups.prototype.add = function (properties) { var _this = this; var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.Group" } }, properties)); return this.post({ body: postBody }).then(function (data) { return { data: data, group: _this.getById(data.Id), }; }); }; /** * Gets a group from the collection by name * * @param groupName The name of the group to retrieve */ SiteGroups.prototype.getByName = function (groupName) { return new SiteGroup(this, "getByName('" + groupName + "')"); }; /** * Gets a group from the collection by id * * @param id The id of the group to retrieve */ SiteGroups.prototype.getById = function (id) { var sg = new SiteGroup(this); sg.concat("(" + id + ")"); return sg; }; /** * Removes the group with the specified member id from the collection * * @param id The id of the group to remove */ SiteGroups.prototype.removeById = function (id) { return this.clone(SiteGroups, "removeById('" + id + "')", true).post(); }; /** * Removes the cross-site group with the specified name from the collection * * @param loginName The name of the group to remove */ SiteGroups.prototype.removeByLoginName = function (loginName) { return this.clone(SiteGroups, "removeByLoginName('" + loginName + "')", true).post(); }; return SiteGroups; }(queryable_1.QueryableCollection)); exports.SiteGroups = SiteGroups; /** * Describes a single group * */ var SiteGroup = (function (_super) { __extends(SiteGroup, _super); function SiteGroup() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(SiteGroup.prototype, "users", { /** * Gets the users for this group * */ get: function () { return new siteusers_1.SiteUsers(this, "users"); }, enumerable: true, configurable: true }); /** * Updates this group instance with the supplied properties * * @param properties A GroupWriteableProperties object of property names and values to update for the group */ /* tslint:disable no-string-literal */ SiteGroup.prototype.update = function (properties) { var _this = this; var postBody = util_1.Util.extend({ "__metadata": { "type": "SP.Group" } }, properties); return this.post({ body: JSON.stringify(postBody), headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { var retGroup = _this; if (properties.hasOwnProperty("Title")) { retGroup = _this.getParent(SiteGroup, _this.parentUrl, "getByName('" + properties["Title"] + "')"); } return { data: data, group: retGroup, }; }); }; return SiteGroup; }(queryable_1.QueryableInstance)); exports.SiteGroup = SiteGroup; /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var util_1 = __webpack_require__(0); /** * Describes a collection of user custom actions * */ var UserCustomActions = (function (_super) { __extends(UserCustomActions, _super); /** * Creates a new instance of the UserCustomActions class * * @param baseUrl The url or Queryable which forms the parent of this user custom actions collection */ function UserCustomActions(baseUrl, path) { if (path === void 0) { path = "usercustomactions"; } return _super.call(this, baseUrl, path) || this; } /** * Returns the user custom action with the specified id * * @param id The GUID id of the user custom action to retrieve */ UserCustomActions.prototype.getById = function (id) { var uca = new UserCustomAction(this); uca.concat("('" + id + "')"); return uca; }; /** * Creates a user custom action * * @param properties The information object of property names and values which define the new user custom action * */ UserCustomActions.prototype.add = function (properties) { var _this = this; var postBody = JSON.stringify(util_1.Util.extend({ __metadata: { "type": "SP.UserCustomAction" } }, properties)); return this.post({ body: postBody }).then(function (data) { return { action: _this.getById(data.Id), data: data, }; }); }; /** * Deletes all user custom actions in the collection * */ UserCustomActions.prototype.clear = function () { return this.clone(UserCustomActions, "clear", true).post(); }; return UserCustomActions; }(queryable_1.QueryableCollection)); exports.UserCustomActions = UserCustomActions; /** * Describes a single user custom action * */ var UserCustomAction = (function (_super) { __extends(UserCustomAction, _super); function UserCustomAction() { return _super !== null && _super.apply(this, arguments) || this; } /** * Updates this user custom action with the supplied properties * * @param properties An information object of property names and values to update for this user custom action */ UserCustomAction.prototype.update = function (properties) { var _this = this; var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.UserCustomAction" }, }, properties)); return this.post({ body: postBody, headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { return { action: _this, data: data, }; }); }; /** * Removes this user custom action * */ UserCustomAction.prototype.delete = function () { return _super.prototype.delete.call(this); }; return UserCustomAction; }(queryable_1.QueryableInstance)); exports.UserCustomAction = UserCustomAction; /***/ }), /* 20 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var storage = __webpack_require__(14); var exceptions_1 = __webpack_require__(3); /** * A caching provider which can wrap other non-caching providers * */ var CachingConfigurationProvider = (function () { /** * Creates a new caching configuration provider * @constructor * @param {IConfigurationProvider} wrappedProvider Provider which will be used to fetch the configuration * @param {string} cacheKey Key that will be used to store cached items to the cache * @param {IPnPClientStore} cacheStore OPTIONAL storage, which will be used to store cached settings. */ function CachingConfigurationProvider(wrappedProvider, cacheKey, cacheStore) { this.wrappedProvider = wrappedProvider; this.store = (cacheStore) ? cacheStore : this.selectPnPCache(); this.cacheKey = "_configcache_" + cacheKey; } /** * Gets the wrapped configuration providers * * @return {IConfigurationProvider} Wrapped configuration provider */ CachingConfigurationProvider.prototype.getWrappedProvider = function () { return this.wrappedProvider; }; /** * Loads the configuration values either from the cache or from the wrapped provider * * @return {Promise<TypedHash<string>>} Promise of loaded configuration values */ CachingConfigurationProvider.prototype.getConfiguration = function () { var _this = this; // Cache not available, pass control to the wrapped provider if ((!this.store) || (!this.store.enabled)) { return this.wrappedProvider.getConfiguration(); } // Value is found in cache, return it directly var cachedConfig = this.store.get(this.cacheKey); if (cachedConfig) { return new Promise(function (resolve) { resolve(cachedConfig); }); } // Get and cache value from the wrapped provider var providerPromise = this.wrappedProvider.getConfiguration(); providerPromise.then(function (providedConfig) { _this.store.put(_this.cacheKey, providedConfig); }); return providerPromise; }; CachingConfigurationProvider.prototype.selectPnPCache = function () { var pnpCache = new storage.PnPClientStorage(); if ((pnpCache.local) && (pnpCache.local.enabled)) { return pnpCache.local; } if ((pnpCache.session) && (pnpCache.session.enabled)) { return pnpCache.session; } throw new exceptions_1.NoCacheAvailableException(); }; return CachingConfigurationProvider; }()); exports.default = CachingConfigurationProvider; /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) { Object.defineProperty(exports, "__esModule", { value: true }); /** * Makes requests using the fetch API */ var FetchClient = (function () { function FetchClient() { } FetchClient.prototype.fetch = function (url, options) { return global.fetch(url, options); }; return FetchClient; }()); exports.FetchClient = FetchClient; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(32))) /***/ }), /* 22 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var storage_1 = __webpack_require__(14); var util_1 = __webpack_require__(0); var pnplibconfig_1 = __webpack_require__(4); var CachingOptions = (function () { function CachingOptions(key) { this.key = key; this.expiration = util_1.Util.dateAdd(new Date(), "second", pnplibconfig_1.RuntimeConfig.defaultCachingTimeoutSeconds); this.storeName = pnplibconfig_1.RuntimeConfig.defaultCachingStore; } Object.defineProperty(CachingOptions.prototype, "store", { get: function () { if (this.storeName === "local") { return CachingOptions.storage.local; } else { return CachingOptions.storage.session; } }, enumerable: true, configurable: true }); return CachingOptions; }()); CachingOptions.storage = new storage_1.PnPClientStorage(); exports.CachingOptions = CachingOptions; var CachingParserWrapper = (function () { function CachingParserWrapper(_parser, _cacheOptions) { this._parser = _parser; this._cacheOptions = _cacheOptions; } CachingParserWrapper.prototype.parse = function (response) { var _this = this; // add this to the cache based on the options return this._parser.parse(response).then(function (data) { if (_this._cacheOptions.store !== null) { _this._cacheOptions.store.put(_this._cacheOptions.key, data, _this._cacheOptions.expiration); } return data; }); }; return CachingParserWrapper; }()); exports.CachingParserWrapper = CachingParserWrapper; /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); /** * Describes a collection of List objects * */ var Features = (function (_super) { __extends(Features, _super); /** * Creates a new instance of the Lists class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Features(baseUrl, path) { if (path === void 0) { path = "features"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a list from the collection by guid id * * @param id The Id of the feature (GUID) */ Features.prototype.getById = function (id) { var feature = new Feature(this); feature.concat("('" + id + "')"); return feature; }; /** * Adds a new list to the collection * * @param id The Id of the feature (GUID) * @param force If true the feature activation will be forced */ Features.prototype.add = function (id, force) { var _this = this; if (force === void 0) { force = false; } return this.clone(Features, "add", true).post({ body: JSON.stringify({ featdefScope: 0, featureId: id, force: force, }), }).then(function (data) { return { data: data, feature: _this.getById(id), }; }); }; /** * Removes (deactivates) a feature from the collection * * @param id The Id of the feature (GUID) * @param force If true the feature deactivation will be forced */ Features.prototype.remove = function (id, force) { if (force === void 0) { force = false; } return this.clone(Features, "remove", true).post({ body: JSON.stringify({ featureId: id, force: force, }), }); }; return Features; }(queryable_1.QueryableCollection)); exports.Features = Features; var Feature = (function (_super) { __extends(Feature, _super); function Feature() { return _super !== null && _super.apply(this, arguments) || this; } /** * Removes (deactivates) a feature from the collection * * @param force If true the feature deactivation will be forced */ Feature.prototype.deactivate = function (force) { var _this = this; if (force === void 0) { force = false; } var removeDependency = this.addBatchDependency(); var idGet = new Feature(this).select("DefinitionId"); return idGet.getAs().then(function (feature) { var promise = _this.getParent(Features, _this.parentUrl, "", _this.batch).remove(feature.DefinitionId, force); removeDependency(); return promise; }); }; return Feature; }(queryable_1.QueryableInstance)); exports.Feature = Feature; /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var util_1 = __webpack_require__(0); var types_1 = __webpack_require__(13); /** * Describes a collection of Field objects * */ var Fields = (function (_super) { __extends(Fields, _super); /** * Creates a new instance of the Fields class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Fields(baseUrl, path) { if (path === void 0) { path = "fields"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a field from the collection by title * * @param title The case-sensitive title of the field */ Fields.prototype.getByTitle = function (title) { return new Field(this, "getByTitle('" + title + "')"); }; /** * Gets a field from the collection by using internal name or title * * @param name The case-sensitive internal name or title of the field */ Fields.prototype.getByInternalNameOrTitle = function (name) { return new Field(this, "getByInternalNameOrTitle('" + name + "')"); }; /** * Gets a list from the collection by guid id * * @param title The Id of the list */ Fields.prototype.getById = function (id) { var f = new Field(this); f.concat("('" + id + "')"); return f; }; /** * Creates a field based on the specified schema */ Fields.prototype.createFieldAsXml = function (xml) { var _this = this; var info; if (typeof xml === "string") { info = { SchemaXml: xml }; } else { info = xml; } var postBody = JSON.stringify({ "parameters": util_1.Util.extend({ "__metadata": { "type": "SP.XmlSchemaFieldCreationInformation", }, }, info), }); return this.clone(Fields, "createfieldasxml", true).postAs({ body: postBody }).then(function (data) { return { data: data, field: _this.getById(data.Id), }; }); }; /** * Adds a new list to the collection * * @param title The new field's title * @param fieldType The new field's type (ex: SP.FieldText) * @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx) */ Fields.prototype.add = function (title, fieldType, properties) { var _this = this; if (properties === void 0) { properties = {}; } var postBody = JSON.stringify(util_1.Util.extend({ "Title": title, "__metadata": { "type": fieldType }, }, properties)); return this.clone(Fields, null, true).postAs({ body: postBody }).then(function (data) { return { data: data, field: _this.getById(data.Id), }; }); }; /** * Adds a new SP.FieldText to the collection * * @param title The field title * @param maxLength The maximum number of characters allowed in the value of the field. * @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx) */ Fields.prototype.addText = function (title, maxLength, properties) { if (maxLength === void 0) { maxLength = 255; } var props = { FieldTypeKind: 2, MaxLength: maxLength, }; return this.add(title, "SP.FieldText", util_1.Util.extend(props, properties)); }; /** * Adds a new SP.FieldCalculated to the collection * * @param title The field title. * @param formula The formula for the field. * @param dateFormat The date and time format that is displayed in the field. * @param outputType Specifies the output format for the field. Represents a FieldType value. * @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx) */ Fields.prototype.addCalculated = function (title, formula, dateFormat, outputType, properties) { if (outputType === void 0) { outputType = types_1.FieldTypes.Text; } var props = { DateFormat: dateFormat, FieldTypeKind: 17, Formula: formula, OutputType: outputType, }; return this.add(title, "SP.FieldCalculated", util_1.Util.extend(props, properties)); }; /** * Adds a new SP.FieldDateTime to the collection * * @param title The field title * @param displayFormat The format of the date and time that is displayed in the field. * @param calendarType Specifies the calendar type of the field. * @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx) */ Fields.prototype.addDateTime = function (title, displayFormat, calendarType, friendlyDisplayFormat, properties) { if (displayFormat === void 0) { displayFormat = types_1.DateTimeFieldFormatType.DateOnly; } if (calendarType === void 0) { calendarType = types_1.CalendarType.Gregorian; } if (friendlyDisplayFormat === void 0) { friendlyDisplayFormat = 0; } var props = { DateTimeCalendarType: calendarType, DisplayFormat: displayFormat, FieldTypeKind: 4, FriendlyDisplayFormat: friendlyDisplayFormat, }; return this.add(title, "SP.FieldDateTime", util_1.Util.extend(props, properties)); }; /** * Adds a new SP.FieldNumber to the collection * * @param title The field title * @param minValue The field's minimum value * @param maxValue The field's maximum value * @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx) */ Fields.prototype.addNumber = function (title, minValue, maxValue, properties) { var props = { FieldTypeKind: 9 }; if (typeof minValue !== "undefined") { props = util_1.Util.extend({ MinimumValue: minValue }, props); } if (typeof maxValue !== "undefined") { props = util_1.Util.extend({ MaximumValue: maxValue }, props); } return this.add(title, "SP.FieldNumber", util_1.Util.extend(props, properties)); }; /** * Adds a new SP.FieldCurrency to the collection * * @param title The field title * @param minValue The field's minimum value * @param maxValue The field's maximum value * @param currencyLocalId Specifies the language code identifier (LCID) used to format the value of the field * @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx) */ Fields.prototype.addCurrency = function (title, minValue, maxValue, currencyLocalId, properties) { if (currencyLocalId === void 0) { currencyLocalId = 1033; } var props = { CurrencyLocaleId: currencyLocalId, FieldTypeKind: 10, }; if (typeof minValue !== "undefined") { props = util_1.Util.extend({ MinimumValue: minValue }, props); } if (typeof maxValue !== "undefined") { props = util_1.Util.extend({ MaximumValue: maxValue }, props); } return this.add(title, "SP.FieldCurrency", util_1.Util.extend(props, properties)); }; /** * Adds a new SP.FieldMultiLineText to the collection * * @param title The field title * @param numberOfLines Specifies the number of lines of text to display for the field. * @param richText Specifies whether the field supports rich formatting. * @param restrictedMode Specifies whether the field supports a subset of rich formatting. * @param appendOnly Specifies whether all changes to the value of the field are displayed in list forms. * @param allowHyperlink Specifies whether a hyperlink is allowed as a value of the field. * @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx) * */ Fields.prototype.addMultilineText = function (title, numberOfLines, richText, restrictedMode, appendOnly, allowHyperlink, properties) { if (numberOfLines === void 0) { numberOfLines = 6; } if (richText === void 0) { richText = true; } if (restrictedMode === void 0) { restrictedMode = false; } if (appendOnly === void 0) { appendOnly = false; } if (allowHyperlink === void 0) { allowHyperlink = true; } var props = { AllowHyperlink: allowHyperlink, AppendOnly: appendOnly, FieldTypeKind: 3, NumberOfLines: numberOfLines, RestrictedMode: restrictedMode, RichText: richText, }; return this.add(title, "SP.FieldMultiLineText", util_1.Util.extend(props, properties)); }; /** * Adds a new SP.FieldUrl to the collection * * @param title The field title */ Fields.prototype.addUrl = function (title, displayFormat, properties) { if (displayFormat === void 0) { displayFormat = types_1.UrlFieldFormatType.Hyperlink; } var props = { DisplayFormat: displayFormat, FieldTypeKind: 11, }; return this.add(title, "SP.FieldUrl", util_1.Util.extend(props, properties)); }; return Fields; }(queryable_1.QueryableCollection)); exports.Fields = Fields; /** * Describes a single of Field instance * */ var Field = (function (_super) { __extends(Field, _super); function Field() { return _super !== null && _super.apply(this, arguments) || this; } /** * Updates this field intance with the supplied properties * * @param properties A plain object hash of values to update for the list * @param fieldType The type value, required to update child field type properties */ Field.prototype.update = function (properties, fieldType) { var _this = this; if (fieldType === void 0) { fieldType = "SP.Field"; } var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": fieldType }, }, properties)); return this.post({ body: postBody, headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { return { data: data, field: _this, }; }); }; /** * Delete this fields * */ Field.prototype.delete = function () { return this.post({ headers: { "X-HTTP-Method": "DELETE", }, }); }; /** * Sets the value of the ShowInDisplayForm property for this field. */ Field.prototype.setShowInDisplayForm = function (show) { return this.clone(Field, "setshowindisplayform(" + show + ")", true).post(); }; /** * Sets the value of the ShowInEditForm property for this field. */ Field.prototype.setShowInEditForm = function (show) { return this.clone(Field, "setshowineditform(" + show + ")", true).post(); }; /** * Sets the value of the ShowInNewForm property for this field. */ Field.prototype.setShowInNewForm = function (show) { return this.clone(Field, "setshowinnewform(" + show + ")", true).post(); }; return Field; }(queryable_1.QueryableInstance)); exports.Field = Field; /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = __webpack_require__(0); var queryable_1 = __webpack_require__(1); /** * Represents a collection of navigation nodes * */ var NavigationNodes = (function (_super) { __extends(NavigationNodes, _super); function NavigationNodes() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets a navigation node by id * * @param id The id of the node */ NavigationNodes.prototype.getById = function (id) { var node = new NavigationNode(this); node.concat("(" + id + ")"); return node; }; /** * Adds a new node to the collection * * @param title Display name of the node * @param url The url of the node * @param visible If true the node is visible, otherwise it is hidden (default: true) */ NavigationNodes.prototype.add = function (title, url, visible) { var _this = this; if (visible === void 0) { visible = true; } var postBody = JSON.stringify({ IsVisible: visible, Title: title, Url: url, "__metadata": { "type": "SP.NavigationNode" }, }); return this.clone(NavigationNodes, null, true).post({ body: postBody }).then(function (data) { return { data: data, node: _this.getById(data.Id), }; }); }; /** * Moves a node to be after another node in the navigation * * @param nodeId Id of the node to move * @param previousNodeId Id of the node after which we move the node specified by nodeId */ NavigationNodes.prototype.moveAfter = function (nodeId, previousNodeId) { var postBody = JSON.stringify({ nodeId: nodeId, previousNodeId: previousNodeId, }); return this.clone(NavigationNodes, "MoveAfter", true).post({ body: postBody }); }; return NavigationNodes; }(queryable_1.QueryableCollection)); exports.NavigationNodes = NavigationNodes; var NavigationNode = (function (_super) { __extends(NavigationNode, _super); function NavigationNode() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(NavigationNode.prototype, "children", { /** * Represents the child nodes of this node */ get: function () { return new NavigationNodes(this, "Children"); }, enumerable: true, configurable: true }); /** * Updates this node based on the supplied properties * * @param properties The hash of key/value pairs to update */ NavigationNode.prototype.update = function (properties) { var _this = this; var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.NavigationNode" }, }, properties)); return this.post({ body: postBody, headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { return { data: data, node: _this, }; }); }; /** * Deletes this node and any child nodes */ NavigationNode.prototype.delete = function () { return _super.prototype.delete.call(this); }; return NavigationNode; }(queryable_1.QueryableInstance)); exports.NavigationNode = NavigationNode; /** * Exposes the navigation components * */ var Navigation = (function (_super) { __extends(Navigation, _super); /** * Creates a new instance of the Lists class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Navigation(baseUrl, path) { if (path === void 0) { path = "navigation"; } return _super.call(this, baseUrl, path) || this; } Object.defineProperty(Navigation.prototype, "quicklaunch", { /** * Gets the quicklaunch navigation for the current context * */ get: function () { return new NavigationNodes(this, "quicklaunch"); }, enumerable: true, configurable: true }); Object.defineProperty(Navigation.prototype, "topNavigationBar", { /** * Gets the top bar navigation navigation for the current context * */ get: function () { return new NavigationNodes(this, "topnavigationbar"); }, enumerable: true, configurable: true }); return Navigation; }(queryable_1.Queryable)); exports.Navigation = Navigation; /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var webs_1 = __webpack_require__(8); var roles_1 = __webpack_require__(17); var types_1 = __webpack_require__(13); var queryable_1 = __webpack_require__(1); var QueryableSecurable = (function (_super) { __extends(QueryableSecurable, _super); function QueryableSecurable() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(QueryableSecurable.prototype, "roleAssignments", { /** * Gets the set of role assignments for this item * */ get: function () { return new roles_1.RoleAssignments(this); }, enumerable: true, configurable: true }); Object.defineProperty(QueryableSecurable.prototype, "firstUniqueAncestorSecurableObject", { /** * Gets the closest securable up the security hierarchy whose permissions are applied to this list item * */ get: function () { return new queryable_1.QueryableInstance(this, "FirstUniqueAncestorSecurableObject"); }, enumerable: true, configurable: true }); /** * Gets the effective permissions for the user supplied * * @param loginName The claims username for the user (ex: i:0#.f|membership|[email protected]) */ QueryableSecurable.prototype.getUserEffectivePermissions = function (loginName) { var q = this.clone(queryable_1.Queryable, "getUserEffectivePermissions(@user)", true); q.query.add("@user", "'" + encodeURIComponent(loginName) + "'"); return q.getAs(); }; /** * Gets the effective permissions for the current user */ QueryableSecurable.prototype.getCurrentUserEffectivePermissions = function () { var _this = this; var w = webs_1.Web.fromUrl(this.toUrl()); return w.currentUser.select("LoginName").getAs().then(function (user) { return _this.getUserEffectivePermissions(user.LoginName); }); }; /** * Breaks the security inheritance at this level optinally copying permissions and clearing subscopes * * @param copyRoleAssignments If true the permissions are copied from the current parent scope * @param clearSubscopes Optional. true to make all child securable objects inherit role assignments from the current object */ QueryableSecurable.prototype.breakRoleInheritance = function (copyRoleAssignments, clearSubscopes) { if (copyRoleAssignments === void 0) { copyRoleAssignments = false; } if (clearSubscopes === void 0) { clearSubscopes = false; } return this.clone(QueryableSecurable, "breakroleinheritance(copyroleassignments=" + copyRoleAssignments + ", clearsubscopes=" + clearSubscopes + ")", true).post(); }; /** * Removes the local role assignments so that it re-inherit role assignments from the parent object. * */ QueryableSecurable.prototype.resetRoleInheritance = function () { return this.clone(QueryableSecurable, "resetroleinheritance", true).post(); }; /** * Determines if a given user has the appropriate permissions * * @param loginName The user to check * @param permission The permission being checked */ QueryableSecurable.prototype.userHasPermissions = function (loginName, permission) { var _this = this; return this.getUserEffectivePermissions(loginName).then(function (perms) { return _this.hasPermissions(perms, permission); }); }; /** * Determines if the current user has the requested permissions * * @param permission The permission we wish to check */ QueryableSecurable.prototype.currentUserHasPermissions = function (permission) { var _this = this; return this.getCurrentUserEffectivePermissions().then(function (perms) { return _this.hasPermissions(perms, permission); }); }; /** * Taken from sp.js, checks the supplied permissions against the mask * * @param value The security principal's permissions on the given object * @param perm The permission checked against the value */ /* tslint:disable:no-bitwise */ QueryableSecurable.prototype.hasPermissions = function (value, perm) { if (!perm) { return true; } if (perm === types_1.PermissionKind.FullMask) { return (value.High & 32767) === 32767 && value.Low === 65535; } perm = perm - 1; var num = 1; if (perm >= 0 && perm < 32) { num = num << perm; return 0 !== (value.Low & num); } else if (perm >= 32 && perm < 64) { num = num << perm - 32; return 0 !== (value.High & num); } return false; }; return QueryableSecurable; }(queryable_1.QueryableInstance)); exports.QueryableSecurable = QueryableSecurable; /***/ }), /* 27 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var util_1 = __webpack_require__(0); /** * Allows for the fluent construction of search queries */ var SearchQueryBuilder = (function () { function SearchQueryBuilder(queryText, _query) { if (queryText === void 0) { queryText = ""; } if (_query === void 0) { _query = {}; } this._query = _query; if (typeof queryText === "string" && queryText.length > 0) { this.extendQuery({ Querytext: queryText }); } } SearchQueryBuilder.create = function (queryText, queryTemplate) { if (queryText === void 0) { queryText = ""; } if (queryTemplate === void 0) { queryTemplate = {}; } return new SearchQueryBuilder(queryText, queryTemplate); }; SearchQueryBuilder.prototype.text = function (queryText) { return this.extendQuery({ Querytext: queryText }); }; SearchQueryBuilder.prototype.template = function (template) { return this.extendQuery({ QueryTemplate: template }); }; SearchQueryBuilder.prototype.sourceId = function (id) { return this.extendQuery({ SourceId: id }); }; Object.defineProperty(SearchQueryBuilder.prototype, "enableInterleaving", { get: function () { return this.extendQuery({ EnableInterleaving: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "enableStemming", { get: function () { return this.extendQuery({ EnableStemming: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "trimDuplicates", { get: function () { return this.extendQuery({ TrimDuplicates: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "enableNicknames", { get: function () { return this.extendQuery({ EnableNicknames: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "enableFql", { get: function () { return this.extendQuery({ EnableFql: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "enablePhonetic", { get: function () { return this.extendQuery({ EnablePhonetic: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "bypassResultTypes", { get: function () { return this.extendQuery({ BypassResultTypes: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "processBestBets", { get: function () { return this.extendQuery({ ProcessBestBets: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "enableQueryRules", { get: function () { return this.extendQuery({ EnableQueryRules: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "enableSorting", { get: function () { return this.extendQuery({ EnableSorting: true }); }, enumerable: true, configurable: true }); Object.defineProperty(SearchQueryBuilder.prototype, "generateBlockRankLog", { get: function () { return this.extendQuery({ GenerateBlockRankLog: true }); }, enumerable: true, configurable: true }); SearchQueryBuilder.prototype.rankingModelId = function (id) { return this.extendQuery({ RankingModelId: id }); }; SearchQueryBuilder.prototype.startRow = function (id) { return this.extendQuery({ StartRow: id }); }; SearchQueryBuilder.prototype.rowLimit = function (id) { return this.extendQuery({ RowLimit: id }); }; SearchQueryBuilder.prototype.rowsPerPage = function (id) { return this.extendQuery({ RowsPerPage: id }); }; SearchQueryBuilder.prototype.selectProperties = function () { var properties = []; for (var _i = 0; _i < arguments.length; _i++) { properties[_i] = arguments[_i]; } return this.extendQuery({ SelectProperties: properties }); }; SearchQueryBuilder.prototype.culture = function (culture) { return this.extendQuery({ Culture: culture }); }; SearchQueryBuilder.prototype.refinementFilters = function () { var filters = []; for (var _i = 0; _i < arguments.length; _i++) { filters[_i] = arguments[_i]; } return this.extendQuery({ RefinementFilters: filters }); }; SearchQueryBuilder.prototype.refiners = function (refiners) { return this.extendQuery({ Refiners: refiners }); }; SearchQueryBuilder.prototype.hiddenConstraints = function (constraints) { return this.extendQuery({ HiddenConstraints: constraints }); }; SearchQueryBuilder.prototype.sortList = function () { var sorts = []; for (var _i = 0; _i < arguments.length; _i++) { sorts[_i] = arguments[_i]; } return this.extendQuery({ SortList: sorts }); }; SearchQueryBuilder.prototype.timeout = function (milliseconds) { return this.extendQuery({ Timeout: milliseconds }); }; SearchQueryBuilder.prototype.hithighlightedProperties = function () { var properties = []; for (var _i = 0; _i < arguments.length; _i++) { properties[_i] = arguments[_i]; } return this.extendQuery({ HithighlightedProperties: properties }); }; SearchQueryBuilder.prototype.clientType = function (clientType) { return this.extendQuery({ ClientType: clientType }); }; SearchQueryBuilder.prototype.personalizationData = function (data) { return this.extendQuery({ PersonalizationData: data }); }; SearchQueryBuilder.prototype.resultsURL = function (url) { return this.extendQuery({ ResultsURL: url }); }; SearchQueryBuilder.prototype.queryTag = function () { var tags = []; for (var _i = 0; _i < arguments.length; _i++) { tags[_i] = arguments[_i]; } return this.extendQuery({ QueryTag: tags }); }; SearchQueryBuilder.prototype.properties = function () { var properties = []; for (var _i = 0; _i < arguments.length; _i++) { properties[_i] = arguments[_i]; } return this.extendQuery({ Properties: properties }); }; Object.defineProperty(SearchQueryBuilder.prototype, "processPersonalFavorites", { get: function () { return this.extendQuery({ ProcessPersonalFavorites: true }); }, enumerable: true, configurable: true }); SearchQueryBuilder.prototype.queryTemplatePropertiesUrl = function (url) { return this.extendQuery({ QueryTemplatePropertiesUrl: url }); }; SearchQueryBuilder.prototype.reorderingRules = function () { var rules = []; for (var _i = 0; _i < arguments.length; _i++) { rules[_i] = arguments[_i]; } return this.extendQuery({ ReorderingRules: rules }); }; SearchQueryBuilder.prototype.hitHighlightedMultivaluePropertyLimit = function (limit) { return this.extendQuery({ HitHighlightedMultivaluePropertyLimit: limit }); }; Object.defineProperty(SearchQueryBuilder.prototype, "enableOrderingHitHighlightedProperty", { get: function () { return this.extendQuery({ EnableOrderingHitHighlightedProperty: true }); }, enumerable: true, configurable: true }); SearchQueryBuilder.prototype.collapseSpecification = function (spec) { return this.extendQuery({ CollapseSpecification: spec }); }; SearchQueryBuilder.prototype.uiLanguage = function (lang) { return this.extendQuery({ UIlanguage: lang }); }; SearchQueryBuilder.prototype.desiredSnippetLength = function (len) { return this.extendQuery({ DesiredSnippetLength: len }); }; SearchQueryBuilder.prototype.maxSnippetLength = function (len) { return this.extendQuery({ MaxSnippetLength: len }); }; SearchQueryBuilder.prototype.summaryLength = function (len) { return this.extendQuery({ SummaryLength: len }); }; SearchQueryBuilder.prototype.toSearchQuery = function () { return this._query; }; SearchQueryBuilder.prototype.extendQuery = function (part) { this._query = util_1.Util.extend(this._query, part); return this; }; return SearchQueryBuilder; }()); exports.SearchQueryBuilder = SearchQueryBuilder; /** * Describes the search API * */ var Search = (function (_super) { __extends(Search, _super); /** * Creates a new instance of the Search class * * @param baseUrl The url for the search context * @param query The SearchQuery object to execute */ function Search(baseUrl, path) { if (path === void 0) { path = "_api/search/postquery"; } return _super.call(this, baseUrl, path) || this; } /** * ....... * @returns Promise */ Search.prototype.execute = function (query) { var _this = this; var formattedBody; formattedBody = query; if (formattedBody.SelectProperties) { formattedBody.SelectProperties = { results: query.SelectProperties }; } if (formattedBody.RefinementFilters) { formattedBody.RefinementFilters = { results: query.RefinementFilters }; } if (formattedBody.SortList) { formattedBody.SortList = { results: query.SortList }; } if (formattedBody.HithighlightedProperties) { formattedBody.HithighlightedProperties = { results: query.HithighlightedProperties }; } if (formattedBody.ReorderingRules) { formattedBody.ReorderingRules = { results: query.ReorderingRules }; } if (formattedBody.Properties) { formattedBody.Properties = { results: query.Properties }; } var postBody = JSON.stringify({ request: util_1.Util.extend({ "__metadata": { "type": "Microsoft.Office.Server.Search.REST.SearchRequest" }, }, formattedBody), }); return this.post({ body: postBody }).then(function (data) { return new SearchResults(data, _this.toUrl(), query); }); }; return Search; }(queryable_1.QueryableInstance)); exports.Search = Search; /** * Describes the SearchResults class, which returns the formatted and raw version of the query response */ var SearchResults = (function () { /** * Creates a new instance of the SearchResult class * */ function SearchResults(rawResponse, _url, _query, _raw, _primary) { if (_raw === void 0) { _raw = null; } if (_primary === void 0) { _primary = null; } this._url = _url; this._query = _query; this._raw = _raw; this._primary = _primary; this._raw = rawResponse.postquery ? rawResponse.postquery : rawResponse; } Object.defineProperty(SearchResults.prototype, "ElapsedTime", { get: function () { return this.RawSearchResults.ElapsedTime; }, enumerable: true, configurable: true }); Object.defineProperty(SearchResults.prototype, "RowCount", { get: function () { return this.RawSearchResults.PrimaryQueryResult.RelevantResults.RowCount; }, enumerable: true, configurable: true }); Object.defineProperty(SearchResults.prototype, "TotalRows", { get: function () { return this.RawSearchResults.PrimaryQueryResult.RelevantResults.TotalRows; }, enumerable: true, configurable: true }); Object.defineProperty(SearchResults.prototype, "TotalRowsIncludingDuplicates", { get: function () { return this.RawSearchResults.PrimaryQueryResult.RelevantResults.TotalRowsIncludingDuplicates; }, enumerable: true, configurable: true }); Object.defineProperty(SearchResults.prototype, "RawSearchResults", { get: function () { return this._raw; }, enumerable: true, configurable: true }); Object.defineProperty(SearchResults.prototype, "PrimarySearchResults", { get: function () { if (this._primary === null) { this._primary = this.formatSearchResults(this._raw.PrimaryQueryResult.RelevantResults.Table.Rows); } return this._primary; }, enumerable: true, configurable: true }); /** * Gets a page of results * * @param pageNumber Index of the page to return. Used to determine StartRow * @param pageSize Optional, items per page (default = 10) */ SearchResults.prototype.getPage = function (pageNumber, pageSize) { // if we got all the available rows we don't have another page if (this.TotalRows < this.RowCount) { return Promise.resolve(null); } // if pageSize is supplied, then we use that regardless of any previous values // otherwise get the previous RowLimit or default to 10 var rows = typeof pageSize !== "undefined" ? pageSize : this._query.hasOwnProperty("RowLimit") ? this._query.RowLimit : 10; var query = util_1.Util.extend(this._query, { RowLimit: rows, StartRow: rows * (pageNumber - 1) + 1, }); // we have reached the end if (query.StartRow > this.TotalRows) { return Promise.resolve(null); } var search = new Search(this._url, null); return search.execute(query); }; /** * Formats a search results array * * @param rawResults The array to process */ SearchResults.prototype.formatSearchResults = function (rawResults) { var results = new Array(); var tempResults = rawResults.results ? rawResults.results : rawResults; for (var _i = 0, tempResults_1 = tempResults; _i < tempResults_1.length; _i++) { var tempResult = tempResults_1[_i]; var cells = tempResult.Cells.results ? tempResult.Cells.results : tempResult.Cells; results.push(cells.reduce(function (res, cell) { Object.defineProperty(res, cell.Key, { configurable: false, enumerable: false, value: cell.Value, writable: false, }); return res; }, {})); } return results; }; return SearchResults; }()); exports.SearchResults = SearchResults; /** * defines the SortDirection enum */ var SortDirection; (function (SortDirection) { SortDirection[SortDirection["Ascending"] = 0] = "Ascending"; SortDirection[SortDirection["Descending"] = 1] = "Descending"; SortDirection[SortDirection["FQLFormula"] = 2] = "FQLFormula"; })(SortDirection = exports.SortDirection || (exports.SortDirection = {})); /** * defines the ReorderingRuleMatchType enum */ var ReorderingRuleMatchType; (function (ReorderingRuleMatchType) { ReorderingRuleMatchType[ReorderingRuleMatchType["ResultContainsKeyword"] = 0] = "ResultContainsKeyword"; ReorderingRuleMatchType[ReorderingRuleMatchType["TitleContainsKeyword"] = 1] = "TitleContainsKeyword"; ReorderingRuleMatchType[ReorderingRuleMatchType["TitleMatchesKeyword"] = 2] = "TitleMatchesKeyword"; ReorderingRuleMatchType[ReorderingRuleMatchType["UrlStartsWith"] = 3] = "UrlStartsWith"; ReorderingRuleMatchType[ReorderingRuleMatchType["UrlExactlyMatches"] = 4] = "UrlExactlyMatches"; ReorderingRuleMatchType[ReorderingRuleMatchType["ContentTypeIs"] = 5] = "ContentTypeIs"; ReorderingRuleMatchType[ReorderingRuleMatchType["FileExtensionMatches"] = 6] = "FileExtensionMatches"; ReorderingRuleMatchType[ReorderingRuleMatchType["ResultHasTag"] = 7] = "ResultHasTag"; ReorderingRuleMatchType[ReorderingRuleMatchType["ManualCondition"] = 8] = "ManualCondition"; })(ReorderingRuleMatchType = exports.ReorderingRuleMatchType || (exports.ReorderingRuleMatchType = {})); /** * Specifies the type value for the property */ var QueryPropertyValueType; (function (QueryPropertyValueType) { QueryPropertyValueType[QueryPropertyValueType["None"] = 0] = "None"; QueryPropertyValueType[QueryPropertyValueType["StringType"] = 1] = "StringType"; QueryPropertyValueType[QueryPropertyValueType["Int32TYpe"] = 2] = "Int32TYpe"; QueryPropertyValueType[QueryPropertyValueType["BooleanType"] = 3] = "BooleanType"; QueryPropertyValueType[QueryPropertyValueType["StringArrayType"] = 4] = "StringArrayType"; QueryPropertyValueType[QueryPropertyValueType["UnSupportedType"] = 5] = "UnSupportedType"; })(QueryPropertyValueType = exports.QueryPropertyValueType || (exports.QueryPropertyValueType = {})); var SearchBuiltInSourceId = (function () { function SearchBuiltInSourceId() { } return SearchBuiltInSourceId; }()); SearchBuiltInSourceId.Documents = "e7ec8cee-ded8-43c9-beb5-436b54b31e84"; SearchBuiltInSourceId.ItemsMatchingContentType = "5dc9f503-801e-4ced-8a2c-5d1237132419"; SearchBuiltInSourceId.ItemsMatchingTag = "e1327b9c-2b8c-4b23-99c9-3730cb29c3f7"; SearchBuiltInSourceId.ItemsRelatedToCurrentUser = "48fec42e-4a92-48ce-8363-c2703a40e67d"; SearchBuiltInSourceId.ItemsWithSameKeywordAsThisItem = "5c069288-1d17-454a-8ac6-9c642a065f48"; SearchBuiltInSourceId.LocalPeopleResults = "b09a7990-05ea-4af9-81ef-edfab16c4e31"; SearchBuiltInSourceId.LocalReportsAndDataResults = "203fba36-2763-4060-9931-911ac8c0583b"; SearchBuiltInSourceId.LocalSharePointResults = "8413cd39-2156-4e00-b54d-11efd9abdb89"; SearchBuiltInSourceId.LocalVideoResults = "78b793ce-7956-4669-aa3b-451fc5defebf"; SearchBuiltInSourceId.Pages = "5e34578e-4d08-4edc-8bf3-002acf3cdbcc"; SearchBuiltInSourceId.Pictures = "38403c8c-3975-41a8-826e-717f2d41568a"; SearchBuiltInSourceId.Popular = "97c71db1-58ce-4891-8b64-585bc2326c12"; SearchBuiltInSourceId.RecentlyChangedItems = "ba63bbae-fa9c-42c0-b027-9a878f16557c"; SearchBuiltInSourceId.RecommendedItems = "ec675252-14fa-4fbe-84dd-8d098ed74181"; SearchBuiltInSourceId.Wiki = "9479bf85-e257-4318-b5a8-81a180f5faa1"; exports.SearchBuiltInSourceId = SearchBuiltInSourceId; /***/ }), /* 28 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var SearchSuggest = (function (_super) { __extends(SearchSuggest, _super); function SearchSuggest(baseUrl, path) { if (path === void 0) { path = "_api/search/suggest"; } return _super.call(this, baseUrl, path) || this; } SearchSuggest.prototype.execute = function (query) { this.mapQueryToQueryString(query); return this.get().then(function (response) { return new SearchSuggestResult(response); }); }; SearchSuggest.prototype.mapQueryToQueryString = function (query) { this.query.add("querytext", "'" + query.querytext + "'"); if (query.hasOwnProperty("count")) { this.query.add("inumberofquerysuggestions", query.count.toString()); } if (query.hasOwnProperty("personalCount")) { this.query.add("inumberofresultsuggestions", query.personalCount.toString()); } if (query.hasOwnProperty("preQuery")) { this.query.add("fprequerysuggestions", query.preQuery.toString()); } if (query.hasOwnProperty("hitHighlighting")) { this.query.add("fhithighlighting", query.hitHighlighting.toString()); } if (query.hasOwnProperty("capitalize")) { this.query.add("fcapitalizefirstletters", query.capitalize.toString()); } if (query.hasOwnProperty("culture")) { this.query.add("culture", query.culture.toString()); } if (query.hasOwnProperty("stemming")) { this.query.add("enablestemming", query.stemming.toString()); } if (query.hasOwnProperty("includePeople")) { this.query.add("showpeoplenamesuggestions", query.includePeople.toString()); } if (query.hasOwnProperty("queryRules")) { this.query.add("enablequeryrules", query.queryRules.toString()); } if (query.hasOwnProperty("prefixMatch")) { this.query.add("fprefixmatchallterms", query.prefixMatch.toString()); } }; return SearchSuggest; }(queryable_1.QueryableInstance)); exports.SearchSuggest = SearchSuggest; var SearchSuggestResult = (function () { function SearchSuggestResult(json) { if (json.hasOwnProperty("suggest")) { // verbose this.PeopleNames = json.suggest.PeopleNames.results; this.PersonalResults = json.suggest.PersonalResults.results; this.Queries = json.suggest.Queries.results; } else { this.PeopleNames = json.PeopleNames; this.PersonalResults = json.PersonalResults; this.Queries = json.Queries; } } return SearchSuggestResult; }()); exports.SearchSuggestResult = SearchSuggestResult; /***/ }), /* 29 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var webs_1 = __webpack_require__(8); var usercustomactions_1 = __webpack_require__(19); var odata_1 = __webpack_require__(2); var features_1 = __webpack_require__(23); /** * Describes a site collection * */ var Site = (function (_super) { __extends(Site, _super); /** * Creates a new instance of the Site class * * @param baseUrl The url or Queryable which forms the parent of this site collection */ function Site(baseUrl, path) { if (path === void 0) { path = "_api/site"; } return _super.call(this, baseUrl, path) || this; } Object.defineProperty(Site.prototype, "rootWeb", { /** * Gets the root web of the site collection * */ get: function () { return new webs_1.Web(this, "rootweb"); }, enumerable: true, configurable: true }); Object.defineProperty(Site.prototype, "features", { /** * Gets the active features for this site collection * */ get: function () { return new features_1.Features(this); }, enumerable: true, configurable: true }); Object.defineProperty(Site.prototype, "userCustomActions", { /** * Gets all custom actions for this site collection * */ get: function () { return new usercustomactions_1.UserCustomActions(this); }, enumerable: true, configurable: true }); /** * Gets the context information for this site collection */ Site.prototype.getContextInfo = function () { var q = new Site(this.parentUrl, "_api/contextinfo"); return q.post().then(function (data) { if (data.hasOwnProperty("GetContextWebInformation")) { var info = data.GetContextWebInformation; info.SupportedSchemaVersions = info.SupportedSchemaVersions.results; return info; } else { return data; } }); }; /** * Gets the document libraries on a site. Static method. (SharePoint Online only) * * @param absoluteWebUrl The absolute url of the web whose document libraries should be returned */ Site.prototype.getDocumentLibraries = function (absoluteWebUrl) { var q = new queryable_1.Queryable("", "_api/sp.web.getdocumentlibraries(@v)"); q.query.add("@v", "'" + absoluteWebUrl + "'"); return q.get().then(function (data) { if (data.hasOwnProperty("GetDocumentLibraries")) { return data.GetDocumentLibraries; } else { return data; } }); }; /** * Gets the site url from a page url * * @param absolutePageUrl The absolute url of the page */ Site.prototype.getWebUrlFromPageUrl = function (absolutePageUrl) { var q = new queryable_1.Queryable("", "_api/sp.web.getweburlfrompageurl(@v)"); q.query.add("@v", "'" + absolutePageUrl + "'"); return q.get().then(function (data) { if (data.hasOwnProperty("GetWebUrlFromPageUrl")) { return data.GetWebUrlFromPageUrl; } else { return data; } }); }; /** * Creates a new batch for requests within the context of this site collection * */ Site.prototype.createBatch = function () { return new odata_1.ODataBatch(this.parentUrl); }; /** * Opens a web by id (using POST) * * @param webId The GUID id of the web to open */ Site.prototype.openWebById = function (webId) { return this.clone(Site, "openWebById('" + webId + "')", true).post().then(function (d) { return { data: d, web: webs_1.Web.fromUrl(odata_1.extractOdataId(d)), }; }); }; return Site; }(queryable_1.QueryableInstance)); exports.Site = Site; /***/ }), /* 30 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var sitegroups_1 = __webpack_require__(18); var util_1 = __webpack_require__(0); /** * Describes a collection of all site collection users * */ var SiteUsers = (function (_super) { __extends(SiteUsers, _super); /** * Creates a new instance of the SiteUsers class * * @param baseUrl The url or Queryable which forms the parent of this user collection */ function SiteUsers(baseUrl, path) { if (path === void 0) { path = "siteusers"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a user from the collection by email * * @param email The email address of the user to retrieve */ SiteUsers.prototype.getByEmail = function (email) { return new SiteUser(this, "getByEmail('" + email + "')"); }; /** * Gets a user from the collection by id * * @param id The id of the user to retrieve */ SiteUsers.prototype.getById = function (id) { return new SiteUser(this, "getById(" + id + ")"); }; /** * Gets a user from the collection by login name * * @param loginName The login name of the user to retrieve */ SiteUsers.prototype.getByLoginName = function (loginName) { var su = new SiteUser(this); su.concat("(@v)"); su.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return su; }; /** * Removes a user from the collection by id * * @param id The id of the user to remove */ SiteUsers.prototype.removeById = function (id) { return this.clone(SiteUsers, "removeById(" + id + ")", true).post(); }; /** * Removes a user from the collection by login name * * @param loginName The login name of the user to remove */ SiteUsers.prototype.removeByLoginName = function (loginName) { var o = this.clone(SiteUsers, "removeByLoginName(@v)", true); o.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return o.post(); }; /** * Adds a user to a group * * @param loginName The login name of the user to add to the group * */ SiteUsers.prototype.add = function (loginName) { var _this = this; return this.clone(SiteUsers, null, true).post({ body: JSON.stringify({ "__metadata": { "type": "SP.User" }, LoginName: loginName }), }).then(function () { return _this.getByLoginName(loginName); }); }; return SiteUsers; }(queryable_1.QueryableCollection)); exports.SiteUsers = SiteUsers; /** * Describes a single user * */ var SiteUser = (function (_super) { __extends(SiteUser, _super); function SiteUser() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(SiteUser.prototype, "groups", { /** * Gets the groups for this user * */ get: function () { return new sitegroups_1.SiteGroups(this, "groups"); }, enumerable: true, configurable: true }); /** * Updates this user instance with the supplied properties * * @param properties A plain object of property names and values to update for the user */ SiteUser.prototype.update = function (properties) { var _this = this; var postBody = util_1.Util.extend({ "__metadata": { "type": "SP.User" } }, properties); return this.post({ body: JSON.stringify(postBody), headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { return { data: data, user: _this, }; }); }; /** * Delete this user * */ SiteUser.prototype.delete = function () { return this.post({ headers: { "X-HTTP-Method": "DELETE", }, }); }; return SiteUser; }(queryable_1.QueryableInstance)); exports.SiteUser = SiteUser; /** * Represents the current user */ var CurrentUser = (function (_super) { __extends(CurrentUser, _super); function CurrentUser(baseUrl, path) { if (path === void 0) { path = "currentuser"; } return _super.call(this, baseUrl, path) || this; } return CurrentUser; }(queryable_1.QueryableInstance)); exports.CurrentUser = CurrentUser; /***/ }), /* 31 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var util_1 = __webpack_require__(0); var files_1 = __webpack_require__(7); var odata_1 = __webpack_require__(2); /** * Allows for calling of the static SP.Utilities.Utility methods by supplying the method name */ var UtilityMethod = (function (_super) { __extends(UtilityMethod, _super); /** * Creates a new instance of the Utility method class * * @param baseUrl The parent url provider * @param methodName The static method name to call on the utility class */ function UtilityMethod(baseUrl, methodName) { return _super.call(this, UtilityMethod.getBaseUrl(baseUrl), "_api/SP.Utilities.Utility." + methodName) || this; } UtilityMethod.getBaseUrl = function (candidate) { if (typeof candidate === "string") { return candidate; } var c = candidate; var url = c.toUrl(); var index = url.indexOf("_api/"); if (index < 0) { return url; } return url.substr(0, index); }; UtilityMethod.prototype.excute = function (props) { return this.postAs({ body: JSON.stringify(props), }); }; /** * Clones this queryable into a new queryable instance of T * @param factory Constructor used to create the new instance * @param additionalPath Any additional path to include in the clone * @param includeBatch If true this instance's batch will be added to the cloned instance */ UtilityMethod.prototype.create = function (methodName, includeBatch) { var clone = new UtilityMethod(this.parentUrl, methodName); var target = this.query.get("@target"); if (target !== null) { clone.query.add("@target", target); } if (includeBatch && this.hasBatch) { clone = clone.inBatch(this.batch); } return clone; }; /** * Sends an email based on the supplied properties * * @param props The properties of the email to send */ UtilityMethod.prototype.sendEmail = function (props) { var params = { properties: { Body: props.Body, From: props.From, Subject: props.Subject, "__metadata": { "type": "SP.Utilities.EmailProperties" }, }, }; if (props.To && props.To.length > 0) { params.properties = util_1.Util.extend(params.properties, { To: { results: props.To }, }); } if (props.CC && props.CC.length > 0) { params.properties = util_1.Util.extend(params.properties, { CC: { results: props.CC }, }); } if (props.BCC && props.BCC.length > 0) { params.properties = util_1.Util.extend(params.properties, { BCC: { results: props.BCC }, }); } if (props.AdditionalHeaders) { params.properties = util_1.Util.extend(params.properties, { AdditionalHeaders: props.AdditionalHeaders, }); } return this.create("SendEmail", true).excute(params); }; UtilityMethod.prototype.getCurrentUserEmailAddresses = function () { return this.create("GetCurrentUserEmailAddresses", true).excute({}); }; UtilityMethod.prototype.resolvePrincipal = function (input, scopes, sources, inputIsEmailOnly, addToUserInfoList, matchUserInfoList) { if (matchUserInfoList === void 0) { matchUserInfoList = false; } var params = { addToUserInfoList: addToUserInfoList, input: input, inputIsEmailOnly: inputIsEmailOnly, matchUserInfoList: matchUserInfoList, scopes: scopes, sources: sources, }; return this.create("ResolvePrincipalInCurrentContext", true).excute(params); }; UtilityMethod.prototype.searchPrincipals = function (input, scopes, sources, groupName, maxCount) { var params = { groupName: groupName, input: input, maxCount: maxCount, scopes: scopes, sources: sources, }; return this.create("SearchPrincipalsUsingContextWeb", true).excute(params); }; UtilityMethod.prototype.createEmailBodyForInvitation = function (pageAddress) { var params = { pageAddress: pageAddress, }; return this.create("CreateEmailBodyForInvitation", true).excute(params); }; UtilityMethod.prototype.expandGroupsToPrincipals = function (inputs, maxCount) { if (maxCount === void 0) { maxCount = 30; } var params = { inputs: inputs, maxCount: maxCount, }; return this.create("ExpandGroupsToPrincipals", true).excute(params); }; UtilityMethod.prototype.createWikiPage = function (info) { return this.create("CreateWikiPageInContextWeb", true).excute({ parameters: info, }).then(function (r) { return { data: r, file: new files_1.File(odata_1.extractOdataId(r)), }; }); }; return UtilityMethod; }(queryable_1.Queryable)); exports.UtilityMethod = UtilityMethod; /***/ }), /* 32 */ /***/ (function(module, exports) { var g; // This works in non-strict mode g = (function() { return this; })(); try { // This works if eval is allowed (see CSP) g = g || Function("return this")() || (1,eval)("this"); } catch(e) { // This works if the window reference is available if(typeof window === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /* 33 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var collections_1 = __webpack_require__(6); /** * Class used to manage the current application settings * */ var Settings = (function () { /** * Creates a new instance of the settings class * * @constructor */ function Settings() { this._settings = new collections_1.Dictionary(); } /** * Adds a new single setting, or overwrites a previous setting with the same key * * @param {string} key The key used to store this setting * @param {string} value The setting value to store */ Settings.prototype.add = function (key, value) { this._settings.add(key, value); }; /** * Adds a JSON value to the collection as a string, you must use getJSON to rehydrate the object when read * * @param {string} key The key used to store this setting * @param {any} value The setting value to store */ Settings.prototype.addJSON = function (key, value) { this._settings.add(key, JSON.stringify(value)); }; /** * Applies the supplied hash to the setting collection overwriting any existing value, or created new values * * @param {TypedHash<any>} hash The set of values to add */ Settings.prototype.apply = function (hash) { var _this = this; return new Promise(function (resolve, reject) { try { _this._settings.merge(hash); resolve(); } catch (e) { reject(e); } }); }; /** * Loads configuration settings into the collection from the supplied provider and returns a Promise * * @param {IConfigurationProvider} provider The provider from which we will load the settings */ Settings.prototype.load = function (provider) { var _this = this; return new Promise(function (resolve, reject) { provider.getConfiguration().then(function (value) { _this._settings.merge(value); resolve(); }).catch(function (reason) { reject(reason); }); }); }; /** * Gets a value from the configuration * * @param {string} key The key whose value we want to return. Returns null if the key does not exist * @return {string} string value from the configuration */ Settings.prototype.get = function (key) { return this._settings.get(key); }; /** * Gets a JSON value, rehydrating the stored string to the original object * * @param {string} key The key whose value we want to return. Returns null if the key does not exist * @return {any} object from the configuration */ Settings.prototype.getJSON = function (key) { var o = this.get(key); if (typeof o === "undefined" || o === null) { return o; } return JSON.parse(o); }; return Settings; }()); exports.Settings = Settings; /***/ }), /* 34 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var search_1 = __webpack_require__(27); var searchsuggest_1 = __webpack_require__(28); var site_1 = __webpack_require__(29); var webs_1 = __webpack_require__(8); var util_1 = __webpack_require__(0); var userprofiles_1 = __webpack_require__(48); var exceptions_1 = __webpack_require__(3); var utilities_1 = __webpack_require__(31); /** * Root of the SharePoint REST module */ var SPRest = (function () { function SPRest() { } /** * Executes a search against this web context * * @param query The SearchQuery definition */ SPRest.prototype.searchSuggest = function (query) { var finalQuery; if (typeof query === "string") { finalQuery = { querytext: query }; } else { finalQuery = query; } return new searchsuggest_1.SearchSuggest("").execute(finalQuery); }; /** * Executes a search against this web context * * @param query The SearchQuery definition */ SPRest.prototype.search = function (query) { var finalQuery; if (typeof query === "string") { finalQuery = { Querytext: query }; } else if (query instanceof search_1.SearchQueryBuilder) { finalQuery = query.toSearchQuery(); } else { finalQuery = query; } return new search_1.Search("").execute(finalQuery); }; Object.defineProperty(SPRest.prototype, "site", { /** * Begins a site collection scoped REST request * */ get: function () { return new site_1.Site(""); }, enumerable: true, configurable: true }); Object.defineProperty(SPRest.prototype, "web", { /** * Begins a web scoped REST request * */ get: function () { return new webs_1.Web(""); }, enumerable: true, configurable: true }); Object.defineProperty(SPRest.prototype, "profiles", { /** * Access to user profile methods * */ get: function () { return new userprofiles_1.UserProfileQuery(""); }, enumerable: true, configurable: true }); /** * Creates a new batch object for use with the Queryable.addToBatch method * */ SPRest.prototype.createBatch = function () { return this.web.createBatch(); }; Object.defineProperty(SPRest.prototype, "utility", { /** * Static utilities methods from SP.Utilities.Utility */ get: function () { return new utilities_1.UtilityMethod("", ""); }, enumerable: true, configurable: true }); /** * Begins a cross-domain, host site scoped REST request, for use in add-in webs * * @param addInWebUrl The absolute url of the add-in web * @param hostWebUrl The absolute url of the host web */ SPRest.prototype.crossDomainSite = function (addInWebUrl, hostWebUrl) { return this._cdImpl(site_1.Site, addInWebUrl, hostWebUrl, "site"); }; /** * Begins a cross-domain, host web scoped REST request, for use in add-in webs * * @param addInWebUrl The absolute url of the add-in web * @param hostWebUrl The absolute url of the host web */ SPRest.prototype.crossDomainWeb = function (addInWebUrl, hostWebUrl) { return this._cdImpl(webs_1.Web, addInWebUrl, hostWebUrl, "web"); }; /** * Implements the creation of cross domain REST urls * * @param factory The constructor of the object to create Site | Web * @param addInWebUrl The absolute url of the add-in web * @param hostWebUrl The absolute url of the host web * @param urlPart String part to append to the url "site" | "web" */ SPRest.prototype._cdImpl = function (factory, addInWebUrl, hostWebUrl, urlPart) { if (!util_1.Util.isUrlAbsolute(addInWebUrl)) { throw new exceptions_1.UrlException("The addInWebUrl parameter must be an absolute url."); } if (!util_1.Util.isUrlAbsolute(hostWebUrl)) { throw new exceptions_1.UrlException("The hostWebUrl parameter must be an absolute url."); } var url = util_1.Util.combinePaths(addInWebUrl, "_api/SP.AppContextSite(@target)"); var instance = new factory(url, urlPart); instance.query.add("@target", "'" + encodeURIComponent(hostWebUrl) + "'"); return instance; }; return SPRest; }()); exports.SPRest = SPRest; /***/ }), /* 35 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(__webpack_require__(44)); var httpclient_1 = __webpack_require__(15); exports.HttpClient = httpclient_1.HttpClient; var sprequestexecutorclient_1 = __webpack_require__(40); exports.SPRequestExecutorClient = sprequestexecutorclient_1.SPRequestExecutorClient; var nodefetchclient_1 = __webpack_require__(39); exports.NodeFetchClient = nodefetchclient_1.NodeFetchClient; var fetchclient_1 = __webpack_require__(21); exports.FetchClient = fetchclient_1.FetchClient; __export(__webpack_require__(36)); var collections_1 = __webpack_require__(6); exports.Dictionary = collections_1.Dictionary; var util_1 = __webpack_require__(0); exports.Util = util_1.Util; __export(__webpack_require__(5)); __export(__webpack_require__(3)); /***/ }), /* 36 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var cachingConfigurationProvider_1 = __webpack_require__(20); exports.CachingConfigurationProvider = cachingConfigurationProvider_1.default; var spListConfigurationProvider_1 = __webpack_require__(37); exports.SPListConfigurationProvider = spListConfigurationProvider_1.default; /***/ }), /* 37 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var cachingConfigurationProvider_1 = __webpack_require__(20); /** * A configuration provider which loads configuration values from a SharePoint list * */ var SPListConfigurationProvider = (function () { /** * Creates a new SharePoint list based configuration provider * @constructor * @param {string} webUrl Url of the SharePoint site, where the configuration list is located * @param {string} listTitle Title of the SharePoint list, which contains the configuration settings (optional, default = "config") */ function SPListConfigurationProvider(sourceWeb, sourceListTitle) { if (sourceListTitle === void 0) { sourceListTitle = "config"; } this.sourceWeb = sourceWeb; this.sourceListTitle = sourceListTitle; } Object.defineProperty(SPListConfigurationProvider.prototype, "web", { /** * Gets the url of the SharePoint site, where the configuration list is located * * @return {string} Url address of the site */ get: function () { return this.sourceWeb; }, enumerable: true, configurable: true }); Object.defineProperty(SPListConfigurationProvider.prototype, "listTitle", { /** * Gets the title of the SharePoint list, which contains the configuration settings * * @return {string} List title */ get: function () { return this.sourceListTitle; }, enumerable: true, configurable: true }); /** * Loads the configuration values from the SharePoint list * * @return {Promise<TypedHash<string>>} Promise of loaded configuration values */ SPListConfigurationProvider.prototype.getConfiguration = function () { return this.web.lists.getByTitle(this.listTitle).items.select("Title", "Value") .getAs().then(function (data) { return data.reduce(function (configuration, item) { return Object.defineProperty(configuration, item.Title, { configurable: false, enumerable: false, value: item.Value, writable: false, }); }, {}); }); }; /** * Wraps the current provider in a cache enabled provider * * @return {CachingConfigurationProvider} Caching providers which wraps the current provider */ SPListConfigurationProvider.prototype.asCaching = function () { var cacheKey = "splist_" + this.web.toUrl() + "+" + this.listTitle; return new cachingConfigurationProvider_1.default(this, cacheKey); }; return SPListConfigurationProvider; }()); exports.default = SPListConfigurationProvider; /***/ }), /* 38 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var collections_1 = __webpack_require__(6); var util_1 = __webpack_require__(0); var odata_1 = __webpack_require__(2); var CachedDigest = (function () { function CachedDigest() { } return CachedDigest; }()); exports.CachedDigest = CachedDigest; // allows for the caching of digests across all HttpClient's which each have their own DigestCache wrapper. var digests = new collections_1.Dictionary(); var DigestCache = (function () { function DigestCache(_httpClient, _digests) { if (_digests === void 0) { _digests = digests; } this._httpClient = _httpClient; this._digests = _digests; } DigestCache.prototype.getDigest = function (webUrl) { var _this = this; var cachedDigest = this._digests.get(webUrl); if (cachedDigest !== null) { var now = new Date(); if (now < cachedDigest.expiration) { return Promise.resolve(cachedDigest.value); } } var url = util_1.Util.combinePaths(webUrl, "/_api/contextinfo"); return this._httpClient.fetchRaw(url, { cache: "no-cache", credentials: "same-origin", headers: { "Accept": "application/json;odata=verbose", "Content-type": "application/json;odata=verbose;charset=utf-8", }, method: "POST", }).then(function (response) { var parser = new odata_1.ODataDefaultParser(); return parser.parse(response).then(function (d) { return d.GetContextWebInformation; }); }).then(function (data) { var newCachedDigest = new CachedDigest(); newCachedDigest.value = data.FormDigestValue; var seconds = data.FormDigestTimeoutSeconds; var expiration = new Date(); expiration.setTime(expiration.getTime() + 1000 * seconds); newCachedDigest.expiration = expiration; _this._digests.add(webUrl, newCachedDigest); return newCachedDigest.value; }); }; DigestCache.prototype.clear = function () { this._digests.clear(); }; return DigestCache; }()); exports.DigestCache = DigestCache; /***/ }), /* 39 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var exceptions_1 = __webpack_require__(3); /** * This module is substituted for the NodeFetchClient.ts during the packaging process. This helps to reduce the pnp.js file size by * not including all of the node dependencies */ var NodeFetchClient = (function () { function NodeFetchClient() { } /** * Always throws an error that NodeFetchClient is not supported for use in the browser */ NodeFetchClient.prototype.fetch = function () { throw new exceptions_1.NodeFetchClientUnsupportedException(); }; return NodeFetchClient; }()); exports.NodeFetchClient = NodeFetchClient; /***/ }), /* 40 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = __webpack_require__(0); var exceptions_1 = __webpack_require__(3); /** * Makes requests using the SP.RequestExecutor library. */ var SPRequestExecutorClient = (function () { function SPRequestExecutorClient() { /** * Converts a SharePoint REST API response to a fetch API response. */ this.convertToResponse = function (spResponse) { var responseHeaders = new Headers(); for (var h in spResponse.headers) { if (spResponse.headers[h]) { responseHeaders.append(h, spResponse.headers[h]); } } // issue #256, Cannot have an empty string body when creating a Response with status 204 var body = spResponse.statusCode === 204 ? null : spResponse.body; return new Response(body, { headers: responseHeaders, status: spResponse.statusCode, statusText: spResponse.statusText, }); }; } /** * Fetches a URL using the SP.RequestExecutor library. */ SPRequestExecutorClient.prototype.fetch = function (url, options) { var _this = this; if (typeof SP === "undefined" || typeof SP.RequestExecutor === "undefined") { throw new exceptions_1.SPRequestExecutorUndefinedException(); } var addinWebUrl = url.substring(0, url.indexOf("/_api")), executor = new SP.RequestExecutor(addinWebUrl); var headers = {}, iterator, temp; if (options.headers && options.headers instanceof Headers) { iterator = options.headers.entries(); temp = iterator.next(); while (!temp.done) { headers[temp.value[0]] = temp.value[1]; temp = iterator.next(); } } else { headers = options.headers; } return new Promise(function (resolve, reject) { var requestOptions = { error: function (error) { reject(_this.convertToResponse(error)); }, headers: headers, method: options.method, success: function (response) { resolve(_this.convertToResponse(response)); }, url: url, }; if (options.body) { requestOptions = util_1.Util.extend(requestOptions, { body: options.body }); } else { requestOptions = util_1.Util.extend(requestOptions, { binaryStringRequestBody: true }); } executor.executeAsync(requestOptions); }); }; return SPRequestExecutorClient; }()); exports.SPRequestExecutorClient = SPRequestExecutorClient; /***/ }), /* 41 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = __webpack_require__(0); var storage_1 = __webpack_require__(14); var configuration_1 = __webpack_require__(33); var logging_1 = __webpack_require__(5); var rest_1 = __webpack_require__(34); var pnplibconfig_1 = __webpack_require__(4); /** * Root class of the Patterns and Practices namespace, provides an entry point to the library */ /** * Utility methods */ exports.util = util_1.Util; /** * Provides access to the REST interface */ exports.sp = new rest_1.SPRest(); /** * Provides access to local and session storage */ exports.storage = new storage_1.PnPClientStorage(); /** * Global configuration instance to which providers can be added */ exports.config = new configuration_1.Settings(); /** * Global logging instance to which subscribers can be registered and messages written */ exports.log = logging_1.Logger; /** * Allows for the configuration of the library */ exports.setup = pnplibconfig_1.setRuntimeConfig; /** * Expose a subset of classes from the library for public consumption */ __export(__webpack_require__(35)); // creating this class instead of directly assigning to default fixes issue #116 var Def = { /** * Global configuration instance to which providers can be added */ config: exports.config, /** * Global logging instance to which subscribers can be registered and messages written */ log: exports.log, /** * Provides access to local and session storage */ setup: exports.setup, /** * Provides access to the REST interface */ sp: exports.sp, /** * Provides access to local and session storage */ storage: exports.storage, /** * Utility methods */ util: exports.util, }; /** * Enables use of the import pnp from syntax */ exports.default = Def; /***/ }), /* 42 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var odata_1 = __webpack_require__(2); /** * Describes a collection of Item objects * */ var AttachmentFiles = (function (_super) { __extends(AttachmentFiles, _super); /** * Creates a new instance of the AttachmentFiles class * * @param baseUrl The url or Queryable which forms the parent of this attachments collection */ function AttachmentFiles(baseUrl, path) { if (path === void 0) { path = "AttachmentFiles"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a Attachment File by filename * * @param name The name of the file, including extension. */ AttachmentFiles.prototype.getByName = function (name) { var f = new AttachmentFile(this); f.concat("('" + name + "')"); return f; }; /** * Adds a new attachment to the collection. Not supported for batching. * * @param name The name of the file, including extension. * @param content The Base64 file content. */ AttachmentFiles.prototype.add = function (name, content) { var _this = this; return this.clone(AttachmentFiles, "add(FileName='" + name + "')").post({ body: content, }).then(function (response) { return { data: response, file: _this.getByName(name), }; }); }; /** * Adds mjultiple new attachment to the collection. Not supported for batching. * * @files name The collection of files to add */ AttachmentFiles.prototype.addMultiple = function (files) { var _this = this; // add the files in series so we don't get update conflicts return files.reduce(function (chain, file) { return chain.then(function () { return _this.clone(AttachmentFiles, "add(FileName='" + file.name + "')").post({ body: file.content, }); }); }, Promise.resolve()); }; return AttachmentFiles; }(queryable_1.QueryableCollection)); exports.AttachmentFiles = AttachmentFiles; /** * Describes a single attachment file instance * */ var AttachmentFile = (function (_super) { __extends(AttachmentFile, _super); function AttachmentFile() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets the contents of the file as text * */ AttachmentFile.prototype.getText = function () { return this.clone(AttachmentFile, "$value").get(new odata_1.TextFileParser()); }; /** * Gets the contents of the file as a blob, does not work in Node.js * */ AttachmentFile.prototype.getBlob = function () { return this.clone(AttachmentFile, "$value").get(new odata_1.BlobFileParser()); }; /** * Gets the contents of a file as an ArrayBuffer, works in Node.js */ AttachmentFile.prototype.getBuffer = function () { return this.clone(AttachmentFile, "$value").get(new odata_1.BufferFileParser()); }; /** * Gets the contents of a file as an ArrayBuffer, works in Node.js */ AttachmentFile.prototype.getJSON = function () { return this.clone(AttachmentFile, "$value").get(new odata_1.JSONFileParser()); }; /** * Sets the content of a file. Not supported for batching * * @param content The value to set for the file contents */ AttachmentFile.prototype.setContent = function (content) { var _this = this; return this.clone(AttachmentFile, "$value").post({ body: content, headers: { "X-HTTP-Method": "PUT", }, }).then(function (_) { return new AttachmentFile(_this); }); }; /** * Delete this attachment file * * @param eTag Value used in the IF-Match header, by default "*" */ AttachmentFile.prototype.delete = function (eTag) { if (eTag === void 0) { eTag = "*"; } return this.post({ headers: { "IF-Match": eTag, "X-HTTP-Method": "DELETE", }, }); }; return AttachmentFile; }(queryable_1.QueryableInstance)); exports.AttachmentFile = AttachmentFile; /***/ }), /* 43 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); /** * Describes a collection of Field objects * */ var Forms = (function (_super) { __extends(Forms, _super); /** * Creates a new instance of the Fields class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Forms(baseUrl, path) { if (path === void 0) { path = "forms"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a form by id * * @param id The guid id of the item to retrieve */ Forms.prototype.getById = function (id) { var i = new Form(this); i.concat("('" + id + "')"); return i; }; return Forms; }(queryable_1.QueryableCollection)); exports.Forms = Forms; /** * Describes a single of Form instance * */ var Form = (function (_super) { __extends(Form, _super); function Form() { return _super !== null && _super.apply(this, arguments) || this; } return Form; }(queryable_1.QueryableInstance)); exports.Form = Form; /***/ }), /* 44 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(__webpack_require__(22)); var files_1 = __webpack_require__(7); exports.CheckinType = files_1.CheckinType; exports.WebPartsPersonalizationScope = files_1.WebPartsPersonalizationScope; exports.MoveOperations = files_1.MoveOperations; exports.TemplateFileType = files_1.TemplateFileType; var folders_1 = __webpack_require__(9); exports.Folder = folders_1.Folder; exports.Folders = folders_1.Folders; var items_1 = __webpack_require__(10); exports.Item = items_1.Item; exports.Items = items_1.Items; exports.PagedItemCollection = items_1.PagedItemCollection; var navigation_1 = __webpack_require__(25); exports.NavigationNodes = navigation_1.NavigationNodes; exports.NavigationNode = navigation_1.NavigationNode; var lists_1 = __webpack_require__(11); exports.List = lists_1.List; exports.Lists = lists_1.Lists; var odata_1 = __webpack_require__(2); exports.extractOdataId = odata_1.extractOdataId; exports.ODataParserBase = odata_1.ODataParserBase; exports.ODataDefaultParser = odata_1.ODataDefaultParser; exports.ODataRaw = odata_1.ODataRaw; exports.ODataValue = odata_1.ODataValue; exports.ODataEntity = odata_1.ODataEntity; exports.ODataEntityArray = odata_1.ODataEntityArray; exports.TextFileParser = odata_1.TextFileParser; exports.BlobFileParser = odata_1.BlobFileParser; exports.BufferFileParser = odata_1.BufferFileParser; exports.JSONFileParser = odata_1.JSONFileParser; var queryable_1 = __webpack_require__(1); exports.Queryable = queryable_1.Queryable; exports.QueryableInstance = queryable_1.QueryableInstance; exports.QueryableCollection = queryable_1.QueryableCollection; var roles_1 = __webpack_require__(17); exports.RoleDefinitionBindings = roles_1.RoleDefinitionBindings; var search_1 = __webpack_require__(27); exports.Search = search_1.Search; exports.SearchQueryBuilder = search_1.SearchQueryBuilder; exports.SearchResults = search_1.SearchResults; exports.SortDirection = search_1.SortDirection; exports.ReorderingRuleMatchType = search_1.ReorderingRuleMatchType; exports.QueryPropertyValueType = search_1.QueryPropertyValueType; exports.SearchBuiltInSourceId = search_1.SearchBuiltInSourceId; var searchsuggest_1 = __webpack_require__(28); exports.SearchSuggest = searchsuggest_1.SearchSuggest; exports.SearchSuggestResult = searchsuggest_1.SearchSuggestResult; var site_1 = __webpack_require__(29); exports.Site = site_1.Site; __export(__webpack_require__(13)); var utilities_1 = __webpack_require__(31); exports.UtilityMethod = utilities_1.UtilityMethod; var webs_1 = __webpack_require__(8); exports.Web = webs_1.Web; /***/ }), /* 45 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); var caching_1 = __webpack_require__(22); var httpclient_1 = __webpack_require__(15); var logging_1 = __webpack_require__(5); var util_1 = __webpack_require__(0); /** * Resolves the context's result value * * @param context The current context */ function returnResult(context) { logging_1.Logger.log({ data: context.result, level: logging_1.LogLevel.Verbose, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Returning result, see data property for value.", }); return Promise.resolve(context.result); } /** * Sets the result on the context */ function setResult(context, value) { return new Promise(function (resolve) { context.result = value; context.hasResult = true; resolve(context); }); } exports.setResult = setResult; /** * Invokes the next method in the provided context's pipeline * * @param c The current request context */ function next(c) { if (c.pipeline.length < 1) { return Promise.resolve(c); } return c.pipeline.shift()(c); } /** * Executes the current request context's pipeline * * @param context Current context */ function pipe(context) { return next(context) .then(function (ctx) { return returnResult(ctx); }) .catch(function (e) { logging_1.Logger.log({ data: e, level: logging_1.LogLevel.Error, message: "Error in request pipeline: " + e.message, }); throw e; }); } exports.pipe = pipe; /** * decorator factory applied to methods in the pipeline to control behavior */ function requestPipelineMethod(alwaysRun) { if (alwaysRun === void 0) { alwaysRun = false; } return function (target, propertyKey, descriptor) { var method = descriptor.value; descriptor.value = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } // if we have a result already in the pipeline, pass it along and don't call the tagged method if (!alwaysRun && args.length > 0 && args[0].hasOwnProperty("hasResult") && args[0].hasResult) { logging_1.Logger.write("[" + args[0].requestId + "] (" + (new Date()).getTime() + ") Skipping request pipeline method " + propertyKey + ", existing result in pipeline.", logging_1.LogLevel.Verbose); return Promise.resolve(args[0]); } // apply the tagged method logging_1.Logger.write("[" + args[0].requestId + "] (" + (new Date()).getTime() + ") Calling request pipeline method " + propertyKey + ".", logging_1.LogLevel.Verbose); // then chain the next method in the context's pipeline - allows for dynamic pipeline return method.apply(target, args).then(function (ctx) { return next(ctx); }); }; }; } exports.requestPipelineMethod = requestPipelineMethod; /** * Contains the methods used within the request pipeline */ var PipelineMethods = (function () { function PipelineMethods() { } /** * Logs the start of the request */ PipelineMethods.logStart = function (context) { return new Promise(function (resolve) { logging_1.Logger.log({ data: logging_1.Logger.activeLogLevel === logging_1.LogLevel.Info ? {} : context, level: logging_1.LogLevel.Info, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Beginning " + context.verb + " request (" + context.requestAbsoluteUrl + ")", }); resolve(context); }); }; /** * Handles caching of the request */ PipelineMethods.caching = function (context) { return new Promise(function (resolve) { // handle caching, if applicable if (context.verb === "GET" && context.isCached) { logging_1.Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Caching is enabled for request, checking cache...", logging_1.LogLevel.Info); var cacheOptions = new caching_1.CachingOptions(context.requestAbsoluteUrl.toLowerCase()); if (typeof context.cachingOptions !== "undefined") { cacheOptions = util_1.Util.extend(cacheOptions, context.cachingOptions); } // we may not have a valid store if (cacheOptions.store !== null) { // check if we have the data in cache and if so resolve the promise and return var data = cacheOptions.store.get(cacheOptions.key); if (data !== null) { // ensure we clear any help batch dependency we are resolving from the cache logging_1.Logger.log({ data: logging_1.Logger.activeLogLevel === logging_1.LogLevel.Info ? {} : data, level: logging_1.LogLevel.Info, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Value returned from cache.", }); context.batchDependency(); return setResult(context, data).then(function (ctx) { return resolve(ctx); }); } } logging_1.Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Value not found in cache.", logging_1.LogLevel.Info); // if we don't then wrap the supplied parser in the caching parser wrapper // and send things on their way context.parser = new caching_1.CachingParserWrapper(context.parser, cacheOptions); } return resolve(context); }); }; /** * Sends the request */ PipelineMethods.send = function (context) { return new Promise(function (resolve, reject) { // send or batch the request if (context.isBatched) { // we are in a batch, so add to batch, remove dependency, and resolve with the batch's promise var p = context.batch.add(context.requestAbsoluteUrl, context.verb, context.options, context.parser); // we release the dependency here to ensure the batch does not execute until the request is added to the batch context.batchDependency(); logging_1.Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Batching request in batch " + context.batch.batchId + ".", logging_1.LogLevel.Info); // we set the result as the promise which will be resolved by the batch's execution resolve(setResult(context, p)); } else { logging_1.Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Sending request.", logging_1.LogLevel.Info); // we are not part of a batch, so proceed as normal var client = new httpclient_1.HttpClient(); var opts = util_1.Util.extend(context.options || {}, { method: context.verb }); client.fetch(context.requestAbsoluteUrl, opts) .then(function (response) { return context.parser.parse(response); }) .then(function (result) { return setResult(context, result); }) .then(function (ctx) { return resolve(ctx); }) .catch(function (e) { return reject(e); }); } }); }; /** * Logs the end of the request */ PipelineMethods.logEnd = function (context) { return new Promise(function (resolve) { if (context.isBatched) { logging_1.Logger.log({ data: logging_1.Logger.activeLogLevel === logging_1.LogLevel.Info ? {} : context, level: logging_1.LogLevel.Info, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") " + context.verb + " request will complete in batch " + context.batch.batchId + ".", }); } else { logging_1.Logger.log({ data: logging_1.Logger.activeLogLevel === logging_1.LogLevel.Info ? {} : context, level: logging_1.LogLevel.Info, message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Completing " + context.verb + " request.", }); } resolve(context); }); }; Object.defineProperty(PipelineMethods, "default", { get: function () { return [ PipelineMethods.logStart, PipelineMethods.caching, PipelineMethods.send, PipelineMethods.logEnd, ]; }, enumerable: true, configurable: true }); return PipelineMethods; }()); __decorate([ requestPipelineMethod(true) ], PipelineMethods, "logStart", null); __decorate([ requestPipelineMethod() ], PipelineMethods, "caching", null); __decorate([ requestPipelineMethod() ], PipelineMethods, "send", null); __decorate([ requestPipelineMethod(true) ], PipelineMethods, "logEnd", null); exports.PipelineMethods = PipelineMethods; /***/ }), /* 46 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var RelatedItemManagerImpl = (function (_super) { __extends(RelatedItemManagerImpl, _super); function RelatedItemManagerImpl(baseUrl, path) { if (path === void 0) { path = "_api/SP.RelatedItemManager"; } return _super.call(this, baseUrl, path) || this; } RelatedItemManagerImpl.FromUrl = function (url) { if (url === null) { return new RelatedItemManagerImpl(""); } var index = url.indexOf("_api/"); if (index > -1) { return new RelatedItemManagerImpl(url.substr(0, index)); } return new RelatedItemManagerImpl(url); }; RelatedItemManagerImpl.prototype.getRelatedItems = function (sourceListName, sourceItemId) { var query = this.clone(RelatedItemManagerImpl, null, true); query.concat(".GetRelatedItems"); return query.post({ body: JSON.stringify({ SourceItemID: sourceItemId, SourceListName: sourceListName, }), }); }; RelatedItemManagerImpl.prototype.getPageOneRelatedItems = function (sourceListName, sourceItemId) { var query = this.clone(RelatedItemManagerImpl, null, true); query.concat(".GetPageOneRelatedItems"); return query.post({ body: JSON.stringify({ SourceItemID: sourceItemId, SourceListName: sourceListName, }), }); }; RelatedItemManagerImpl.prototype.addSingleLink = function (sourceListName, sourceItemId, sourceWebUrl, targetListName, targetItemID, targetWebUrl, tryAddReverseLink) { if (tryAddReverseLink === void 0) { tryAddReverseLink = false; } var query = this.clone(RelatedItemManagerImpl, null, true); query.concat(".AddSingleLink"); return query.post({ body: JSON.stringify({ SourceItemID: sourceItemId, SourceListName: sourceListName, SourceWebUrl: sourceWebUrl, TargetItemID: targetItemID, TargetListName: targetListName, TargetWebUrl: targetWebUrl, TryAddReverseLink: tryAddReverseLink, }), }); }; /** * Adds a related item link from an item specified by list name and item id, to an item specified by url * * @param sourceListName The source list name or list id * @param sourceItemId The source item id * @param targetItemUrl The target item url * @param tryAddReverseLink If set to true try to add the reverse link (will not return error if it fails) */ RelatedItemManagerImpl.prototype.addSingleLinkToUrl = function (sourceListName, sourceItemId, targetItemUrl, tryAddReverseLink) { if (tryAddReverseLink === void 0) { tryAddReverseLink = false; } var query = this.clone(RelatedItemManagerImpl, null, true); query.concat(".AddSingleLinkToUrl"); return query.post({ body: JSON.stringify({ SourceItemID: sourceItemId, SourceListName: sourceListName, TargetItemUrl: targetItemUrl, TryAddReverseLink: tryAddReverseLink, }), }); }; /** * Adds a related item link from an item specified by url, to an item specified by list name and item id * * @param sourceItemUrl The source item url * @param targetListName The target list name or list id * @param targetItemId The target item id * @param tryAddReverseLink If set to true try to add the reverse link (will not return error if it fails) */ RelatedItemManagerImpl.prototype.addSingleLinkFromUrl = function (sourceItemUrl, targetListName, targetItemId, tryAddReverseLink) { if (tryAddReverseLink === void 0) { tryAddReverseLink = false; } var query = this.clone(RelatedItemManagerImpl, null, true); query.concat(".AddSingleLinkFromUrl"); return query.post({ body: JSON.stringify({ SourceItemUrl: sourceItemUrl, TargetItemID: targetItemId, TargetListName: targetListName, TryAddReverseLink: tryAddReverseLink, }), }); }; RelatedItemManagerImpl.prototype.deleteSingleLink = function (sourceListName, sourceItemId, sourceWebUrl, targetListName, targetItemId, targetWebUrl, tryDeleteReverseLink) { if (tryDeleteReverseLink === void 0) { tryDeleteReverseLink = false; } var query = this.clone(RelatedItemManagerImpl, null, true); query.concat(".DeleteSingleLink"); return query.post({ body: JSON.stringify({ SourceItemID: sourceItemId, SourceListName: sourceListName, SourceWebUrl: sourceWebUrl, TargetItemID: targetItemId, TargetListName: targetListName, TargetWebUrl: targetWebUrl, TryDeleteReverseLink: tryDeleteReverseLink, }), }); }; return RelatedItemManagerImpl; }(queryable_1.Queryable)); exports.RelatedItemManagerImpl = RelatedItemManagerImpl; /***/ }), /* 47 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); /** * Describes a collection of webhook subscriptions * */ var Subscriptions = (function (_super) { __extends(Subscriptions, _super); /** * Creates a new instance of the Subscriptions class * * @param baseUrl - The url or Queryable which forms the parent of this webhook subscriptions collection */ function Subscriptions(baseUrl, path) { if (path === void 0) { path = "subscriptions"; } return _super.call(this, baseUrl, path) || this; } /** * Returns all the webhook subscriptions or the specified webhook subscription * * @param subscriptionId The id of a specific webhook subscription to retrieve, omit to retrieve all the webhook subscriptions */ Subscriptions.prototype.getById = function (subscriptionId) { var subscription = new Subscription(this); subscription.concat("('" + subscriptionId + "')"); return subscription; }; /** * Creates a new webhook subscription * * @param notificationUrl The url to receive the notifications * @param expirationDate The date and time to expire the subscription in the form YYYY-MM-ddTHH:mm:ss+00:00 (maximum of 6 months) * @param clientState A client specific string (defaults to pnp-js-core-subscription when omitted) */ Subscriptions.prototype.add = function (notificationUrl, expirationDate, clientState) { var _this = this; var postBody = JSON.stringify({ "clientState": clientState || "pnp-js-core-subscription", "expirationDateTime": expirationDate, "notificationUrl": notificationUrl, "resource": this.toUrl(), }); return this.post({ body: postBody, headers: { "Content-Type": "application/json" } }).then(function (result) { return { data: result, subscription: _this.getById(result.id) }; }); }; return Subscriptions; }(queryable_1.QueryableCollection)); exports.Subscriptions = Subscriptions; /** * Describes a single webhook subscription instance * */ var Subscription = (function (_super) { __extends(Subscription, _super); function Subscription() { return _super !== null && _super.apply(this, arguments) || this; } /** * Renews this webhook subscription * * @param expirationDate The date and time to expire the subscription in the form YYYY-MM-ddTHH:mm:ss+00:00 (maximum of 6 months) */ Subscription.prototype.update = function (expirationDate) { var _this = this; var postBody = JSON.stringify({ "expirationDateTime": expirationDate, }); return this.patch({ body: postBody, headers: { "Content-Type": "application/json" } }).then(function (data) { return { data: data, subscription: _this }; }); }; /** * Removes this webhook subscription * */ Subscription.prototype.delete = function () { return _super.prototype.delete.call(this); }; return Subscription; }(queryable_1.QueryableInstance)); exports.Subscription = Subscription; /***/ }), /* 48 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var files_1 = __webpack_require__(52); var odata_1 = __webpack_require__(2); var UserProfileQuery = (function (_super) { __extends(UserProfileQuery, _super); /** * Creates a new instance of the UserProfileQuery class * * @param baseUrl The url or Queryable which forms the parent of this user profile query */ function UserProfileQuery(baseUrl, path) { if (path === void 0) { path = "_api/sp.userprofiles.peoplemanager"; } var _this = _super.call(this, baseUrl, path) || this; _this.profileLoader = new ProfileLoader(baseUrl); return _this; } Object.defineProperty(UserProfileQuery.prototype, "editProfileLink", { /** * The url of the edit profile page for the current user */ get: function () { return this.clone(UserProfileQuery, "EditProfileLink").getAs(odata_1.ODataValue()); }, enumerable: true, configurable: true }); Object.defineProperty(UserProfileQuery.prototype, "isMyPeopleListPublic", { /** * A boolean value that indicates whether the current user's "People I'm Following" list is public */ get: function () { return this.clone(UserProfileQuery, "IsMyPeopleListPublic").getAs(odata_1.ODataValue()); }, enumerable: true, configurable: true }); /** * A boolean value that indicates whether the current user is being followed by the specified user * * @param loginName The account name of the user */ UserProfileQuery.prototype.amIFollowedBy = function (loginName) { var q = this.clone(UserProfileQuery, "amifollowedby(@v)", true); q.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return q.get(); }; /** * A boolean value that indicates whether the current user is following the specified user * * @param loginName The account name of the user */ UserProfileQuery.prototype.amIFollowing = function (loginName) { var q = this.clone(UserProfileQuery, "amifollowing(@v)", true); q.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return q.get(); }; /** * Gets tags that the current user is following * * @param maxCount The maximum number of tags to retrieve (default is 20) */ UserProfileQuery.prototype.getFollowedTags = function (maxCount) { if (maxCount === void 0) { maxCount = 20; } return this.clone(UserProfileQuery, "getfollowedtags(" + maxCount + ")", true).get(); }; /** * Gets the people who are following the specified user * * @param loginName The account name of the user */ UserProfileQuery.prototype.getFollowersFor = function (loginName) { var q = this.clone(UserProfileQuery, "getfollowersfor(@v)", true); q.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return q.get(); }; Object.defineProperty(UserProfileQuery.prototype, "myFollowers", { /** * Gets the people who are following the current user * */ get: function () { return new queryable_1.QueryableCollection(this, "getmyfollowers"); }, enumerable: true, configurable: true }); Object.defineProperty(UserProfileQuery.prototype, "myProperties", { /** * Gets user properties for the current user * */ get: function () { return new UserProfileQuery(this, "getmyproperties"); }, enumerable: true, configurable: true }); /** * Gets the people who the specified user is following * * @param loginName The account name of the user. */ UserProfileQuery.prototype.getPeopleFollowedBy = function (loginName) { var q = this.clone(UserProfileQuery, "getpeoplefollowedby(@v)", true); q.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return q.get(); }; /** * Gets user properties for the specified user. * * @param loginName The account name of the user. */ UserProfileQuery.prototype.getPropertiesFor = function (loginName) { var q = this.clone(UserProfileQuery, "getpropertiesfor(@v)", true); q.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return q.get(); }; Object.defineProperty(UserProfileQuery.prototype, "trendingTags", { /** * Gets the 20 most popular hash tags over the past week, sorted so that the most popular tag appears first * */ get: function () { var q = this.clone(UserProfileQuery, null, true); q.concat(".gettrendingtags"); return q.get(); }, enumerable: true, configurable: true }); /** * Gets the specified user profile property for the specified user * * @param loginName The account name of the user * @param propertyName The case-sensitive name of the property to get */ UserProfileQuery.prototype.getUserProfilePropertyFor = function (loginName, propertyName) { var q = this.clone(UserProfileQuery, "getuserprofilepropertyfor(accountname=@v, propertyname='" + propertyName + "')", true); q.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return q.get(); }; /** * Removes the specified user from the user's list of suggested people to follow * * @param loginName The account name of the user */ UserProfileQuery.prototype.hideSuggestion = function (loginName) { var q = this.clone(UserProfileQuery, "hidesuggestion(@v)", true); q.query.add("@v", "'" + encodeURIComponent(loginName) + "'"); return q.post(); }; /** * A boolean values that indicates whether the first user is following the second user * * @param follower The account name of the user who might be following the followee * @param followee The account name of the user who might be followed by the follower */ UserProfileQuery.prototype.isFollowing = function (follower, followee) { var q = this.clone(UserProfileQuery, null, true); q.concat(".isfollowing(possiblefolloweraccountname=@v, possiblefolloweeaccountname=@y)"); q.query.add("@v", "'" + encodeURIComponent(follower) + "'"); q.query.add("@y", "'" + encodeURIComponent(followee) + "'"); return q.get(); }; /** * Uploads and sets the user profile picture (Users can upload a picture to their own profile only). Not supported for batching. * * @param profilePicSource Blob data representing the user's picture in BMP, JPEG, or PNG format of up to 4.76MB */ UserProfileQuery.prototype.setMyProfilePic = function (profilePicSource) { var _this = this; return new Promise(function (resolve, reject) { files_1.readBlobAsArrayBuffer(profilePicSource).then(function (buffer) { var request = new UserProfileQuery(_this, "setmyprofilepicture"); request.post({ body: String.fromCharCode.apply(null, new Uint16Array(buffer)), }).then(function (_) { return resolve(); }); }).catch(function (e) { return reject(e); }); }); }; /** * Provisions one or more users' personal sites. (My Site administrator on SharePoint Online only) * * @param emails The email addresses of the users to provision sites for */ UserProfileQuery.prototype.createPersonalSiteEnqueueBulk = function () { var emails = []; for (var _i = 0; _i < arguments.length; _i++) { emails[_i] = arguments[_i]; } return this.profileLoader.createPersonalSiteEnqueueBulk(emails); }; Object.defineProperty(UserProfileQuery.prototype, "ownerUserProfile", { /** * Gets the user profile of the site owner * */ get: function () { return this.profileLoader.ownerUserProfile; }, enumerable: true, configurable: true }); Object.defineProperty(UserProfileQuery.prototype, "userProfile", { /** * Gets the user profile for the current user */ get: function () { return this.profileLoader.userProfile; }, enumerable: true, configurable: true }); /** * Enqueues creating a personal site for this user, which can be used to share documents, web pages, and other files * * @param interactiveRequest true if interactively (web) initiated request, or false (default) if non-interactively (client) initiated request */ UserProfileQuery.prototype.createPersonalSite = function (interactiveRequest) { if (interactiveRequest === void 0) { interactiveRequest = false; } return this.profileLoader.createPersonalSite(interactiveRequest); }; /** * Sets the privacy settings for this profile * * @param share true to make all social data public; false to make all social data private */ UserProfileQuery.prototype.shareAllSocialData = function (share) { return this.profileLoader.shareAllSocialData(share); }; return UserProfileQuery; }(queryable_1.QueryableInstance)); exports.UserProfileQuery = UserProfileQuery; var ProfileLoader = (function (_super) { __extends(ProfileLoader, _super); /** * Creates a new instance of the ProfileLoader class * * @param baseUrl The url or Queryable which forms the parent of this profile loader */ function ProfileLoader(baseUrl, path) { if (path === void 0) { path = "_api/sp.userprofiles.profileloader.getprofileloader"; } return _super.call(this, baseUrl, path) || this; } /** * Provisions one or more users' personal sites. (My Site administrator on SharePoint Online only) * * @param emails The email addresses of the users to provision sites for */ ProfileLoader.prototype.createPersonalSiteEnqueueBulk = function (emails) { return this.clone(ProfileLoader, "createpersonalsiteenqueuebulk").post({ body: JSON.stringify({ "emailIDs": emails }), }); }; Object.defineProperty(ProfileLoader.prototype, "ownerUserProfile", { /** * Gets the user profile of the site owner. * */ get: function () { var q = this.getParent(ProfileLoader, this.parentUrl, "_api/sp.userprofiles.profileloader.getowneruserprofile"); if (this.hasBatch) { q = q.inBatch(this.batch); } return q.postAs(); }, enumerable: true, configurable: true }); Object.defineProperty(ProfileLoader.prototype, "userProfile", { /** * Gets the user profile of the current user. * */ get: function () { return this.clone(ProfileLoader, "getuserprofile", true).postAs(); }, enumerable: true, configurable: true }); /** * Enqueues creating a personal site for this user, which can be used to share documents, web pages, and other files. * * @param interactiveRequest true if interactively (web) initiated request, or false (default) if non-interactively (client) initiated request */ ProfileLoader.prototype.createPersonalSite = function (interactiveRequest) { if (interactiveRequest === void 0) { interactiveRequest = false; } return this.clone(ProfileLoader, "getuserprofile/createpersonalsiteenque(" + interactiveRequest + ")", true).post(); }; /** * Sets the privacy settings for this profile * * @param share true to make all social data public; false to make all social data private. */ ProfileLoader.prototype.shareAllSocialData = function (share) { return this.clone(ProfileLoader, "getuserprofile/shareallsocialdata(" + share + ")", true).post(); }; return ProfileLoader; }(queryable_1.Queryable)); /***/ }), /* 49 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var util_1 = __webpack_require__(0); /** * Describes the views available in the current context * */ var Views = (function (_super) { __extends(Views, _super); /** * Creates a new instance of the Views class * * @param baseUrl The url or Queryable which forms the parent of this fields collection */ function Views(baseUrl, path) { if (path === void 0) { path = "views"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a view by guid id * * @param id The GUID id of the view */ Views.prototype.getById = function (id) { var v = new View(this); v.concat("('" + id + "')"); return v; }; /** * Gets a view by title (case-sensitive) * * @param title The case-sensitive title of the view */ Views.prototype.getByTitle = function (title) { return new View(this, "getByTitle('" + title + "')"); }; /** * Adds a new view to the collection * * @param title The new views's title * @param personalView True if this is a personal view, otherwise false, default = false * @param additionalSettings Will be passed as part of the view creation body */ /*tslint:disable max-line-length */ Views.prototype.add = function (title, personalView, additionalSettings) { var _this = this; if (personalView === void 0) { personalView = false; } if (additionalSettings === void 0) { additionalSettings = {}; } var postBody = JSON.stringify(util_1.Util.extend({ "PersonalView": personalView, "Title": title, "__metadata": { "type": "SP.View" }, }, additionalSettings)); return this.clone(Views, null, true).postAs({ body: postBody }).then(function (data) { return { data: data, view: _this.getById(data.Id), }; }); }; return Views; }(queryable_1.QueryableCollection)); exports.Views = Views; /** * Describes a single View instance * */ var View = (function (_super) { __extends(View, _super); function View() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(View.prototype, "fields", { get: function () { return new ViewFields(this); }, enumerable: true, configurable: true }); /** * Updates this view intance with the supplied properties * * @param properties A plain object hash of values to update for the view */ View.prototype.update = function (properties) { var _this = this; var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.View" }, }, properties)); return this.post({ body: postBody, headers: { "X-HTTP-Method": "MERGE", }, }).then(function (data) { return { data: data, view: _this, }; }); }; /** * Delete this view * */ View.prototype.delete = function () { return this.post({ headers: { "X-HTTP-Method": "DELETE", }, }); }; /** * Returns the list view as HTML. * */ View.prototype.renderAsHtml = function () { return this.clone(queryable_1.Queryable, "renderashtml", true).get(); }; return View; }(queryable_1.QueryableInstance)); exports.View = View; var ViewFields = (function (_super) { __extends(ViewFields, _super); function ViewFields(baseUrl, path) { if (path === void 0) { path = "viewfields"; } return _super.call(this, baseUrl, path) || this; } /** * Gets a value that specifies the XML schema that represents the collection. */ ViewFields.prototype.getSchemaXml = function () { return this.clone(queryable_1.Queryable, "schemaxml", true).get(); }; /** * Adds the field with the specified field internal name or display name to the collection. * * @param fieldTitleOrInternalName The case-sensitive internal name or display name of the field to add. */ ViewFields.prototype.add = function (fieldTitleOrInternalName) { return this.clone(ViewFields, "addviewfield('" + fieldTitleOrInternalName + "')", true).post(); }; /** * Moves the field with the specified field internal name to the specified position in the collection. * * @param fieldInternalName The case-sensitive internal name of the field to move. * @param index The zero-based index of the new position for the field. */ ViewFields.prototype.move = function (fieldInternalName, index) { return this.clone(ViewFields, "moveviewfieldto", true).post({ body: JSON.stringify({ "field": fieldInternalName, "index": index }), }); }; /** * Removes all the fields from the collection. */ ViewFields.prototype.removeAll = function () { return this.clone(ViewFields, "removeallviewfields", true).post(); }; /** * Removes the field with the specified field internal name from the collection. * * @param fieldInternalName The case-sensitive internal name of the field to remove from the view. */ ViewFields.prototype.remove = function (fieldInternalName) { return this.clone(ViewFields, "removeviewfield('" + fieldInternalName + "')", true).post(); }; return ViewFields; }(queryable_1.QueryableCollection)); exports.ViewFields = ViewFields; /***/ }), /* 50 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __extends = (this && this.__extends) || (function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var queryable_1 = __webpack_require__(1); var LimitedWebPartManager = (function (_super) { __extends(LimitedWebPartManager, _super); function LimitedWebPartManager() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(LimitedWebPartManager.prototype, "webparts", { /** * Gets the set of web part definitions contained by this web part manager * */ get: function () { return new WebPartDefinitions(this, "webparts"); }, enumerable: true, configurable: true }); /** * Exports a webpart definition * * @param id the GUID id of the definition to export */ LimitedWebPartManager.prototype.export = function (id) { return this.clone(LimitedWebPartManager, "ExportWebPart", true).post({ body: JSON.stringify({ webPartId: id }), }); }; /** * Imports a webpart * * @param xml webpart definition which must be valid XML in the .dwp or .webpart format */ LimitedWebPartManager.prototype.import = function (xml) { return this.clone(LimitedWebPartManager, "ImportWebPart", true).post({ body: JSON.stringify({ webPartXml: xml }), }); }; return LimitedWebPartManager; }(queryable_1.Queryable)); exports.LimitedWebPartManager = LimitedWebPartManager; var WebPartDefinitions = (function (_super) { __extends(WebPartDefinitions, _super); function WebPartDefinitions() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets a web part definition from the collection by id * * @param id GUID id of the web part definition to get */ WebPartDefinitions.prototype.getById = function (id) { return new WebPartDefinition(this, "getbyid('" + id + "')"); }; return WebPartDefinitions; }(queryable_1.QueryableCollection)); exports.WebPartDefinitions = WebPartDefinitions; var WebPartDefinition = (function (_super) { __extends(WebPartDefinition, _super); function WebPartDefinition() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(WebPartDefinition.prototype, "webpart", { /** * Gets the webpart information associated with this definition */ get: function () { return new WebPart(this); }, enumerable: true, configurable: true }); /** * Removes a webpart from a page, all settings will be lost */ WebPartDefinition.prototype.delete = function () { return this.clone(WebPartDefinition, "DeleteWebPart", true).post(); }; return WebPartDefinition; }(queryable_1.QueryableInstance)); exports.WebPartDefinition = WebPartDefinition; var WebPart = (function (_super) { __extends(WebPart, _super); /** * Creates a new instance of the WebPart class * * @param baseUrl The url or Queryable which forms the parent of this fields collection * @param path Optional, if supplied will be appended to the supplied baseUrl */ function WebPart(baseUrl, path) { if (path === void 0) { path = "webpart"; } return _super.call(this, baseUrl, path) || this; } return WebPart; }(queryable_1.QueryableInstance)); exports.WebPart = WebPart; /***/ }), /* 51 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var logging_1 = __webpack_require__(5); function deprecated(message) { return function (target, propertyKey, descriptor) { var method = descriptor.value; descriptor.value = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } logging_1.Logger.log({ data: { descriptor: descriptor, propertyKey: propertyKey, target: target, }, level: logging_1.LogLevel.Warning, message: message, }); return method.apply(this, args); }; }; } exports.deprecated = deprecated; /***/ }), /* 52 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Reads a blob as text * * @param blob The data to read */ function readBlobAsText(blob) { return readBlobAs(blob, "string"); } exports.readBlobAsText = readBlobAsText; /** * Reads a blob into an array buffer * * @param blob The data to read */ function readBlobAsArrayBuffer(blob) { return readBlobAs(blob, "buffer"); } exports.readBlobAsArrayBuffer = readBlobAsArrayBuffer; /** * Generic method to read blob's content * * @param blob The data to read * @param mode The read mode */ function readBlobAs(blob, mode) { return new Promise(function (resolve, reject) { try { var reader = new FileReader(); reader.onload = function (e) { resolve(e.target.result); }; switch (mode) { case "string": reader.readAsText(blob); break; case "buffer": reader.readAsArrayBuffer(blob); break; } } catch (e) { reject(e); } }); } /***/ }) /******/ ]); }); //# sourceMappingURL=pnp.js.map
var leafletDirective = angular.module("leaflet-directive", []); leafletDirective.directive('leaflet', [ '$http', '$log', '$parse', '$rootScope', function ($http, $log, $parse, $rootScope) { var defaults = { maxZoom: 14, minZoom: 1, doubleClickZoom: true, tileLayer: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', tileLayerOptions: { attribution: 'Tiles &copy; Open Street Maps' }, icon: { url: 'http://cdn.leafletjs.com/leaflet-0.5.1/images/marker-icon.png', retinaUrl: 'http://cdn.leafletjs.com/leaflet-0.5.1/images/[email protected]', size: [25, 41], anchor: [12, 40], popup: [0, -40], shadow: { url: 'http://cdn.leafletjs.com/leaflet-0.5.1/images/marker-shadow.png', retinaUrl: 'http://cdn.leafletjs.com/leaflet-0.5.1/images/marker-shadow.png', size: [41, 41], anchor: [12, 40] } }, path: { weight: 10, opacity: 1, color: '#0000ff' } }; var str_inspect_hint = 'Add testing="testing" to <leaflet> tag to inspect this object'; return { restrict: "E", replace: true, transclude: true, scope: { center: '=center', maxBounds: '=maxbounds', bounds: '=bounds', marker: '=marker', markers: '=markers', defaults: '=defaults', paths: '=paths', tiles: '=tiles', events: '=events' }, template: '<div class="angular-leaflet-map"></div>', link: function ($scope, element, attrs /*, ctrl */) { var centerModel = { lat:$parse("center.lat"), lng:$parse("center.lng"), zoom:$parse("center.zoom") }; if (attrs.width) { element.css('width', attrs.width); } if (attrs.height) { element.css('height', attrs.height); } $scope.leaflet = {}; $scope.leaflet.maxZoom = !!(attrs.defaults && $scope.defaults && $scope.defaults.maxZoom) ? parseInt($scope.defaults.maxZoom, 10) : defaults.maxZoom; $scope.leaflet.minZoom = !!(attrs.defaults && $scope.defaults && $scope.defaults.minZoom) ? parseInt($scope.defaults.minZoom, 10) : defaults.minZoom; $scope.leaflet.doubleClickZoom = !!(attrs.defaults && $scope.defaults && (typeof($scope.defaults.doubleClickZoom) == "boolean") ) ? $scope.defaults.doubleClickZoom : defaults.doubleClickZoom; var map = new L.Map(element[0], { maxZoom: $scope.leaflet.maxZoom, minZoom: $scope.leaflet.minZoom, doubleClickZoom: $scope.leaflet.doubleClickZoom }); map.setView([0, 0], 1); $scope.leaflet.tileLayer = !!(attrs.defaults && $scope.defaults && $scope.defaults.tileLayer) ? $scope.defaults.tileLayer : defaults.tileLayer; $scope.leaflet.map = !!attrs.testing ? map : str_inspect_hint; setupTiles(); setupCenter(); setupMaxBounds(); setupBounds(); setupMainMaerker(); setupMarkers(); setupPaths(); setupEvents(); // use of leafletDirectiveSetMap event is not encouraged. only use // it when there is no easy way to bind data to the directive $scope.$on('leafletDirectiveSetMap', function(event, message) { var meth = message.shift(); map[meth].apply(map, message); }); $scope.safeApply = function(fn) { var phase = this.$root.$$phase; if (phase == '$apply' || phase == '$digest') { $scope.$eval(fn); } else { $scope.$apply(fn); } }; /* * Event setup watches for callbacks set in the parent scope * * $scope.events = { * dblclick: function(){ * // doThis() * }, * click: function(){ * // doThat() * } * } * */ function setupEvents(){ if ( typeof($scope.events) != 'object'){ return false; }else{ for (var bind_to in $scope.events){ map.on(bind_to,$scope.events[bind_to]); } } } function setupTiles(){ // TODO build custom object for tiles, actually only the tile string if ($scope.defaults && $scope.defaults.tileLayerOptions) { for (var key in $scope.defaults.tileLayerOptions) { defaults.tileLayerOptions[key] = $scope.defaults.tileLayerOptions[key]; } } if ($scope.tiles) { if ($scope.tiles.tileLayer) { $scope.leaflet.tileLayer = $scope.tiles.tileLayer; } if ($scope.tiles.tileLayerOptions.attribution) { defaults.tileLayerOptions.attribution = $scope.tiles.tileLayerOptions.attribution; } } var tileLayerObj = L.tileLayer( $scope.leaflet.tileLayer, defaults.tileLayerOptions); tileLayerObj.addTo(map); $scope.leaflet.tileLayerObj = !!attrs.testing ? tileLayerObj : str_inspect_hint; } function setupMaxBounds() { if (!$scope.maxBounds) { return; } if ($scope.maxBounds.southWest && $scope.maxBounds.southWest.lat && $scope.maxBounds.southWest.lng && $scope.maxBounds.northEast && $scope.maxBounds.northEast.lat && $scope.maxBounds.northEast.lng) { map.setMaxBounds( new L.LatLngBounds( new L.LatLng($scope.maxBounds.southWest.lat, $scope.maxBounds.southWest.lng), new L.LatLng($scope.maxBounds.northEast.lat, $scope.maxBounds.northEast.lng) ) ); $scope.$watch("maxBounds", function (maxBounds) { if (maxBounds.southWest && maxBounds.northEast && maxBounds.southWest.lat && maxBounds.southWest.lng && maxBounds.northEast.lat && maxBounds.northEast.lng) { map.setMaxBounds( new L.LatLngBounds( new L.LatLng(maxBounds.southWest.lat, maxBounds.southWest.lng), new L.LatLng(maxBounds.northEast.lat, maxBounds.northEast.lng) ) ); } }); } } function tryFitBounds(bounds) { if (bounds) { var southWest = bounds.southWest; var northEast = bounds.northEast; if (southWest && northEast && southWest.lat && southWest.lng && northEast.lat && northEast.lng) { var sw_latlng = new L.LatLng(southWest.lat, southWest.lng); var ne_latlng = new L.LatLng(northEast.lat, northEast.lng); map.fitBounds(new L.LatLngBounds(sw_latlng, ne_latlng)); } } } function setupBounds() { if (!$scope.bounds) { return; } $scope.$watch('bounds', function (new_bounds) { tryFitBounds(new_bounds); }); } function setupCenter() { $scope.$watch("center", function (center) { if (!center) { $log.warn("[AngularJS - Leaflet] 'center' is undefined in the current scope, did you forget to initialize it?"); return; } if (center.lat && center.lng && center.zoom) { map.setView([center.lat, center.lng], center.zoom); } else if (center.autoDiscover === true) { map.locate({ setView: true, maxZoom: $scope.leaflet.maxZoom }); } }, true); map.on("dragend", function (/* event */) { $scope.safeApply(function (scope) { centerModel.lat.assign(scope, map.getCenter().lat); centerModel.lng.assign(scope, map.getCenter().lng); }); }); map.on("zoomend", function (/* event */) { if(angular.isUndefined($scope.center)){ $log.warn("[AngularJS - Leaflet] 'center' is undefined in the current scope, did you forget to initialize it?"); } if (angular.isUndefined($scope.center) || $scope.center.zoom !== map.getZoom()) { $scope.safeApply(function (s) { centerModel.zoom.assign(s, map.getZoom()); centerModel.lat.assign(s, map.getCenter().lat); centerModel.lng.assign(s, map.getCenter().lng); }); } }); } function setupMainMaerker() { var main_marker; if (!$scope.marker) { return; } main_marker = createMarker('marker', $scope.marker, map); $scope.leaflet.marker = !!attrs.testing ? main_marker : str_inspect_hint; main_marker.on('click', function(e) { $rootScope.$broadcast('leafletDirectiveMainMarkerClick'); }); } function setupMarkers() { var markers = {}; $scope.leaflet.markers = !!attrs.testing ? markers : str_inspect_hint; if (!$scope.markers) { return; } function genMultiMarkersClickCallback(m_name) { return function(e) { $rootScope.$broadcast('leafletDirectiveMarkersClick', m_name); }; } for (var name in $scope.markers) { markers[name] = createMarker( 'markers.'+name, $scope.markers[name], map); markers[name].on('click', genMultiMarkersClickCallback(name)); } $scope.$watch('markers', function(newMarkers) { // Delete markers from the array for (var name in markers) { if (newMarkers[name] === undefined) { delete markers[name]; } } // add new markers for (var new_name in newMarkers) { if (markers[new_name] === undefined) { markers[new_name] = createMarker( 'markers.'+new_name, newMarkers[new_name], map); markers[new_name].on('click', genMultiMarkersClickCallback(new_name)); } } }, true); } function createMarker(scope_watch_name, marker_data, map) { var marker = buildMarker(marker_data); map.addLayer(marker); if (marker_data.focus === true) { marker.openPopup(); } marker.on("dragend", function () { $scope.safeApply(function (scope) { marker_data.lat = marker.getLatLng().lat; marker_data.lng = marker.getLatLng().lng; }); if (marker_data.message) { marker.openPopup(); } }); var clearWatch = $scope.$watch(scope_watch_name, function (data, old_data) { if (!data) { map.removeLayer(marker); clearWatch(); return; } if (old_data) { if (data.draggable !== undefined && data.draggable !== old_data.draggable) { if (data.draggable === true) { marker.dragging.enable(); } else { marker.dragging.disable(); } } if (data.focus !== undefined && data.focus !== old_data.focus) { if (data.focus === true) { marker.openPopup(); } else { marker.closePopup(); } } if (data.message !== undefined && data.message !== old_data.message) { marker.bindPopup(data); } if (data.lat !== old_data.lat || data.lng !== old_data.lng) { marker.setLatLng(new L.LatLng(data.lat, data.lng)); } if (data.icon && data.icon !== old_data.icon) { marker.setIcon(data.icon); } } }, true); return marker; } function buildMarker(data) { var micon = null; if (data.icon) { micon = data.icon; } else { micon = buildIcon(); } var marker = new L.marker(data, { icon: micon, draggable: data.draggable ? true : false } ); if (data.message) { marker.bindPopup(data.message); } return marker; } function buildIcon() { return L.icon({ iconUrl: defaults.icon.url, iconRetinaUrl: defaults.icon.retinaUrl, iconSize: defaults.icon.size, iconAnchor: defaults.icon.anchor, popupAnchor: defaults.icon.popup, shadowUrl: defaults.icon.shadow.url, shadowRetinaUrl: defaults.icon.shadow.retinaUrl, shadowSize: defaults.icon.shadow.size, shadowAnchor: defaults.icon.shadow.anchor }); } function setupPaths() { var paths = {}; $scope.leaflet.paths = !!attrs.testing ? paths : str_inspect_hint; if (!$scope.paths) { return; } $log.warn("[AngularJS - Leaflet] Creating polylines and adding them to the map will break the directive's scope's inspection in AngularJS Batarang"); for (var name in $scope.paths) { paths[name] = createPath(name, $scope.paths[name], map); } $scope.$watch("paths", function (newPaths) { for (var new_name in newPaths) { if (paths[new_name] === undefined) { paths[new_name] = createPath(new_name, newPaths[new_name], map); } } // Delete paths from the array for (var name in paths) { if (newPaths[name] === undefined) { delete paths[name]; } } }, true); } function createPath(name, scopePath, map) { var polyline = new L.Polyline([], { weight: defaults.path.weight, color: defaults.path.color, opacity: defaults.path.opacity }); if (scopePath.latlngs !== undefined) { var latlngs = convertToLeafletLatLngs(scopePath.latlngs); polyline.setLatLngs(latlngs); } if (scopePath.weight !== undefined) { polyline.setStyle({ weight: scopePath.weight }); } if (scopePath.color !== undefined) { polyline.setStyle({ color: scopePath.color }); } if (scopePath.opacity !== undefined) { polyline.setStyle({ opacity: scopePath.opacity }); } map.addLayer(polyline); var clearWatch = $scope.$watch('paths.' + name, function (data, oldData) { if (!data) { map.removeLayer(polyline); clearWatch(); return; } if (oldData) { if (data.latlngs !== undefined && data.latlngs !== oldData.latlngs) { var latlngs = convertToLeafletLatLngs(data.latlngs); polyline.setLatLngs(latlngs); } if (data.weight !== undefined && data.weight !== oldData.weight) { polyline.setStyle({ weight: data.weight }); } if (data.color !== undefined && data.color !== oldData.color) { polyline.setStyle({ color: data.color }); } if (data.opacity !== undefined && data.opacity !== oldData.opacity) { polyline.setStyle({ opacity: data.opacity }); } } }, true); return polyline; } function convertToLeafletLatLngs(latlngs) { var leafletLatLngs = latlngs.filter(function (latlng) { return !!latlng.lat && !!latlng.lng; }).map(function (latlng) { return new L.LatLng(latlng.lat, latlng.lng); }); return leafletLatLngs; } } }; }]);
/** * AngularJS filter for Numeral.js: number formatting as a filter * @version v2.0.1 - 2017-05-06 * @link https://github.com/baumandm/angular-numeraljs * @author Dave Bauman <[email protected]> * @license MIT License, http://www.opensource.org/licenses/MIT */ "use strict";!function(a,b){"object"==typeof exports?module.exports=b(require("numeral")):"function"==typeof define&&define.amd?define(["numeral"],function(c){return a.ngNumeraljs=b(c)}):a.ngNumeraljs=b(a.numeral)}(this,function(a){return angular.module("ngNumeraljs",[]).provider("$numeraljsConfig",function(){var b={};this.defaultFormat=function(b){a.defaultFormat(b)},this.locale=function(b){a.locale(b)},this.namedFormat=function(a,c){b[a]=c},this.register=function(b,c,d){a.register(b,c,d)},this.$get=function(){return{customFormat:function(a){return b[a]||a},defaultFormat:this.defaultFormat,locale:this.locale,register:this.register,namedFormat:this.namedFormat}}}).filter("numeraljs",["$numeraljsConfig",function(b){return function(c,d){return null==c?c:(d=b.customFormat(d),a(c).format(d))}}])});
/** * Add your manual test filenames and display names below. **/ var tests = [ { href: "test-add.html", name: "Add Events" }, { href: "test-delete.html", name: "Delete Events" }, { href: "test-tracks.html", name: "Add Tracks" }, { href: "test-vimeo.html", name: "Change Media to Vimeo" }, { href: "test-youtube.html", name: "Change Media to YouTube" }, { href: "test-save.html", name: "Save and Load" }, { href: "test-share.html", name: "Share HTML5 project" }, { href: "test-sharevimeo.html", name: "Share Vimeo project" }, { href: "test-shareyoutube.html", name: "Share YouTube project" }, { href: "test-export.html", name: "Export HTML5 project" } ].reverse();
/* Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @file Horizontal Page Break */ // Register a plugin named "pagebreak". CKEDITOR.plugins.add( 'pagebreak', { init : function( editor ) { // Register the command. editor.addCommand( 'pagebreak', CKEDITOR.plugins.pagebreakCmd ); // Register the toolbar button. editor.ui.addButton( 'PageBreak', { label : editor.lang.pagebreak, command : 'pagebreak' }); // Add the style that renders our placeholder. editor.addCss( 'img.cke_pagebreak' + '{' + 'background-image: url(' + CKEDITOR.getUrl( this.path + 'images/pagebreak.gif' ) + ');' + 'background-position: center center;' + 'background-repeat: no-repeat;' + 'clear: both;' + 'display: block;' + 'float: none;' + 'width: 100%;' + 'border-top: #999999 1px dotted;' + 'border-bottom: #999999 1px dotted;' + 'height: 5px;' + '}' ); }, afterInit : function( editor ) { // Register a filter to displaying placeholders after mode change. var dataProcessor = editor.dataProcessor, dataFilter = dataProcessor && dataProcessor.dataFilter; if ( dataFilter ) { dataFilter.addRules( { elements : { div : function( element ) { var attributes = element.attributes, style = attributes && attributes.style, child = style && element.children.length == 1 && element.children[ 0 ], childStyle = child && ( child.name == 'span' ) && child.attributes.style; if ( childStyle && ( /page-break-after\s*:\s*always/i ).test( style ) && ( /display\s*:\s*none/i ).test( childStyle ) ) return editor.createFakeParserElement( element, 'cke_pagebreak', 'div' ); } } }); } }, requires : [ 'fakeobjects' ] }); CKEDITOR.plugins.pagebreakCmd = { exec : function( editor ) { // Create the element that represents a print break. var breakObject = CKEDITOR.dom.element.createFromHtml( '<div style="page-break-after: always;"><span style="display: none;">&nbsp;</span></div>' ); // Creates the fake image used for this element. breakObject = editor.createFakeElement( breakObject, 'cke_pagebreak', 'div' ); var ranges = editor.getSelection().getRanges(); for ( var range, i = 0 ; i < ranges.length ; i++ ) { range = ranges[ i ]; if ( i > 0 ) breakObject = breakObject.clone( true ); range.splitBlock( 'p' ); range.insertNode( breakObject ); } } };
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'save', 'af', { toolbar: 'Bewaar' } );
define( //begin v1.x content { "field-sat-relative+0": "เสาร์นี้", "field-sat-relative+1": "เสาร์หน้า", "field-dayperiod": "ช่วงวัน", "field-sun-relative+-1": "อาทิตย์ที่แล้ว", "field-mon-relative+-1": "จันทร์ที่แล้ว", "field-minute": "นาที", "field-day-relative+-1": "เมื่อวาน", "field-weekday": "วันในสัปดาห์", "field-day-relative+-2": "เมื่อวานซืน", "months-standAlone-narrow": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13" ], "field-era": "สมัย", "field-hour": "ชั่วโมง", "field-sun-relative+0": "อาทิตย์นี้", "field-sun-relative+1": "อาทิตย์หน้า", "months-standAlone-abbr": [ "เมสเคอเรม", "เตเกมท", "เฮดาร์", "ทาฮ์ซัส", "เทอร์", "เยคาทิท", "เมกาบิต", "เมียเซีย", "เจนบอต", "เซเน", "ฮัมเล", "เนแฮซ", "พากูเมน" ], "field-wed-relative+-1": "พุธที่แล้ว", "field-day-relative+0": "วันนี้", "field-day-relative+1": "พรุ่งนี้", "field-day-relative+2": "มะรืนนี้", "field-tue-relative+0": "อังคารนี้", "field-zone": "เขตเวลา", "field-tue-relative+1": "อังคารหน้า", "field-week-relative+-1": "สัปดาห์ที่แล้ว", "field-year-relative+0": "ปีนี้", "field-year-relative+1": "ปีหน้า", "field-sat-relative+-1": "เสาร์ที่แล้ว", "field-year-relative+-1": "ปีที่แล้ว", "field-year": "ปี", "field-fri-relative+0": "ศุกร์นี้", "field-fri-relative+1": "ศุกร์หน้า", "months-standAlone-wide": [ "เมสเคอเรม", "เตเกมท", "เฮดาร์", "ทาฮ์ซัส", "เทอร์", "เยคาทิท", "เมกาบิต", "เมียเซีย", "เจนบอต", "เซเน", "ฮัมเล", "เนแฮซ", "พากูเมน" ], "field-week": "สัปดาห์", "field-week-relative+0": "สัปดาห์นี้", "field-week-relative+1": "สัปดาห์หน้า", "months-format-abbr": [ "เมสเคอเรม", "เตเกมท", "เฮดาร์", "ทาฮ์ซัส", "เทอร์", "เยคาทิท", "เมกาบิต", "เมียเซีย", "เจนบอต", "เซเน", "ฮัมเล", "เนแฮซ", "พากูเมน" ], "field-month-relative+0": "เดือนนี้", "field-month": "เดือน", "field-month-relative+1": "เดือนหน้า", "field-fri-relative+-1": "ศุกร์ที่แล้ว", "field-second": "วินาที", "field-tue-relative+-1": "อังคารที่แล้ว", "field-day": "วัน", "months-format-narrow": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13" ], "field-mon-relative+0": "จันทร์นี้", "field-mon-relative+1": "จันทร์หน้า", "field-thu-relative+0": "พฤหัสนี้", "field-second-relative+0": "ขณะนี้", "field-thu-relative+1": "พฤหัสหน้า", "months-format-wide": [ "เมสเคอเรม", "เตเกมท", "เฮดาร์", "ทาฮ์ซัส", "เทอร์", "เยคาทิท", "เมกาบิต", "เมียเซีย", "เจนบอต", "เซเน", "ฮัมเล", "เนแฮซ", "พากูเมน" ], "field-wed-relative+0": "พุธนี้", "field-wed-relative+1": "พุธหน้า", "field-month-relative+-1": "เดือนที่แล้ว", "field-thu-relative+-1": "พฤหัสที่แล้ว" } //end v1.x content );
(function (factory) { if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else if (typeof module === 'object' && typeof module.exports === 'object') { factory(require('jquery')); } else { factory(jQuery); } }(function (jQuery) { // Amharic jQuery.timeago.settings.strings = { prefixAgo: null, prefixFromNow: null, suffixAgo: "በፊት", suffixFromNow: "በኋላ", seconds: "ከአንድ ደቂቃ በታች", minute: "ከአንድ ደቂቃ ገደማ", minutes: "ከ%d ደቂቃ", hour: "ከአንድ ሰዓት ገደማ", hours: "ከ%d ሰዓት ገደማ", day: "ከአንድ ቀን", days: "ከ%d ቀን", month: "ከአንድ ወር ገደማ", months: "ከ%d ወር", year: "ከአንድ ዓመት ገደማ", years: "ከ%d ዓመት", wordSeparator: " ", numbers: [] }; }));
import { changeProperties } from './property_events'; import { set } from './property_set'; /** Set a list of properties on an object. These properties are set inside a single `beginPropertyChanges` and `endPropertyChanges` batch, so observers will be buffered. ```javascript let anObject = Ember.Object.create(); anObject.setProperties({ firstName: 'Stanley', lastName: 'Stuart', age: 21 }); ``` @method setProperties @param obj @param {Object} properties @return properties @public */ export default function setProperties(obj, properties) { if (!properties || typeof properties !== 'object') { return properties; } changeProperties(() => { let props = Object.keys(properties); let propertyName; for (let i = 0; i < props.length; i++) { propertyName = props[i]; set(obj, propertyName, properties[propertyName]); } }); return properties; }
/* * JsSIP v3.0.2 * the Javascript SIP library * Copyright: 2012-2017 José Luis Millán <[email protected]> (https://github.com/jmillan) * Homepage: http://jssip.net * License: MIT */ (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.JsSIP = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ var pkg = require('../package.json'); var C = { USER_AGENT: pkg.title + ' ' + pkg.version, // SIP scheme SIP: 'sip', SIPS: 'sips', // End and Failure causes causes: { // Generic error causes CONNECTION_ERROR: 'Connection Error', REQUEST_TIMEOUT: 'Request Timeout', SIP_FAILURE_CODE: 'SIP Failure Code', INTERNAL_ERROR: 'Internal Error', // SIP error causes BUSY: 'Busy', REJECTED: 'Rejected', REDIRECTED: 'Redirected', UNAVAILABLE: 'Unavailable', NOT_FOUND: 'Not Found', ADDRESS_INCOMPLETE: 'Address Incomplete', INCOMPATIBLE_SDP: 'Incompatible SDP', MISSING_SDP: 'Missing SDP', AUTHENTICATION_ERROR: 'Authentication Error', // Session error causes BYE: 'Terminated', WEBRTC_ERROR: 'WebRTC Error', CANCELED: 'Canceled', NO_ANSWER: 'No Answer', EXPIRES: 'Expires', NO_ACK: 'No ACK', DIALOG_ERROR: 'Dialog Error', USER_DENIED_MEDIA_ACCESS: 'User Denied Media Access', BAD_MEDIA_DESCRIPTION: 'Bad Media Description', RTP_TIMEOUT: 'RTP Timeout' }, SIP_ERROR_CAUSES: { REDIRECTED: [300,301,302,305,380], BUSY: [486,600], REJECTED: [403,603], NOT_FOUND: [404,604], UNAVAILABLE: [480,410,408,430], ADDRESS_INCOMPLETE: [484, 424], INCOMPATIBLE_SDP: [488,606], AUTHENTICATION_ERROR:[401,407] }, // SIP Methods ACK: 'ACK', BYE: 'BYE', CANCEL: 'CANCEL', INFO: 'INFO', INVITE: 'INVITE', MESSAGE: 'MESSAGE', NOTIFY: 'NOTIFY', OPTIONS: 'OPTIONS', REGISTER: 'REGISTER', REFER: 'REFER', UPDATE: 'UPDATE', SUBSCRIBE: 'SUBSCRIBE', /* SIP Response Reasons * DOC: http://www.iana.org/assignments/sip-parameters * Copied from https://github.com/versatica/OverSIP/blob/master/lib/oversip/sip/constants.rb#L7 */ REASON_PHRASE: { 100: 'Trying', 180: 'Ringing', 181: 'Call Is Being Forwarded', 182: 'Queued', 183: 'Session Progress', 199: 'Early Dialog Terminated', // draft-ietf-sipcore-199 200: 'OK', 202: 'Accepted', // RFC 3265 204: 'No Notification', //RFC 5839 300: 'Multiple Choices', 301: 'Moved Permanently', 302: 'Moved Temporarily', 305: 'Use Proxy', 380: 'Alternative Service', 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 407: 'Proxy Authentication Required', 408: 'Request Timeout', 410: 'Gone', 412: 'Conditional Request Failed', // RFC 3903 413: 'Request Entity Too Large', 414: 'Request-URI Too Long', 415: 'Unsupported Media Type', 416: 'Unsupported URI Scheme', 417: 'Unknown Resource-Priority', // RFC 4412 420: 'Bad Extension', 421: 'Extension Required', 422: 'Session Interval Too Small', // RFC 4028 423: 'Interval Too Brief', 424: 'Bad Location Information', // RFC 6442 428: 'Use Identity Header', // RFC 4474 429: 'Provide Referrer Identity', // RFC 3892 430: 'Flow Failed', // RFC 5626 433: 'Anonymity Disallowed', // RFC 5079 436: 'Bad Identity-Info', // RFC 4474 437: 'Unsupported Certificate', // RFC 4744 438: 'Invalid Identity Header', // RFC 4744 439: 'First Hop Lacks Outbound Support', // RFC 5626 440: 'Max-Breadth Exceeded', // RFC 5393 469: 'Bad Info Package', // draft-ietf-sipcore-info-events 470: 'Consent Needed', // RFC 5360 478: 'Unresolvable Destination', // Custom code copied from Kamailio. 480: 'Temporarily Unavailable', 481: 'Call/Transaction Does Not Exist', 482: 'Loop Detected', 483: 'Too Many Hops', 484: 'Address Incomplete', 485: 'Ambiguous', 486: 'Busy Here', 487: 'Request Terminated', 488: 'Not Acceptable Here', 489: 'Bad Event', // RFC 3265 491: 'Request Pending', 493: 'Undecipherable', 494: 'Security Agreement Required', // RFC 3329 500: 'JsSIP Internal Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Server Time-out', 505: 'Version Not Supported', 513: 'Message Too Large', 580: 'Precondition Failure', // RFC 3312 600: 'Busy Everywhere', 603: 'Decline', 604: 'Does Not Exist Anywhere', 606: 'Not Acceptable' }, ALLOWED_METHODS: 'INVITE,ACK,CANCEL,BYE,UPDATE,MESSAGE,OPTIONS,REFER,INFO', ACCEPTED_BODY_TYPES: 'application/sdp, application/dtmf-relay', MAX_FORWARDS: 69, SESSION_EXPIRES: 90, MIN_SESSION_EXPIRES: 60 }; module.exports = C; },{"../package.json":50}],2:[function(require,module,exports){ module.exports = Dialog; var C = { // Dialog states STATUS_EARLY: 1, STATUS_CONFIRMED: 2 }; /** * Expose C object. */ Dialog.C = C; /** * Dependencies. */ var debug = require('debug')('JsSIP:Dialog'); var SIPMessage = require('./SIPMessage'); var JsSIP_C = require('./Constants'); var Transactions = require('./Transactions'); var Dialog_RequestSender = require('./Dialog/RequestSender'); // RFC 3261 12.1 function Dialog(owner, message, type, state) { var contact; this.uac_pending_reply = false; this.uas_pending_reply = false; if(!message.hasHeader('contact')) { return { error: 'unable to create a Dialog without Contact header field' }; } if(message instanceof SIPMessage.IncomingResponse) { state = (message.status_code < 200) ? C.STATUS_EARLY : C.STATUS_CONFIRMED; } else { // Create confirmed dialog if state is not defined state = state || C.STATUS_CONFIRMED; } contact = message.parseHeader('contact'); // RFC 3261 12.1.1 if(type === 'UAS') { this.id = { call_id: message.call_id, local_tag: message.to_tag, remote_tag: message.from_tag, toString: function() { return this.call_id + this.local_tag + this.remote_tag; } }; this.state = state; this.remote_seqnum = message.cseq; this.local_uri = message.parseHeader('to').uri; this.remote_uri = message.parseHeader('from').uri; this.remote_target = contact.uri; this.route_set = message.getHeaders('record-route'); } // RFC 3261 12.1.2 else if(type === 'UAC') { this.id = { call_id: message.call_id, local_tag: message.from_tag, remote_tag: message.to_tag, toString: function() { return this.call_id + this.local_tag + this.remote_tag; } }; this.state = state; this.local_seqnum = message.cseq; this.local_uri = message.parseHeader('from').uri; this.remote_uri = message.parseHeader('to').uri; this.remote_target = contact.uri; this.route_set = message.getHeaders('record-route').reverse(); } this.owner = owner; owner.ua.dialogs[this.id.toString()] = this; debug('new ' + type + ' dialog created with status ' + (this.state === C.STATUS_EARLY ? 'EARLY': 'CONFIRMED')); } Dialog.prototype = { update: function(message, type) { this.state = C.STATUS_CONFIRMED; debug('dialog '+ this.id.toString() +' changed to CONFIRMED state'); if(type === 'UAC') { // RFC 3261 13.2.2.4 this.route_set = message.getHeaders('record-route').reverse(); } }, terminate: function() { debug('dialog ' + this.id.toString() + ' deleted'); delete this.owner.ua.dialogs[this.id.toString()]; }, // RFC 3261 12.2.1.1 createRequest: function(method, extraHeaders, body) { var cseq, request; extraHeaders = extraHeaders && extraHeaders.slice() || []; if(!this.local_seqnum) { this.local_seqnum = Math.floor(Math.random() * 10000); } cseq = (method === JsSIP_C.CANCEL || method === JsSIP_C.ACK) ? this.local_seqnum : this.local_seqnum += 1; request = new SIPMessage.OutgoingRequest( method, this.remote_target, this.owner.ua, { 'cseq': cseq, 'call_id': this.id.call_id, 'from_uri': this.local_uri, 'from_tag': this.id.local_tag, 'to_uri': this.remote_uri, 'to_tag': this.id.remote_tag, 'route_set': this.route_set }, extraHeaders, body); request.dialog = this; return request; }, // RFC 3261 12.2.2 checkInDialogRequest: function(request) { var self = this; if(!this.remote_seqnum) { this.remote_seqnum = request.cseq; } else if(request.cseq < this.remote_seqnum) { //Do not try to reply to an ACK request. if (request.method !== JsSIP_C.ACK) { request.reply(500); } return false; } else if(request.cseq > this.remote_seqnum) { this.remote_seqnum = request.cseq; } // RFC3261 14.2 Modifying an Existing Session -UAS BEHAVIOR- if (request.method === JsSIP_C.INVITE || (request.method === JsSIP_C.UPDATE && request.body)) { if (this.uac_pending_reply === true) { request.reply(491); } else if (this.uas_pending_reply === true) { var retryAfter = (Math.random() * 10 | 0) + 1; request.reply(500, null, ['Retry-After:'+ retryAfter]); return false; } else { this.uas_pending_reply = true; request.server_transaction.on('stateChanged', function stateChanged(){ if (this.state === Transactions.C.STATUS_ACCEPTED || this.state === Transactions.C.STATUS_COMPLETED || this.state === Transactions.C.STATUS_TERMINATED) { request.server_transaction.removeListener('stateChanged', stateChanged); self.uas_pending_reply = false; } }); } // RFC3261 12.2.2 Replace the dialog`s remote target URI if the request is accepted if(request.hasHeader('contact')) { request.server_transaction.on('stateChanged', function(){ if (this.state === Transactions.C.STATUS_ACCEPTED) { self.remote_target = request.parseHeader('contact').uri; } }); } } else if (request.method === JsSIP_C.NOTIFY) { // RFC6665 3.2 Replace the dialog`s remote target URI if the request is accepted if(request.hasHeader('contact')) { request.server_transaction.on('stateChanged', function(){ if (this.state === Transactions.C.STATUS_COMPLETED) { self.remote_target = request.parseHeader('contact').uri; } }); } } return true; }, sendRequest: function(applicant, method, options) { options = options || {}; var extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], body = options.body || null, request = this.createRequest(method, extraHeaders, body), request_sender = new Dialog_RequestSender(this, applicant, request); request_sender.send(); // Return the instance of OutgoingRequest return request; }, receiveRequest: function(request) { //Check in-dialog request if(!this.checkInDialogRequest(request)) { return; } this.owner.receiveRequest(request); } }; },{"./Constants":1,"./Dialog/RequestSender":3,"./SIPMessage":18,"./Transactions":21,"debug":34}],3:[function(require,module,exports){ module.exports = DialogRequestSender; /** * Dependencies. */ var JsSIP_C = require('../Constants'); var Transactions = require('../Transactions'); var RTCSession = require('../RTCSession'); var RequestSender = require('../RequestSender'); function DialogRequestSender(dialog, applicant, request) { this.dialog = dialog; this.applicant = applicant; this.request = request; // RFC3261 14.1 Modifying an Existing Session. UAC Behavior. this.reattempt = false; this.reattemptTimer = null; } DialogRequestSender.prototype = { send: function() { var self = this, request_sender = new RequestSender(this, this.dialog.owner.ua); request_sender.send(); // RFC3261 14.2 Modifying an Existing Session -UAC BEHAVIOR- if ((this.request.method === JsSIP_C.INVITE || (this.request.method === JsSIP_C.UPDATE && this.request.body)) && request_sender.clientTransaction.state !== Transactions.C.STATUS_TERMINATED) { this.dialog.uac_pending_reply = true; request_sender.clientTransaction.on('stateChanged', function stateChanged(){ if (this.state === Transactions.C.STATUS_ACCEPTED || this.state === Transactions.C.STATUS_COMPLETED || this.state === Transactions.C.STATUS_TERMINATED) { request_sender.clientTransaction.removeListener('stateChanged', stateChanged); self.dialog.uac_pending_reply = false; } }); } }, onRequestTimeout: function() { this.applicant.onRequestTimeout(); }, onTransportError: function() { this.applicant.onTransportError(); }, receiveResponse: function(response) { var self = this; // RFC3261 12.2.1.2 408 or 481 is received for a request within a dialog. if (response.status_code === 408 || response.status_code === 481) { this.applicant.onDialogError(response); } else if (response.method === JsSIP_C.INVITE && response.status_code === 491) { if (this.reattempt) { this.applicant.receiveResponse(response); } else { this.request.cseq.value = this.dialog.local_seqnum += 1; this.reattemptTimer = setTimeout(function() { if (self.applicant.owner.status !== RTCSession.C.STATUS_TERMINATED) { self.reattempt = true; self.request_sender.send(); } }, 1000); } } else { this.applicant.receiveResponse(response); } } }; },{"../Constants":1,"../RTCSession":11,"../RequestSender":17,"../Transactions":21}],4:[function(require,module,exports){ module.exports = DigestAuthentication; /** * Dependencies. */ var debug = require('debug')('JsSIP:DigestAuthentication'); var debugerror = require('debug')('JsSIP:ERROR:DigestAuthentication'); debugerror.log = console.warn.bind(console); var Utils = require('./Utils'); function DigestAuthentication(credentials) { this.credentials = credentials; this.cnonce = null; this.nc = 0; this.ncHex = '00000000'; this.algorithm = null; this.realm = null; this.nonce = null; this.opaque = null; this.stale = null; this.qop = null; this.method = null; this.uri = null; this.ha1 = null; this.response = null; } DigestAuthentication.prototype.get = function(parameter) { switch (parameter) { case 'realm': return this.realm; case 'ha1': return this.ha1; default: debugerror('get() | cannot get "%s" parameter', parameter); return undefined; } }; /** * Performs Digest authentication given a SIP request and the challenge * received in a response to that request. * Returns true if auth was successfully generated, false otherwise. */ DigestAuthentication.prototype.authenticate = function(request, challenge) { var ha2, hex; this.algorithm = challenge.algorithm; this.realm = challenge.realm; this.nonce = challenge.nonce; this.opaque = challenge.opaque; this.stale = challenge.stale; if (this.algorithm) { if (this.algorithm !== 'MD5') { debugerror('authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted'); return false; } } else { this.algorithm = 'MD5'; } if (!this.nonce) { debugerror('authenticate() | challenge without Digest nonce, authentication aborted'); return false; } if (!this.realm) { debugerror('authenticate() | challenge without Digest realm, authentication aborted'); return false; } // If no plain SIP password is provided. if (!this.credentials.password) { // If ha1 is not provided we cannot authenticate. if (!this.credentials.ha1) { debugerror('authenticate() | no plain SIP password nor ha1 provided, authentication aborted'); return false; } // If the realm does not match the stored realm we cannot authenticate. if (this.credentials.realm !== this.realm) { debugerror('authenticate() | no plain SIP password, and stored `realm` does not match the given `realm`, cannot authenticate [stored:"%s", given:"%s"]', this.credentials.realm, this.realm); return false; } } // 'qop' can contain a list of values (Array). Let's choose just one. if (challenge.qop) { if (challenge.qop.indexOf('auth') > -1) { this.qop = 'auth'; } else if (challenge.qop.indexOf('auth-int') > -1) { this.qop = 'auth-int'; } else { // Otherwise 'qop' is present but does not contain 'auth' or 'auth-int', so abort here. debugerror('authenticate() | challenge without Digest qop different than "auth" or "auth-int", authentication aborted'); return false; } } else { this.qop = null; } // Fill other attributes. this.method = request.method; this.uri = request.ruri; this.cnonce = Utils.createRandomToken(12); this.nc += 1; hex = Number(this.nc).toString(16); this.ncHex = '00000000'.substr(0, 8-hex.length) + hex; // nc-value = 8LHEX. Max value = 'FFFFFFFF'. if (this.nc === 4294967296) { this.nc = 1; this.ncHex = '00000001'; } // Calculate the Digest "response" value. // If we have plain SIP password then regenerate ha1. if (this.credentials.password) { // HA1 = MD5(A1) = MD5(username:realm:password) this.ha1 = Utils.calculateMD5(this.credentials.username + ':' + this.realm + ':' + this.credentials.password); // // Otherwise reuse the stored ha1. } else { this.ha1 = this.credentials.ha1; } if (this.qop === 'auth') { // HA2 = MD5(A2) = MD5(method:digestURI) ha2 = Utils.calculateMD5(this.method + ':' + this.uri); // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) this.response = Utils.calculateMD5(this.ha1 + ':' + this.nonce + ':' + this.ncHex + ':' + this.cnonce + ':auth:' + ha2); } else if (this.qop === 'auth-int') { // HA2 = MD5(A2) = MD5(method:digestURI:MD5(entityBody)) ha2 = Utils.calculateMD5(this.method + ':' + this.uri + ':' + Utils.calculateMD5(this.body ? this.body : '')); // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) this.response = Utils.calculateMD5(this.ha1 + ':' + this.nonce + ':' + this.ncHex + ':' + this.cnonce + ':auth-int:' + ha2); } else if (this.qop === null) { // HA2 = MD5(A2) = MD5(method:digestURI) ha2 = Utils.calculateMD5(this.method + ':' + this.uri); // response = MD5(HA1:nonce:HA2) this.response = Utils.calculateMD5(this.ha1 + ':' + this.nonce + ':' + ha2); } debug('authenticate() | response generated'); return true; }; /** * Return the Proxy-Authorization or WWW-Authorization header value. */ DigestAuthentication.prototype.toString = function() { var auth_params = []; if (!this.response) { throw new Error('response field does not exist, cannot generate Authorization header'); } auth_params.push('algorithm=' + this.algorithm); auth_params.push('username="' + this.credentials.username + '"'); auth_params.push('realm="' + this.realm + '"'); auth_params.push('nonce="' + this.nonce + '"'); auth_params.push('uri="' + this.uri + '"'); auth_params.push('response="' + this.response + '"'); if (this.opaque) { auth_params.push('opaque="' + this.opaque + '"'); } if (this.qop) { auth_params.push('qop=' + this.qop); auth_params.push('cnonce="' + this.cnonce + '"'); auth_params.push('nc=' + this.ncHex); } return 'Digest ' + auth_params.join(', '); }; },{"./Utils":25,"debug":34}],5:[function(require,module,exports){ /** * @namespace Exceptions * @memberOf JsSIP */ var Exceptions = { /** * Exception thrown when a valid parameter is given to the JsSIP.UA constructor. * @class ConfigurationError * @memberOf JsSIP.Exceptions */ ConfigurationError: (function(){ var exception = function(parameter, value) { this.code = 1; this.name = 'CONFIGURATION_ERROR'; this.parameter = parameter; this.value = value; this.message = (!this.value)? 'Missing parameter: '+ this.parameter : 'Invalid value '+ JSON.stringify(this.value) +' for parameter "'+ this.parameter +'"'; }; exception.prototype = new Error(); return exception; }()), InvalidStateError: (function(){ var exception = function(status) { this.code = 2; this.name = 'INVALID_STATE_ERROR'; this.status = status; this.message = 'Invalid status: '+ status; }; exception.prototype = new Error(); return exception; }()), NotSupportedError: (function(){ var exception = function(message) { this.code = 3; this.name = 'NOT_SUPPORTED_ERROR'; this.message = message; }; exception.prototype = new Error(); return exception; }()), NotReadyError: (function(){ var exception = function(message) { this.code = 4; this.name = 'NOT_READY_ERROR'; this.message = message; }; exception.prototype = new Error(); return exception; }()) }; module.exports = Exceptions; },{}],6:[function(require,module,exports){ module.exports = (function(){ /* * Generated by PEG.js 0.7.0. * * http://pegjs.majda.cz/ */ function quote(s) { /* * ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a * string literal except for the closing quote character, backslash, * carriage return, line separator, paragraph separator, and line feed. * Any character may appear in the form of an escape sequence. * * For portability, we also escape escape all control and non-ASCII * characters. Note that "\0" and "\v" escape sequences are not used * because JSHint does not like the first and IE the second. */ return '"' + s .replace(/\\/g, '\\\\') // backslash .replace(/"/g, '\\"') // closing quote character .replace(/\x08/g, '\\b') // backspace .replace(/\t/g, '\\t') // horizontal tab .replace(/\n/g, '\\n') // line feed .replace(/\f/g, '\\f') // form feed .replace(/\r/g, '\\r') // carriage return .replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g, escape) + '"'; } var result = { /* * Parses the input with a generated parser. If the parsing is successfull, * returns a value explicitly or implicitly specified by the grammar from * which the parser was generated (see |PEG.buildParser|). If the parsing is * unsuccessful, throws |PEG.parser.SyntaxError| describing the error. */ parse: function(input, startRule) { var parseFunctions = { "CRLF": parse_CRLF, "DIGIT": parse_DIGIT, "ALPHA": parse_ALPHA, "HEXDIG": parse_HEXDIG, "WSP": parse_WSP, "OCTET": parse_OCTET, "DQUOTE": parse_DQUOTE, "SP": parse_SP, "HTAB": parse_HTAB, "alphanum": parse_alphanum, "reserved": parse_reserved, "unreserved": parse_unreserved, "mark": parse_mark, "escaped": parse_escaped, "LWS": parse_LWS, "SWS": parse_SWS, "HCOLON": parse_HCOLON, "TEXT_UTF8_TRIM": parse_TEXT_UTF8_TRIM, "TEXT_UTF8char": parse_TEXT_UTF8char, "UTF8_NONASCII": parse_UTF8_NONASCII, "UTF8_CONT": parse_UTF8_CONT, "LHEX": parse_LHEX, "token": parse_token, "token_nodot": parse_token_nodot, "separators": parse_separators, "word": parse_word, "STAR": parse_STAR, "SLASH": parse_SLASH, "EQUAL": parse_EQUAL, "LPAREN": parse_LPAREN, "RPAREN": parse_RPAREN, "RAQUOT": parse_RAQUOT, "LAQUOT": parse_LAQUOT, "COMMA": parse_COMMA, "SEMI": parse_SEMI, "COLON": parse_COLON, "LDQUOT": parse_LDQUOT, "RDQUOT": parse_RDQUOT, "comment": parse_comment, "ctext": parse_ctext, "quoted_string": parse_quoted_string, "quoted_string_clean": parse_quoted_string_clean, "qdtext": parse_qdtext, "quoted_pair": parse_quoted_pair, "SIP_URI_noparams": parse_SIP_URI_noparams, "SIP_URI": parse_SIP_URI, "uri_scheme": parse_uri_scheme, "uri_scheme_sips": parse_uri_scheme_sips, "uri_scheme_sip": parse_uri_scheme_sip, "userinfo": parse_userinfo, "user": parse_user, "user_unreserved": parse_user_unreserved, "password": parse_password, "hostport": parse_hostport, "host": parse_host, "hostname": parse_hostname, "domainlabel": parse_domainlabel, "toplabel": parse_toplabel, "IPv6reference": parse_IPv6reference, "IPv6address": parse_IPv6address, "h16": parse_h16, "ls32": parse_ls32, "IPv4address": parse_IPv4address, "dec_octet": parse_dec_octet, "port": parse_port, "uri_parameters": parse_uri_parameters, "uri_parameter": parse_uri_parameter, "transport_param": parse_transport_param, "user_param": parse_user_param, "method_param": parse_method_param, "ttl_param": parse_ttl_param, "maddr_param": parse_maddr_param, "lr_param": parse_lr_param, "other_param": parse_other_param, "pname": parse_pname, "pvalue": parse_pvalue, "paramchar": parse_paramchar, "param_unreserved": parse_param_unreserved, "headers": parse_headers, "header": parse_header, "hname": parse_hname, "hvalue": parse_hvalue, "hnv_unreserved": parse_hnv_unreserved, "Request_Response": parse_Request_Response, "Request_Line": parse_Request_Line, "Request_URI": parse_Request_URI, "absoluteURI": parse_absoluteURI, "hier_part": parse_hier_part, "net_path": parse_net_path, "abs_path": parse_abs_path, "opaque_part": parse_opaque_part, "uric": parse_uric, "uric_no_slash": parse_uric_no_slash, "path_segments": parse_path_segments, "segment": parse_segment, "param": parse_param, "pchar": parse_pchar, "scheme": parse_scheme, "authority": parse_authority, "srvr": parse_srvr, "reg_name": parse_reg_name, "query": parse_query, "SIP_Version": parse_SIP_Version, "INVITEm": parse_INVITEm, "ACKm": parse_ACKm, "OPTIONSm": parse_OPTIONSm, "BYEm": parse_BYEm, "CANCELm": parse_CANCELm, "REGISTERm": parse_REGISTERm, "SUBSCRIBEm": parse_SUBSCRIBEm, "NOTIFYm": parse_NOTIFYm, "REFERm": parse_REFERm, "Method": parse_Method, "Status_Line": parse_Status_Line, "Status_Code": parse_Status_Code, "extension_code": parse_extension_code, "Reason_Phrase": parse_Reason_Phrase, "Allow_Events": parse_Allow_Events, "Call_ID": parse_Call_ID, "Contact": parse_Contact, "contact_param": parse_contact_param, "name_addr": parse_name_addr, "display_name": parse_display_name, "contact_params": parse_contact_params, "c_p_q": parse_c_p_q, "c_p_expires": parse_c_p_expires, "delta_seconds": parse_delta_seconds, "qvalue": parse_qvalue, "generic_param": parse_generic_param, "gen_value": parse_gen_value, "Content_Disposition": parse_Content_Disposition, "disp_type": parse_disp_type, "disp_param": parse_disp_param, "handling_param": parse_handling_param, "Content_Encoding": parse_Content_Encoding, "Content_Length": parse_Content_Length, "Content_Type": parse_Content_Type, "media_type": parse_media_type, "m_type": parse_m_type, "discrete_type": parse_discrete_type, "composite_type": parse_composite_type, "extension_token": parse_extension_token, "x_token": parse_x_token, "m_subtype": parse_m_subtype, "m_parameter": parse_m_parameter, "m_value": parse_m_value, "CSeq": parse_CSeq, "CSeq_value": parse_CSeq_value, "Expires": parse_Expires, "Event": parse_Event, "event_type": parse_event_type, "From": parse_From, "from_param": parse_from_param, "tag_param": parse_tag_param, "Max_Forwards": parse_Max_Forwards, "Min_Expires": parse_Min_Expires, "Name_Addr_Header": parse_Name_Addr_Header, "Proxy_Authenticate": parse_Proxy_Authenticate, "challenge": parse_challenge, "other_challenge": parse_other_challenge, "auth_param": parse_auth_param, "digest_cln": parse_digest_cln, "realm": parse_realm, "realm_value": parse_realm_value, "domain": parse_domain, "URI": parse_URI, "nonce": parse_nonce, "nonce_value": parse_nonce_value, "opaque": parse_opaque, "stale": parse_stale, "algorithm": parse_algorithm, "qop_options": parse_qop_options, "qop_value": parse_qop_value, "Proxy_Require": parse_Proxy_Require, "Record_Route": parse_Record_Route, "rec_route": parse_rec_route, "Reason": parse_Reason, "reason_param": parse_reason_param, "reason_cause": parse_reason_cause, "Require": parse_Require, "Route": parse_Route, "route_param": parse_route_param, "Subscription_State": parse_Subscription_State, "substate_value": parse_substate_value, "subexp_params": parse_subexp_params, "event_reason_value": parse_event_reason_value, "Subject": parse_Subject, "Supported": parse_Supported, "To": parse_To, "to_param": parse_to_param, "Via": parse_Via, "via_param": parse_via_param, "via_params": parse_via_params, "via_ttl": parse_via_ttl, "via_maddr": parse_via_maddr, "via_received": parse_via_received, "via_branch": parse_via_branch, "response_port": parse_response_port, "sent_protocol": parse_sent_protocol, "protocol_name": parse_protocol_name, "transport": parse_transport, "sent_by": parse_sent_by, "via_host": parse_via_host, "via_port": parse_via_port, "ttl": parse_ttl, "WWW_Authenticate": parse_WWW_Authenticate, "Session_Expires": parse_Session_Expires, "s_e_expires": parse_s_e_expires, "s_e_params": parse_s_e_params, "s_e_refresher": parse_s_e_refresher, "extension_header": parse_extension_header, "header_value": parse_header_value, "message_body": parse_message_body, "uuid_URI": parse_uuid_URI, "uuid": parse_uuid, "hex4": parse_hex4, "hex8": parse_hex8, "hex12": parse_hex12, "Refer_To": parse_Refer_To, "Replaces": parse_Replaces, "call_id": parse_call_id, "replaces_param": parse_replaces_param, "to_tag": parse_to_tag, "from_tag": parse_from_tag, "early_flag": parse_early_flag }; if (startRule !== undefined) { if (parseFunctions[startRule] === undefined) { throw new Error("Invalid rule name: " + quote(startRule) + "."); } } else { startRule = "CRLF"; } var pos = 0; var reportFailures = 0; var rightmostFailuresPos = 0; var rightmostFailuresExpected = []; function padLeft(input, padding, length) { var result = input; var padLength = length - input.length; for (var i = 0; i < padLength; i++) { result = padding + result; } return result; } function escape(ch) { var charCode = ch.charCodeAt(0); var escapeChar; var length; if (charCode <= 0xFF) { escapeChar = 'x'; length = 2; } else { escapeChar = 'u'; length = 4; } return '\\' + escapeChar + padLeft(charCode.toString(16).toUpperCase(), '0', length); } function matchFailed(failure) { if (pos < rightmostFailuresPos) { return; } if (pos > rightmostFailuresPos) { rightmostFailuresPos = pos; rightmostFailuresExpected = []; } rightmostFailuresExpected.push(failure); } function parse_CRLF() { var result0; if (input.substr(pos, 2) === "\r\n") { result0 = "\r\n"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"\\r\\n\""); } } return result0; } function parse_DIGIT() { var result0; if (/^[0-9]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[0-9]"); } } return result0; } function parse_ALPHA() { var result0; if (/^[a-zA-Z]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[a-zA-Z]"); } } return result0; } function parse_HEXDIG() { var result0; if (/^[0-9a-fA-F]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[0-9a-fA-F]"); } } return result0; } function parse_WSP() { var result0; result0 = parse_SP(); if (result0 === null) { result0 = parse_HTAB(); } return result0; } function parse_OCTET() { var result0; if (/^[\0-\xFF]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[\\0-\\xFF]"); } } return result0; } function parse_DQUOTE() { var result0; if (/^["]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[\"]"); } } return result0; } function parse_SP() { var result0; if (input.charCodeAt(pos) === 32) { result0 = " "; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\" \""); } } return result0; } function parse_HTAB() { var result0; if (input.charCodeAt(pos) === 9) { result0 = "\t"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"\\t\""); } } return result0; } function parse_alphanum() { var result0; if (/^[a-zA-Z0-9]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[a-zA-Z0-9]"); } } return result0; } function parse_reserved() { var result0; if (input.charCodeAt(pos) === 59) { result0 = ";"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 47) { result0 = "/"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 63) { result0 = "?"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 58) { result0 = ":"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 64) { result0 = "@"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 38) { result0 = "&"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 61) { result0 = "="; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 43) { result0 = "+"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 36) { result0 = "$"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 44) { result0 = ","; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\",\""); } } } } } } } } } } } return result0; } function parse_unreserved() { var result0; result0 = parse_alphanum(); if (result0 === null) { result0 = parse_mark(); } return result0; } function parse_mark() { var result0; if (input.charCodeAt(pos) === 45) { result0 = "-"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 95) { result0 = "_"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 46) { result0 = "."; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 33) { result0 = "!"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"!\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 126) { result0 = "~"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"~\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 42) { result0 = "*"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"*\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 39) { result0 = "'"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"'\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 40) { result0 = "("; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"(\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 41) { result0 = ")"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\")\""); } } } } } } } } } } return result0; } function parse_escaped() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.charCodeAt(pos) === 37) { result0 = "%"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"%\""); } } if (result0 !== null) { result1 = parse_HEXDIG(); if (result1 !== null) { result2 = parse_HEXDIG(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, escaped) {return escaped.join(''); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_LWS() { var result0, result1, result2; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; pos2 = pos; result0 = []; result1 = parse_WSP(); while (result1 !== null) { result0.push(result1); result1 = parse_WSP(); } if (result0 !== null) { result1 = parse_CRLF(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos2; } } else { result0 = null; pos = pos2; } result0 = result0 !== null ? result0 : ""; if (result0 !== null) { result2 = parse_WSP(); if (result2 !== null) { result1 = []; while (result2 !== null) { result1.push(result2); result2 = parse_WSP(); } } else { result1 = null; } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return " "; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_SWS() { var result0; result0 = parse_LWS(); result0 = result0 !== null ? result0 : ""; return result0; } function parse_HCOLON() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = []; result1 = parse_SP(); if (result1 === null) { result1 = parse_HTAB(); } while (result1 !== null) { result0.push(result1); result1 = parse_SP(); if (result1 === null) { result1 = parse_HTAB(); } } if (result0 !== null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return ':'; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_TEXT_UTF8_TRIM() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result1 = parse_TEXT_UTF8char(); if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_TEXT_UTF8char(); } } else { result0 = null; } if (result0 !== null) { result1 = []; pos2 = pos; result2 = []; result3 = parse_LWS(); while (result3 !== null) { result2.push(result3); result3 = parse_LWS(); } if (result2 !== null) { result3 = parse_TEXT_UTF8char(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = []; result3 = parse_LWS(); while (result3 !== null) { result2.push(result3); result3 = parse_LWS(); } if (result2 !== null) { result3 = parse_TEXT_UTF8char(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_TEXT_UTF8char() { var result0; if (/^[!-~]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[!-~]"); } } if (result0 === null) { result0 = parse_UTF8_NONASCII(); } return result0; } function parse_UTF8_NONASCII() { var result0; if (/^[\x80-\uFFFF]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[\\x80-\\uFFFF]"); } } return result0; } function parse_UTF8_CONT() { var result0; if (/^[\x80-\xBF]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[\\x80-\\xBF]"); } } return result0; } function parse_LHEX() { var result0; result0 = parse_DIGIT(); if (result0 === null) { if (/^[a-f]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[a-f]"); } } } return result0; } function parse_token() { var result0, result1; var pos0; pos0 = pos; result1 = parse_alphanum(); if (result1 === null) { if (input.charCodeAt(pos) === 45) { result1 = "-"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 46) { result1 = "."; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 33) { result1 = "!"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"!\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 37) { result1 = "%"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"%\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 42) { result1 = "*"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"*\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 95) { result1 = "_"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 96) { result1 = "`"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"`\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 39) { result1 = "'"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"'\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 126) { result1 = "~"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"~\""); } } } } } } } } } } } } if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_alphanum(); if (result1 === null) { if (input.charCodeAt(pos) === 45) { result1 = "-"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 46) { result1 = "."; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 33) { result1 = "!"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"!\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 37) { result1 = "%"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"%\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 42) { result1 = "*"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"*\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 95) { result1 = "_"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 96) { result1 = "`"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"`\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 39) { result1 = "'"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"'\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 126) { result1 = "~"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"~\""); } } } } } } } } } } } } } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset) { return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_token_nodot() { var result0, result1; var pos0; pos0 = pos; result1 = parse_alphanum(); if (result1 === null) { if (input.charCodeAt(pos) === 45) { result1 = "-"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 33) { result1 = "!"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"!\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 37) { result1 = "%"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"%\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 42) { result1 = "*"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"*\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 95) { result1 = "_"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 96) { result1 = "`"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"`\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 39) { result1 = "'"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"'\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 126) { result1 = "~"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"~\""); } } } } } } } } } } } if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_alphanum(); if (result1 === null) { if (input.charCodeAt(pos) === 45) { result1 = "-"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 33) { result1 = "!"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"!\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 37) { result1 = "%"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"%\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 42) { result1 = "*"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"*\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 95) { result1 = "_"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 96) { result1 = "`"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"`\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 39) { result1 = "'"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"'\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 126) { result1 = "~"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"~\""); } } } } } } } } } } } } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset) { return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_separators() { var result0; if (input.charCodeAt(pos) === 40) { result0 = "("; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"(\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 41) { result0 = ")"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\")\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 60) { result0 = "<"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"<\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 62) { result0 = ">"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\">\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 64) { result0 = "@"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 44) { result0 = ","; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\",\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 59) { result0 = ";"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 58) { result0 = ":"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 92) { result0 = "\\"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"\\\\\""); } } if (result0 === null) { result0 = parse_DQUOTE(); if (result0 === null) { if (input.charCodeAt(pos) === 47) { result0 = "/"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 91) { result0 = "["; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"[\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 93) { result0 = "]"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"]\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 63) { result0 = "?"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 61) { result0 = "="; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 123) { result0 = "{"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"{\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 125) { result0 = "}"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"}\""); } } if (result0 === null) { result0 = parse_SP(); if (result0 === null) { result0 = parse_HTAB(); } } } } } } } } } } } } } } } } } } return result0; } function parse_word() { var result0, result1; var pos0; pos0 = pos; result1 = parse_alphanum(); if (result1 === null) { if (input.charCodeAt(pos) === 45) { result1 = "-"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 46) { result1 = "."; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 33) { result1 = "!"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"!\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 37) { result1 = "%"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"%\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 42) { result1 = "*"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"*\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 95) { result1 = "_"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 96) { result1 = "`"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"`\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 39) { result1 = "'"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"'\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 126) { result1 = "~"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"~\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 40) { result1 = "("; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"(\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 41) { result1 = ")"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\")\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 60) { result1 = "<"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"<\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 62) { result1 = ">"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\">\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 92) { result1 = "\\"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"\\\\\""); } } if (result1 === null) { result1 = parse_DQUOTE(); if (result1 === null) { if (input.charCodeAt(pos) === 47) { result1 = "/"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 91) { result1 = "["; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"[\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 93) { result1 = "]"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"]\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 63) { result1 = "?"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 123) { result1 = "{"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"{\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 125) { result1 = "}"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"}\""); } } } } } } } } } } } } } } } } } } } } } } } } } if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_alphanum(); if (result1 === null) { if (input.charCodeAt(pos) === 45) { result1 = "-"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 46) { result1 = "."; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 33) { result1 = "!"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"!\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 37) { result1 = "%"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"%\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 42) { result1 = "*"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"*\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 95) { result1 = "_"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 96) { result1 = "`"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"`\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 39) { result1 = "'"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"'\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 126) { result1 = "~"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"~\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 40) { result1 = "("; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"(\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 41) { result1 = ")"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\")\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 60) { result1 = "<"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"<\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 62) { result1 = ">"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\">\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 92) { result1 = "\\"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"\\\\\""); } } if (result1 === null) { result1 = parse_DQUOTE(); if (result1 === null) { if (input.charCodeAt(pos) === 47) { result1 = "/"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 91) { result1 = "["; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"[\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 93) { result1 = "]"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"]\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 63) { result1 = "?"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 123) { result1 = "{"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"{\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 125) { result1 = "}"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"}\""); } } } } } } } } } } } } } } } } } } } } } } } } } } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset) { return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_STAR() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 42) { result1 = "*"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"*\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return "*"; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_SLASH() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 47) { result1 = "/"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return "/"; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_EQUAL() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 61) { result1 = "="; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return "="; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_LPAREN() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 40) { result1 = "("; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"(\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return "("; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_RPAREN() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 41) { result1 = ")"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\")\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return ")"; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_RAQUOT() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.charCodeAt(pos) === 62) { result0 = ">"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\">\""); } } if (result0 !== null) { result1 = parse_SWS(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return ">"; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_LAQUOT() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 60) { result1 = "<"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"<\""); } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return "<"; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_COMMA() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 44) { result1 = ","; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\",\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return ","; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_SEMI() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 59) { result1 = ";"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return ";"; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_COLON() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return ":"; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_LDQUOT() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { result1 = parse_DQUOTE(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return "\""; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_RDQUOT() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_DQUOTE(); if (result0 !== null) { result1 = parse_SWS(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return "\""; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_comment() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_LPAREN(); if (result0 !== null) { result1 = []; result2 = parse_ctext(); if (result2 === null) { result2 = parse_quoted_pair(); if (result2 === null) { result2 = parse_comment(); } } while (result2 !== null) { result1.push(result2); result2 = parse_ctext(); if (result2 === null) { result2 = parse_quoted_pair(); if (result2 === null) { result2 = parse_comment(); } } } if (result1 !== null) { result2 = parse_RPAREN(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_ctext() { var result0; if (/^[!-']/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[!-']"); } } if (result0 === null) { if (/^[*-[]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[*-[]"); } } if (result0 === null) { if (/^[\]-~]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[\\]-~]"); } } if (result0 === null) { result0 = parse_UTF8_NONASCII(); if (result0 === null) { result0 = parse_LWS(); } } } } return result0; } function parse_quoted_string() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { result1 = parse_DQUOTE(); if (result1 !== null) { result2 = []; result3 = parse_qdtext(); if (result3 === null) { result3 = parse_quoted_pair(); } while (result3 !== null) { result2.push(result3); result3 = parse_qdtext(); if (result3 === null) { result3 = parse_quoted_pair(); } } if (result2 !== null) { result3 = parse_DQUOTE(); if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_quoted_string_clean() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { result1 = parse_DQUOTE(); if (result1 !== null) { result2 = []; result3 = parse_qdtext(); if (result3 === null) { result3 = parse_quoted_pair(); } while (result3 !== null) { result2.push(result3); result3 = parse_qdtext(); if (result3 === null) { result3 = parse_quoted_pair(); } } if (result2 !== null) { result3 = parse_DQUOTE(); if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { return input.substring(pos-1, offset+1); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_qdtext() { var result0; result0 = parse_LWS(); if (result0 === null) { if (input.charCodeAt(pos) === 33) { result0 = "!"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"!\""); } } if (result0 === null) { if (/^[#-[]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[#-[]"); } } if (result0 === null) { if (/^[\]-~]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[\\]-~]"); } } if (result0 === null) { result0 = parse_UTF8_NONASCII(); } } } } return result0; } function parse_quoted_pair() { var result0, result1; var pos0; pos0 = pos; if (input.charCodeAt(pos) === 92) { result0 = "\\"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"\\\\\""); } } if (result0 !== null) { if (/^[\0-\t]/.test(input.charAt(pos))) { result1 = input.charAt(pos); pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("[\\0-\\t]"); } } if (result1 === null) { if (/^[\x0B-\f]/.test(input.charAt(pos))) { result1 = input.charAt(pos); pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("[\\x0B-\\f]"); } } if (result1 === null) { if (/^[\x0E-]/.test(input.charAt(pos))) { result1 = input.charAt(pos); pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("[\\x0E-]"); } } } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_SIP_URI_noparams() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_uri_scheme(); if (result0 !== null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_userinfo(); result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result3 = parse_hostport(); if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { try { data.uri = new URI(data.scheme, data.user, data.host, data.port); delete data.scheme; delete data.user; delete data.host; delete data.host_type; delete data.port; } catch(e) { data = -1; }})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_SIP_URI() { var result0, result1, result2, result3, result4, result5; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_uri_scheme(); if (result0 !== null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_userinfo(); result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result3 = parse_hostport(); if (result3 !== null) { result4 = parse_uri_parameters(); if (result4 !== null) { result5 = parse_headers(); result5 = result5 !== null ? result5 : ""; if (result5 !== null) { result0 = [result0, result1, result2, result3, result4, result5]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { var header; try { data.uri = new URI(data.scheme, data.user, data.host, data.port, data.uri_params, data.uri_headers); delete data.scheme; delete data.user; delete data.host; delete data.host_type; delete data.port; delete data.uri_params; if (startRule === 'SIP_URI') { data = data.uri;} } catch(e) { data = -1; }})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_uri_scheme() { var result0; result0 = parse_uri_scheme_sips(); if (result0 === null) { result0 = parse_uri_scheme_sip(); } return result0; } function parse_uri_scheme_sips() { var result0; var pos0; pos0 = pos; if (input.substr(pos, 4).toLowerCase() === "sips") { result0 = input.substr(pos, 4); pos += 4; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"sips\""); } } if (result0 !== null) { result0 = (function(offset, scheme) { data.scheme = scheme.toLowerCase(); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_uri_scheme_sip() { var result0; var pos0; pos0 = pos; if (input.substr(pos, 3).toLowerCase() === "sip") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"sip\""); } } if (result0 !== null) { result0 = (function(offset, scheme) { data.scheme = scheme.toLowerCase(); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_userinfo() { var result0, result1, result2; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_user(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_password(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { if (input.charCodeAt(pos) === 64) { result2 = "@"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { data.user = decodeURIComponent(input.substring(pos-1, offset));})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_user() { var result0, result1; result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); if (result1 === null) { result1 = parse_user_unreserved(); } } if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); if (result1 === null) { result1 = parse_user_unreserved(); } } } } else { result0 = null; } return result0; } function parse_user_unreserved() { var result0; if (input.charCodeAt(pos) === 38) { result0 = "&"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 61) { result0 = "="; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 43) { result0 = "+"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 36) { result0 = "$"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 44) { result0 = ","; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\",\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 59) { result0 = ";"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 63) { result0 = "?"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 47) { result0 = "/"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } } } } } } } } return result0; } function parse_password() { var result0, result1; var pos0; pos0 = pos; result0 = []; result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); if (result1 === null) { if (input.charCodeAt(pos) === 38) { result1 = "&"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 61) { result1 = "="; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 36) { result1 = "$"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 44) { result1 = ","; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\",\""); } } } } } } } } while (result1 !== null) { result0.push(result1); result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); if (result1 === null) { if (input.charCodeAt(pos) === 38) { result1 = "&"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 61) { result1 = "="; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 36) { result1 = "$"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 44) { result1 = ","; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\",\""); } } } } } } } } } if (result0 !== null) { result0 = (function(offset) { data.password = input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_hostport() { var result0, result1, result2; var pos0, pos1; pos0 = pos; result0 = parse_host(); if (result0 !== null) { pos1 = pos; if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_port(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos1; } } else { result1 = null; pos = pos1; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_host() { var result0; var pos0; pos0 = pos; result0 = parse_hostname(); if (result0 === null) { result0 = parse_IPv4address(); if (result0 === null) { result0 = parse_IPv6reference(); } } if (result0 !== null) { result0 = (function(offset) { data.host = input.substring(pos, offset).toLowerCase(); return data.host; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_hostname() { var result0, result1, result2; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = []; pos2 = pos; result1 = parse_domainlabel(); if (result1 !== null) { if (input.charCodeAt(pos) === 46) { result2 = "."; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } while (result1 !== null) { result0.push(result1); pos2 = pos; result1 = parse_domainlabel(); if (result1 !== null) { if (input.charCodeAt(pos) === 46) { result2 = "."; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } } if (result0 !== null) { result1 = parse_toplabel(); if (result1 !== null) { if (input.charCodeAt(pos) === 46) { result2 = "."; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\".\""); } } result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { data.host_type = 'domain'; return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_domainlabel() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_alphanum(); if (result0 !== null) { result1 = []; result2 = parse_alphanum(); if (result2 === null) { if (input.charCodeAt(pos) === 45) { result2 = "-"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result2 === null) { if (input.charCodeAt(pos) === 95) { result2 = "_"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } } } while (result2 !== null) { result1.push(result2); result2 = parse_alphanum(); if (result2 === null) { if (input.charCodeAt(pos) === 45) { result2 = "-"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result2 === null) { if (input.charCodeAt(pos) === 95) { result2 = "_"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } } } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_toplabel() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_ALPHA(); if (result0 !== null) { result1 = []; result2 = parse_alphanum(); if (result2 === null) { if (input.charCodeAt(pos) === 45) { result2 = "-"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result2 === null) { if (input.charCodeAt(pos) === 95) { result2 = "_"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } } } while (result2 !== null) { result1.push(result2); result2 = parse_alphanum(); if (result2 === null) { if (input.charCodeAt(pos) === 45) { result2 = "-"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result2 === null) { if (input.charCodeAt(pos) === 95) { result2 = "_"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } } } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_IPv6reference() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.charCodeAt(pos) === 91) { result0 = "["; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"[\""); } } if (result0 !== null) { result1 = parse_IPv6address(); if (result1 !== null) { if (input.charCodeAt(pos) === 93) { result2 = "]"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"]\""); } } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { data.host_type = 'IPv6'; return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_IPv6address() { var result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11, result12; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_h16(); if (result0 !== null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { if (input.charCodeAt(pos) === 58) { result3 = ":"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result3 !== null) { result4 = parse_h16(); if (result4 !== null) { if (input.charCodeAt(pos) === 58) { result5 = ":"; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result5 !== null) { result6 = parse_h16(); if (result6 !== null) { if (input.charCodeAt(pos) === 58) { result7 = ":"; pos++; } else { result7 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result7 !== null) { result8 = parse_h16(); if (result8 !== null) { if (input.charCodeAt(pos) === 58) { result9 = ":"; pos++; } else { result9 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result9 !== null) { result10 = parse_h16(); if (result10 !== null) { if (input.charCodeAt(pos) === 58) { result11 = ":"; pos++; } else { result11 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result11 !== null) { result12 = parse_ls32(); if (result12 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11, result12]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; if (input.substr(pos, 2) === "::") { result0 = "::"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result0 !== null) { result1 = parse_h16(); if (result1 !== null) { if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { if (input.charCodeAt(pos) === 58) { result4 = ":"; pos++; } else { result4 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result4 !== null) { result5 = parse_h16(); if (result5 !== null) { if (input.charCodeAt(pos) === 58) { result6 = ":"; pos++; } else { result6 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result6 !== null) { result7 = parse_h16(); if (result7 !== null) { if (input.charCodeAt(pos) === 58) { result8 = ":"; pos++; } else { result8 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result8 !== null) { result9 = parse_h16(); if (result9 !== null) { if (input.charCodeAt(pos) === 58) { result10 = ":"; pos++; } else { result10 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result10 !== null) { result11 = parse_ls32(); if (result11 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; if (input.substr(pos, 2) === "::") { result0 = "::"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result0 !== null) { result1 = parse_h16(); if (result1 !== null) { if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { if (input.charCodeAt(pos) === 58) { result4 = ":"; pos++; } else { result4 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result4 !== null) { result5 = parse_h16(); if (result5 !== null) { if (input.charCodeAt(pos) === 58) { result6 = ":"; pos++; } else { result6 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result6 !== null) { result7 = parse_h16(); if (result7 !== null) { if (input.charCodeAt(pos) === 58) { result8 = ":"; pos++; } else { result8 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result8 !== null) { result9 = parse_ls32(); if (result9 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; if (input.substr(pos, 2) === "::") { result0 = "::"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result0 !== null) { result1 = parse_h16(); if (result1 !== null) { if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { if (input.charCodeAt(pos) === 58) { result4 = ":"; pos++; } else { result4 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result4 !== null) { result5 = parse_h16(); if (result5 !== null) { if (input.charCodeAt(pos) === 58) { result6 = ":"; pos++; } else { result6 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result6 !== null) { result7 = parse_ls32(); if (result7 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; if (input.substr(pos, 2) === "::") { result0 = "::"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result0 !== null) { result1 = parse_h16(); if (result1 !== null) { if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { if (input.charCodeAt(pos) === 58) { result4 = ":"; pos++; } else { result4 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result4 !== null) { result5 = parse_ls32(); if (result5 !== null) { result0 = [result0, result1, result2, result3, result4, result5]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; if (input.substr(pos, 2) === "::") { result0 = "::"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result0 !== null) { result1 = parse_h16(); if (result1 !== null) { if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_ls32(); if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; if (input.substr(pos, 2) === "::") { result0 = "::"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result0 !== null) { result1 = parse_ls32(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; if (input.substr(pos, 2) === "::") { result0 = "::"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result0 !== null) { result1 = parse_h16(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; result0 = parse_h16(); if (result0 !== null) { if (input.substr(pos, 2) === "::") { result1 = "::"; pos += 2; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { if (input.charCodeAt(pos) === 58) { result3 = ":"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result3 !== null) { result4 = parse_h16(); if (result4 !== null) { if (input.charCodeAt(pos) === 58) { result5 = ":"; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result5 !== null) { result6 = parse_h16(); if (result6 !== null) { if (input.charCodeAt(pos) === 58) { result7 = ":"; pos++; } else { result7 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result7 !== null) { result8 = parse_h16(); if (result8 !== null) { if (input.charCodeAt(pos) === 58) { result9 = ":"; pos++; } else { result9 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result9 !== null) { result10 = parse_ls32(); if (result10 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; result0 = parse_h16(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { if (input.substr(pos, 2) === "::") { result2 = "::"; pos += 2; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { if (input.charCodeAt(pos) === 58) { result4 = ":"; pos++; } else { result4 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result4 !== null) { result5 = parse_h16(); if (result5 !== null) { if (input.charCodeAt(pos) === 58) { result6 = ":"; pos++; } else { result6 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result6 !== null) { result7 = parse_h16(); if (result7 !== null) { if (input.charCodeAt(pos) === 58) { result8 = ":"; pos++; } else { result8 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result8 !== null) { result9 = parse_ls32(); if (result9 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; result0 = parse_h16(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } result2 = result2 !== null ? result2 : ""; if (result2 !== null) { if (input.substr(pos, 2) === "::") { result3 = "::"; pos += 2; } else { result3 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result3 !== null) { result4 = parse_h16(); if (result4 !== null) { if (input.charCodeAt(pos) === 58) { result5 = ":"; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result5 !== null) { result6 = parse_h16(); if (result6 !== null) { if (input.charCodeAt(pos) === 58) { result7 = ":"; pos++; } else { result7 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result7 !== null) { result8 = parse_ls32(); if (result8 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; result0 = parse_h16(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } result2 = result2 !== null ? result2 : ""; if (result2 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result3 = ":"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result3 !== null) { result4 = parse_h16(); if (result4 !== null) { result3 = [result3, result4]; } else { result3 = null; pos = pos2; } } else { result3 = null; pos = pos2; } result3 = result3 !== null ? result3 : ""; if (result3 !== null) { if (input.substr(pos, 2) === "::") { result4 = "::"; pos += 2; } else { result4 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result4 !== null) { result5 = parse_h16(); if (result5 !== null) { if (input.charCodeAt(pos) === 58) { result6 = ":"; pos++; } else { result6 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result6 !== null) { result7 = parse_ls32(); if (result7 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; result0 = parse_h16(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } result2 = result2 !== null ? result2 : ""; if (result2 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result3 = ":"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result3 !== null) { result4 = parse_h16(); if (result4 !== null) { result3 = [result3, result4]; } else { result3 = null; pos = pos2; } } else { result3 = null; pos = pos2; } result3 = result3 !== null ? result3 : ""; if (result3 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result4 = ":"; pos++; } else { result4 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result4 !== null) { result5 = parse_h16(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos2; } } else { result4 = null; pos = pos2; } result4 = result4 !== null ? result4 : ""; if (result4 !== null) { if (input.substr(pos, 2) === "::") { result5 = "::"; pos += 2; } else { result5 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result5 !== null) { result6 = parse_ls32(); if (result6 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; result0 = parse_h16(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } result2 = result2 !== null ? result2 : ""; if (result2 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result3 = ":"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result3 !== null) { result4 = parse_h16(); if (result4 !== null) { result3 = [result3, result4]; } else { result3 = null; pos = pos2; } } else { result3 = null; pos = pos2; } result3 = result3 !== null ? result3 : ""; if (result3 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result4 = ":"; pos++; } else { result4 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result4 !== null) { result5 = parse_h16(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos2; } } else { result4 = null; pos = pos2; } result4 = result4 !== null ? result4 : ""; if (result4 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result5 = ":"; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result5 !== null) { result6 = parse_h16(); if (result6 !== null) { result5 = [result5, result6]; } else { result5 = null; pos = pos2; } } else { result5 = null; pos = pos2; } result5 = result5 !== null ? result5 : ""; if (result5 !== null) { if (input.substr(pos, 2) === "::") { result6 = "::"; pos += 2; } else { result6 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result6 !== null) { result7 = parse_h16(); if (result7 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; result0 = parse_h16(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } result2 = result2 !== null ? result2 : ""; if (result2 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result3 = ":"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result3 !== null) { result4 = parse_h16(); if (result4 !== null) { result3 = [result3, result4]; } else { result3 = null; pos = pos2; } } else { result3 = null; pos = pos2; } result3 = result3 !== null ? result3 : ""; if (result3 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result4 = ":"; pos++; } else { result4 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result4 !== null) { result5 = parse_h16(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos2; } } else { result4 = null; pos = pos2; } result4 = result4 !== null ? result4 : ""; if (result4 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result5 = ":"; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result5 !== null) { result6 = parse_h16(); if (result6 !== null) { result5 = [result5, result6]; } else { result5 = null; pos = pos2; } } else { result5 = null; pos = pos2; } result5 = result5 !== null ? result5 : ""; if (result5 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result6 = ":"; pos++; } else { result6 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result6 !== null) { result7 = parse_h16(); if (result7 !== null) { result6 = [result6, result7]; } else { result6 = null; pos = pos2; } } else { result6 = null; pos = pos2; } result6 = result6 !== null ? result6 : ""; if (result6 !== null) { if (input.substr(pos, 2) === "::") { result7 = "::"; pos += 2; } else { result7 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result7 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } } } } } } } } } } } } } } if (result0 !== null) { result0 = (function(offset) { data.host_type = 'IPv6'; return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_h16() { var result0, result1, result2, result3; var pos0; pos0 = pos; result0 = parse_HEXDIG(); if (result0 !== null) { result1 = parse_HEXDIG(); result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result2 = parse_HEXDIG(); result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result3 = parse_HEXDIG(); result3 = result3 !== null ? result3 : ""; if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_ls32() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_h16(); if (result0 !== null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } if (result0 === null) { result0 = parse_IPv4address(); } return result0; } function parse_IPv4address() { var result0, result1, result2, result3, result4, result5, result6; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_dec_octet(); if (result0 !== null) { if (input.charCodeAt(pos) === 46) { result1 = "."; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result1 !== null) { result2 = parse_dec_octet(); if (result2 !== null) { if (input.charCodeAt(pos) === 46) { result3 = "."; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result3 !== null) { result4 = parse_dec_octet(); if (result4 !== null) { if (input.charCodeAt(pos) === 46) { result5 = "."; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result5 !== null) { result6 = parse_dec_octet(); if (result6 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { data.host_type = 'IPv4'; return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_dec_octet() { var result0, result1, result2; var pos0; pos0 = pos; if (input.substr(pos, 2) === "25") { result0 = "25"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"25\""); } } if (result0 !== null) { if (/^[0-5]/.test(input.charAt(pos))) { result1 = input.charAt(pos); pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("[0-5]"); } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } if (result0 === null) { pos0 = pos; if (input.charCodeAt(pos) === 50) { result0 = "2"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"2\""); } } if (result0 !== null) { if (/^[0-4]/.test(input.charAt(pos))) { result1 = input.charAt(pos); pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("[0-4]"); } } if (result1 !== null) { result2 = parse_DIGIT(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } if (result0 === null) { pos0 = pos; if (input.charCodeAt(pos) === 49) { result0 = "1"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"1\""); } } if (result0 !== null) { result1 = parse_DIGIT(); if (result1 !== null) { result2 = parse_DIGIT(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } if (result0 === null) { pos0 = pos; if (/^[1-9]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[1-9]"); } } if (result0 !== null) { result1 = parse_DIGIT(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } if (result0 === null) { result0 = parse_DIGIT(); } } } } return result0; } function parse_port() { var result0, result1, result2, result3, result4; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_DIGIT(); result0 = result0 !== null ? result0 : ""; if (result0 !== null) { result1 = parse_DIGIT(); result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result2 = parse_DIGIT(); result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result3 = parse_DIGIT(); result3 = result3 !== null ? result3 : ""; if (result3 !== null) { result4 = parse_DIGIT(); result4 = result4 !== null ? result4 : ""; if (result4 !== null) { result0 = [result0, result1, result2, result3, result4]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, port) { port = parseInt(port.join('')); data.port = port; return port; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_uri_parameters() { var result0, result1, result2; var pos0; result0 = []; pos0 = pos; if (input.charCodeAt(pos) === 59) { result1 = ";"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result1 !== null) { result2 = parse_uri_parameter(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos0; } } else { result1 = null; pos = pos0; } while (result1 !== null) { result0.push(result1); pos0 = pos; if (input.charCodeAt(pos) === 59) { result1 = ";"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result1 !== null) { result2 = parse_uri_parameter(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos0; } } else { result1 = null; pos = pos0; } } return result0; } function parse_uri_parameter() { var result0; result0 = parse_transport_param(); if (result0 === null) { result0 = parse_user_param(); if (result0 === null) { result0 = parse_method_param(); if (result0 === null) { result0 = parse_ttl_param(); if (result0 === null) { result0 = parse_maddr_param(); if (result0 === null) { result0 = parse_lr_param(); if (result0 === null) { result0 = parse_other_param(); } } } } } } return result0; } function parse_transport_param() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 10).toLowerCase() === "transport=") { result0 = input.substr(pos, 10); pos += 10; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"transport=\""); } } if (result0 !== null) { if (input.substr(pos, 3).toLowerCase() === "udp") { result1 = input.substr(pos, 3); pos += 3; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"udp\""); } } if (result1 === null) { if (input.substr(pos, 3).toLowerCase() === "tcp") { result1 = input.substr(pos, 3); pos += 3; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"tcp\""); } } if (result1 === null) { if (input.substr(pos, 4).toLowerCase() === "sctp") { result1 = input.substr(pos, 4); pos += 4; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"sctp\""); } } if (result1 === null) { if (input.substr(pos, 3).toLowerCase() === "tls") { result1 = input.substr(pos, 3); pos += 3; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"tls\""); } } if (result1 === null) { result1 = parse_token(); } } } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, transport) { if(!data.uri_params) data.uri_params={}; data.uri_params['transport'] = transport.toLowerCase(); })(pos0, result0[1]); } if (result0 === null) { pos = pos0; } return result0; } function parse_user_param() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 5).toLowerCase() === "user=") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"user=\""); } } if (result0 !== null) { if (input.substr(pos, 5).toLowerCase() === "phone") { result1 = input.substr(pos, 5); pos += 5; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"phone\""); } } if (result1 === null) { if (input.substr(pos, 2).toLowerCase() === "ip") { result1 = input.substr(pos, 2); pos += 2; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"ip\""); } } if (result1 === null) { result1 = parse_token(); } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, user) { if(!data.uri_params) data.uri_params={}; data.uri_params['user'] = user.toLowerCase(); })(pos0, result0[1]); } if (result0 === null) { pos = pos0; } return result0; } function parse_method_param() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 7).toLowerCase() === "method=") { result0 = input.substr(pos, 7); pos += 7; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"method=\""); } } if (result0 !== null) { result1 = parse_Method(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, method) { if(!data.uri_params) data.uri_params={}; data.uri_params['method'] = method; })(pos0, result0[1]); } if (result0 === null) { pos = pos0; } return result0; } function parse_ttl_param() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 4).toLowerCase() === "ttl=") { result0 = input.substr(pos, 4); pos += 4; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"ttl=\""); } } if (result0 !== null) { result1 = parse_ttl(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, ttl) { if(!data.params) data.params={}; data.params['ttl'] = ttl; })(pos0, result0[1]); } if (result0 === null) { pos = pos0; } return result0; } function parse_maddr_param() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 6).toLowerCase() === "maddr=") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"maddr=\""); } } if (result0 !== null) { result1 = parse_host(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, maddr) { if(!data.uri_params) data.uri_params={}; data.uri_params['maddr'] = maddr; })(pos0, result0[1]); } if (result0 === null) { pos = pos0; } return result0; } function parse_lr_param() { var result0, result1, result2; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; if (input.substr(pos, 2).toLowerCase() === "lr") { result0 = input.substr(pos, 2); pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"lr\""); } } if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 61) { result1 = "="; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result1 !== null) { result2 = parse_token(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { if(!data.uri_params) data.uri_params={}; data.uri_params['lr'] = undefined; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_other_param() { var result0, result1, result2; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_pname(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 61) { result1 = "="; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result1 !== null) { result2 = parse_pvalue(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, param, value) { if(!data.uri_params) data.uri_params = {}; if (typeof value === 'undefined'){ value = undefined; } else { value = value[1]; } data.uri_params[param.toLowerCase()] = value;})(pos0, result0[0], result0[1]); } if (result0 === null) { pos = pos0; } return result0; } function parse_pname() { var result0, result1; var pos0; pos0 = pos; result1 = parse_paramchar(); if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_paramchar(); } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset, pname) {return pname.join(''); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_pvalue() { var result0, result1; var pos0; pos0 = pos; result1 = parse_paramchar(); if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_paramchar(); } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset, pvalue) {return pvalue.join(''); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_paramchar() { var result0; result0 = parse_param_unreserved(); if (result0 === null) { result0 = parse_unreserved(); if (result0 === null) { result0 = parse_escaped(); } } return result0; } function parse_param_unreserved() { var result0; if (input.charCodeAt(pos) === 91) { result0 = "["; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"[\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 93) { result0 = "]"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"]\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 47) { result0 = "/"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 58) { result0 = ":"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 38) { result0 = "&"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 43) { result0 = "+"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 36) { result0 = "$"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } } } } } } } return result0; } function parse_headers() { var result0, result1, result2, result3, result4; var pos0, pos1; pos0 = pos; if (input.charCodeAt(pos) === 63) { result0 = "?"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result0 !== null) { result1 = parse_header(); if (result1 !== null) { result2 = []; pos1 = pos; if (input.charCodeAt(pos) === 38) { result3 = "&"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result3 !== null) { result4 = parse_header(); if (result4 !== null) { result3 = [result3, result4]; } else { result3 = null; pos = pos1; } } else { result3 = null; pos = pos1; } while (result3 !== null) { result2.push(result3); pos1 = pos; if (input.charCodeAt(pos) === 38) { result3 = "&"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result3 !== null) { result4 = parse_header(); if (result4 !== null) { result3 = [result3, result4]; } else { result3 = null; pos = pos1; } } else { result3 = null; pos = pos1; } } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_header() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_hname(); if (result0 !== null) { if (input.charCodeAt(pos) === 61) { result1 = "="; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result1 !== null) { result2 = parse_hvalue(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, hname, hvalue) { hname = hname.join('').toLowerCase(); hvalue = hvalue.join(''); if(!data.uri_headers) data.uri_headers = {}; if (!data.uri_headers[hname]) { data.uri_headers[hname] = [hvalue]; } else { data.uri_headers[hname].push(hvalue); }})(pos0, result0[0], result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_hname() { var result0, result1; result1 = parse_hnv_unreserved(); if (result1 === null) { result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); } } if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_hnv_unreserved(); if (result1 === null) { result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); } } } } else { result0 = null; } return result0; } function parse_hvalue() { var result0, result1; result0 = []; result1 = parse_hnv_unreserved(); if (result1 === null) { result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); } } while (result1 !== null) { result0.push(result1); result1 = parse_hnv_unreserved(); if (result1 === null) { result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); } } } return result0; } function parse_hnv_unreserved() { var result0; if (input.charCodeAt(pos) === 91) { result0 = "["; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"[\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 93) { result0 = "]"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"]\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 47) { result0 = "/"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 63) { result0 = "?"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 58) { result0 = ":"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 43) { result0 = "+"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 36) { result0 = "$"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } } } } } } } return result0; } function parse_Request_Response() { var result0; result0 = parse_Status_Line(); if (result0 === null) { result0 = parse_Request_Line(); } return result0; } function parse_Request_Line() { var result0, result1, result2, result3, result4; var pos0; pos0 = pos; result0 = parse_Method(); if (result0 !== null) { result1 = parse_SP(); if (result1 !== null) { result2 = parse_Request_URI(); if (result2 !== null) { result3 = parse_SP(); if (result3 !== null) { result4 = parse_SIP_Version(); if (result4 !== null) { result0 = [result0, result1, result2, result3, result4]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Request_URI() { var result0; result0 = parse_SIP_URI(); if (result0 === null) { result0 = parse_absoluteURI(); } return result0; } function parse_absoluteURI() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_scheme(); if (result0 !== null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_hier_part(); if (result2 === null) { result2 = parse_opaque_part(); } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_hier_part() { var result0, result1, result2; var pos0, pos1; pos0 = pos; result0 = parse_net_path(); if (result0 === null) { result0 = parse_abs_path(); } if (result0 !== null) { pos1 = pos; if (input.charCodeAt(pos) === 63) { result1 = "?"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result1 !== null) { result2 = parse_query(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos1; } } else { result1 = null; pos = pos1; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_net_path() { var result0, result1, result2; var pos0; pos0 = pos; if (input.substr(pos, 2) === "//") { result0 = "//"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"//\""); } } if (result0 !== null) { result1 = parse_authority(); if (result1 !== null) { result2 = parse_abs_path(); result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_abs_path() { var result0, result1; var pos0; pos0 = pos; if (input.charCodeAt(pos) === 47) { result0 = "/"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result0 !== null) { result1 = parse_path_segments(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_opaque_part() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_uric_no_slash(); if (result0 !== null) { result1 = []; result2 = parse_uric(); while (result2 !== null) { result1.push(result2); result2 = parse_uric(); } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_uric() { var result0; result0 = parse_reserved(); if (result0 === null) { result0 = parse_unreserved(); if (result0 === null) { result0 = parse_escaped(); } } return result0; } function parse_uric_no_slash() { var result0; result0 = parse_unreserved(); if (result0 === null) { result0 = parse_escaped(); if (result0 === null) { if (input.charCodeAt(pos) === 59) { result0 = ";"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 63) { result0 = "?"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 58) { result0 = ":"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 64) { result0 = "@"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 38) { result0 = "&"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 61) { result0 = "="; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 43) { result0 = "+"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 36) { result0 = "$"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 44) { result0 = ","; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\",\""); } } } } } } } } } } } } return result0; } function parse_path_segments() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_segment(); if (result0 !== null) { result1 = []; pos1 = pos; if (input.charCodeAt(pos) === 47) { result2 = "/"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result2 !== null) { result3 = parse_segment(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; if (input.charCodeAt(pos) === 47) { result2 = "/"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result2 !== null) { result3 = parse_segment(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_segment() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = []; result1 = parse_pchar(); while (result1 !== null) { result0.push(result1); result1 = parse_pchar(); } if (result0 !== null) { result1 = []; pos1 = pos; if (input.charCodeAt(pos) === 59) { result2 = ";"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result2 !== null) { result3 = parse_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; if (input.charCodeAt(pos) === 59) { result2 = ";"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result2 !== null) { result3 = parse_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_param() { var result0, result1; result0 = []; result1 = parse_pchar(); while (result1 !== null) { result0.push(result1); result1 = parse_pchar(); } return result0; } function parse_pchar() { var result0; result0 = parse_unreserved(); if (result0 === null) { result0 = parse_escaped(); if (result0 === null) { if (input.charCodeAt(pos) === 58) { result0 = ":"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 64) { result0 = "@"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 38) { result0 = "&"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 61) { result0 = "="; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 43) { result0 = "+"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 36) { result0 = "$"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 44) { result0 = ","; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\",\""); } } } } } } } } } } return result0; } function parse_scheme() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_ALPHA(); if (result0 !== null) { result1 = []; result2 = parse_ALPHA(); if (result2 === null) { result2 = parse_DIGIT(); if (result2 === null) { if (input.charCodeAt(pos) === 43) { result2 = "+"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result2 === null) { if (input.charCodeAt(pos) === 45) { result2 = "-"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result2 === null) { if (input.charCodeAt(pos) === 46) { result2 = "."; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\".\""); } } } } } } while (result2 !== null) { result1.push(result2); result2 = parse_ALPHA(); if (result2 === null) { result2 = parse_DIGIT(); if (result2 === null) { if (input.charCodeAt(pos) === 43) { result2 = "+"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result2 === null) { if (input.charCodeAt(pos) === 45) { result2 = "-"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result2 === null) { if (input.charCodeAt(pos) === 46) { result2 = "."; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\".\""); } } } } } } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { data.scheme= input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_authority() { var result0; result0 = parse_srvr(); if (result0 === null) { result0 = parse_reg_name(); } return result0; } function parse_srvr() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_userinfo(); if (result0 !== null) { if (input.charCodeAt(pos) === 64) { result1 = "@"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } result0 = result0 !== null ? result0 : ""; if (result0 !== null) { result1 = parse_hostport(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } result0 = result0 !== null ? result0 : ""; return result0; } function parse_reg_name() { var result0, result1; result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); if (result1 === null) { if (input.charCodeAt(pos) === 36) { result1 = "$"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 44) { result1 = ","; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\",\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 59) { result1 = ";"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 64) { result1 = "@"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 38) { result1 = "&"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 61) { result1 = "="; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } } } } } } } } } } if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); if (result1 === null) { if (input.charCodeAt(pos) === 36) { result1 = "$"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 44) { result1 = ","; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\",\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 59) { result1 = ";"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 64) { result1 = "@"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 38) { result1 = "&"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 61) { result1 = "="; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } } } } } } } } } } } } else { result0 = null; } return result0; } function parse_query() { var result0, result1; result0 = []; result1 = parse_uric(); while (result1 !== null) { result0.push(result1); result1 = parse_uric(); } return result0; } function parse_SIP_Version() { var result0, result1, result2, result3, result4, result5; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 3).toLowerCase() === "sip") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"SIP\""); } } if (result0 !== null) { if (input.charCodeAt(pos) === 47) { result1 = "/"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result1 !== null) { result3 = parse_DIGIT(); if (result3 !== null) { result2 = []; while (result3 !== null) { result2.push(result3); result3 = parse_DIGIT(); } } else { result2 = null; } if (result2 !== null) { if (input.charCodeAt(pos) === 46) { result3 = "."; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result3 !== null) { result5 = parse_DIGIT(); if (result5 !== null) { result4 = []; while (result5 !== null) { result4.push(result5); result5 = parse_DIGIT(); } } else { result4 = null; } if (result4 !== null) { result0 = [result0, result1, result2, result3, result4]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { data.sip_version = input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_INVITEm() { var result0; if (input.substr(pos, 6) === "INVITE") { result0 = "INVITE"; pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"INVITE\""); } } return result0; } function parse_ACKm() { var result0; if (input.substr(pos, 3) === "ACK") { result0 = "ACK"; pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"ACK\""); } } return result0; } function parse_OPTIONSm() { var result0; if (input.substr(pos, 7) === "OPTIONS") { result0 = "OPTIONS"; pos += 7; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"OPTIONS\""); } } return result0; } function parse_BYEm() { var result0; if (input.substr(pos, 3) === "BYE") { result0 = "BYE"; pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"BYE\""); } } return result0; } function parse_CANCELm() { var result0; if (input.substr(pos, 6) === "CANCEL") { result0 = "CANCEL"; pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"CANCEL\""); } } return result0; } function parse_REGISTERm() { var result0; if (input.substr(pos, 8) === "REGISTER") { result0 = "REGISTER"; pos += 8; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"REGISTER\""); } } return result0; } function parse_SUBSCRIBEm() { var result0; if (input.substr(pos, 9) === "SUBSCRIBE") { result0 = "SUBSCRIBE"; pos += 9; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"SUBSCRIBE\""); } } return result0; } function parse_NOTIFYm() { var result0; if (input.substr(pos, 6) === "NOTIFY") { result0 = "NOTIFY"; pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"NOTIFY\""); } } return result0; } function parse_REFERm() { var result0; if (input.substr(pos, 5) === "REFER") { result0 = "REFER"; pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"REFER\""); } } return result0; } function parse_Method() { var result0; var pos0; pos0 = pos; result0 = parse_INVITEm(); if (result0 === null) { result0 = parse_ACKm(); if (result0 === null) { result0 = parse_OPTIONSm(); if (result0 === null) { result0 = parse_BYEm(); if (result0 === null) { result0 = parse_CANCELm(); if (result0 === null) { result0 = parse_REGISTERm(); if (result0 === null) { result0 = parse_SUBSCRIBEm(); if (result0 === null) { result0 = parse_NOTIFYm(); if (result0 === null) { result0 = parse_REFERm(); if (result0 === null) { result0 = parse_token(); } } } } } } } } } if (result0 !== null) { result0 = (function(offset) { data.method = input.substring(pos, offset); return data.method; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Status_Line() { var result0, result1, result2, result3, result4; var pos0; pos0 = pos; result0 = parse_SIP_Version(); if (result0 !== null) { result1 = parse_SP(); if (result1 !== null) { result2 = parse_Status_Code(); if (result2 !== null) { result3 = parse_SP(); if (result3 !== null) { result4 = parse_Reason_Phrase(); if (result4 !== null) { result0 = [result0, result1, result2, result3, result4]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Status_Code() { var result0; var pos0; pos0 = pos; result0 = parse_extension_code(); if (result0 !== null) { result0 = (function(offset, status_code) { data.status_code = parseInt(status_code.join('')); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_extension_code() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_DIGIT(); if (result0 !== null) { result1 = parse_DIGIT(); if (result1 !== null) { result2 = parse_DIGIT(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Reason_Phrase() { var result0, result1; var pos0; pos0 = pos; result0 = []; result1 = parse_reserved(); if (result1 === null) { result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); if (result1 === null) { result1 = parse_UTF8_NONASCII(); if (result1 === null) { result1 = parse_UTF8_CONT(); if (result1 === null) { result1 = parse_SP(); if (result1 === null) { result1 = parse_HTAB(); } } } } } } while (result1 !== null) { result0.push(result1); result1 = parse_reserved(); if (result1 === null) { result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); if (result1 === null) { result1 = parse_UTF8_NONASCII(); if (result1 === null) { result1 = parse_UTF8_CONT(); if (result1 === null) { result1 = parse_SP(); if (result1 === null) { result1 = parse_HTAB(); } } } } } } } if (result0 !== null) { result0 = (function(offset) { data.reason_phrase = input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Allow_Events() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_event_type(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_event_type(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_event_type(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Call_ID() { var result0, result1, result2; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_word(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 64) { result1 = "@"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result1 !== null) { result2 = parse_word(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { data = input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Contact() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; result0 = parse_STAR(); if (result0 === null) { pos1 = pos; result0 = parse_contact_param(); if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_contact_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_contact_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } if (result0 !== null) { result0 = (function(offset) { var idx, length; length = data.multi_header.length; for (idx = 0; idx < length; idx++) { if (data.multi_header[idx].parsed === null) { data = null; break; } } if (data !== null) { data = data.multi_header; } else { data = -1; }})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_contact_param() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_SIP_URI_noparams(); if (result0 === null) { result0 = parse_name_addr(); } if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_contact_params(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_contact_params(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { var header; if(!data.multi_header) data.multi_header = []; try { header = new NameAddrHeader(data.uri, data.display_name, data.params); delete data.uri; delete data.display_name; delete data.params; } catch(e) { header = null; } data.multi_header.push( { 'possition': pos, 'offset': offset, 'parsed': header });})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_name_addr() { var result0, result1, result2, result3; var pos0; pos0 = pos; result0 = parse_display_name(); result0 = result0 !== null ? result0 : ""; if (result0 !== null) { result1 = parse_LAQUOT(); if (result1 !== null) { result2 = parse_SIP_URI(); if (result2 !== null) { result3 = parse_RAQUOT(); if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_display_name() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_token(); if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_LWS(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_LWS(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { result0 = parse_quoted_string(); } if (result0 !== null) { result0 = (function(offset, display_name) { display_name = input.substring(pos, offset).trim(); if (display_name[0] === '\"') { display_name = display_name.substring(1, display_name.length-1); } data.display_name = display_name; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_contact_params() { var result0; result0 = parse_c_p_q(); if (result0 === null) { result0 = parse_c_p_expires(); if (result0 === null) { result0 = parse_generic_param(); } } return result0; } function parse_c_p_q() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 1).toLowerCase() === "q") { result0 = input.substr(pos, 1); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"q\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_qvalue(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, q) { if(!data.params) data.params = {}; data.params['q'] = q; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_c_p_expires() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 7).toLowerCase() === "expires") { result0 = input.substr(pos, 7); pos += 7; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"expires\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_delta_seconds(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, expires) { if(!data.params) data.params = {}; data.params['expires'] = expires; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_delta_seconds() { var result0, result1; var pos0; pos0 = pos; result1 = parse_DIGIT(); if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_DIGIT(); } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset, delta_seconds) { return parseInt(delta_seconds.join('')); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_qvalue() { var result0, result1, result2, result3, result4; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; if (input.charCodeAt(pos) === 48) { result0 = "0"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"0\""); } } if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 46) { result1 = "."; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result1 !== null) { result2 = parse_DIGIT(); result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result3 = parse_DIGIT(); result3 = result3 !== null ? result3 : ""; if (result3 !== null) { result4 = parse_DIGIT(); result4 = result4 !== null ? result4 : ""; if (result4 !== null) { result1 = [result1, result2, result3, result4]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { return parseFloat(input.substring(pos, offset)); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_generic_param() { var result0, result1, result2; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_token(); if (result0 !== null) { pos2 = pos; result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_gen_value(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, param, value) { if(!data.params) data.params = {}; if (typeof value === 'undefined'){ value = undefined; } else { value = value[1]; } data.params[param.toLowerCase()] = value;})(pos0, result0[0], result0[1]); } if (result0 === null) { pos = pos0; } return result0; } function parse_gen_value() { var result0; result0 = parse_token(); if (result0 === null) { result0 = parse_host(); if (result0 === null) { result0 = parse_quoted_string(); } } return result0; } function parse_Content_Disposition() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_disp_type(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_disp_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_disp_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_disp_type() { var result0; if (input.substr(pos, 6).toLowerCase() === "render") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"render\""); } } if (result0 === null) { if (input.substr(pos, 7).toLowerCase() === "session") { result0 = input.substr(pos, 7); pos += 7; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"session\""); } } if (result0 === null) { if (input.substr(pos, 4).toLowerCase() === "icon") { result0 = input.substr(pos, 4); pos += 4; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"icon\""); } } if (result0 === null) { if (input.substr(pos, 5).toLowerCase() === "alert") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"alert\""); } } if (result0 === null) { result0 = parse_token(); } } } } return result0; } function parse_disp_param() { var result0; result0 = parse_handling_param(); if (result0 === null) { result0 = parse_generic_param(); } return result0; } function parse_handling_param() { var result0, result1, result2; var pos0; pos0 = pos; if (input.substr(pos, 8).toLowerCase() === "handling") { result0 = input.substr(pos, 8); pos += 8; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"handling\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { if (input.substr(pos, 8).toLowerCase() === "optional") { result2 = input.substr(pos, 8); pos += 8; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"optional\""); } } if (result2 === null) { if (input.substr(pos, 8).toLowerCase() === "required") { result2 = input.substr(pos, 8); pos += 8; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"required\""); } } if (result2 === null) { result2 = parse_token(); } } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Content_Encoding() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_token(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Content_Length() { var result0, result1; var pos0; pos0 = pos; result1 = parse_DIGIT(); if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_DIGIT(); } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset, length) { data = parseInt(length.join('')); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Content_Type() { var result0; var pos0; pos0 = pos; result0 = parse_media_type(); if (result0 !== null) { result0 = (function(offset) { data = input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_media_type() { var result0, result1, result2, result3, result4, result5; var pos0, pos1; pos0 = pos; result0 = parse_m_type(); if (result0 !== null) { result1 = parse_SLASH(); if (result1 !== null) { result2 = parse_m_subtype(); if (result2 !== null) { result3 = []; pos1 = pos; result4 = parse_SEMI(); if (result4 !== null) { result5 = parse_m_parameter(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos1; } } else { result4 = null; pos = pos1; } while (result4 !== null) { result3.push(result4); pos1 = pos; result4 = parse_SEMI(); if (result4 !== null) { result5 = parse_m_parameter(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos1; } } else { result4 = null; pos = pos1; } } if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_m_type() { var result0; result0 = parse_discrete_type(); if (result0 === null) { result0 = parse_composite_type(); } return result0; } function parse_discrete_type() { var result0; if (input.substr(pos, 4).toLowerCase() === "text") { result0 = input.substr(pos, 4); pos += 4; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"text\""); } } if (result0 === null) { if (input.substr(pos, 5).toLowerCase() === "image") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"image\""); } } if (result0 === null) { if (input.substr(pos, 5).toLowerCase() === "audio") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"audio\""); } } if (result0 === null) { if (input.substr(pos, 5).toLowerCase() === "video") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"video\""); } } if (result0 === null) { if (input.substr(pos, 11).toLowerCase() === "application") { result0 = input.substr(pos, 11); pos += 11; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"application\""); } } if (result0 === null) { result0 = parse_extension_token(); } } } } } return result0; } function parse_composite_type() { var result0; if (input.substr(pos, 7).toLowerCase() === "message") { result0 = input.substr(pos, 7); pos += 7; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"message\""); } } if (result0 === null) { if (input.substr(pos, 9).toLowerCase() === "multipart") { result0 = input.substr(pos, 9); pos += 9; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"multipart\""); } } if (result0 === null) { result0 = parse_extension_token(); } } return result0; } function parse_extension_token() { var result0; result0 = parse_token(); if (result0 === null) { result0 = parse_x_token(); } return result0; } function parse_x_token() { var result0, result1; var pos0; pos0 = pos; if (input.substr(pos, 2).toLowerCase() === "x-") { result0 = input.substr(pos, 2); pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"x-\""); } } if (result0 !== null) { result1 = parse_token(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_m_subtype() { var result0; result0 = parse_extension_token(); if (result0 === null) { result0 = parse_token(); } return result0; } function parse_m_parameter() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_token(); if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_m_value(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_m_value() { var result0; result0 = parse_token(); if (result0 === null) { result0 = parse_quoted_string(); } return result0; } function parse_CSeq() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_CSeq_value(); if (result0 !== null) { result1 = parse_LWS(); if (result1 !== null) { result2 = parse_Method(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_CSeq_value() { var result0, result1; var pos0; pos0 = pos; result1 = parse_DIGIT(); if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_DIGIT(); } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset, cseq_value) { data.value=parseInt(cseq_value.join('')); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Expires() { var result0; var pos0; pos0 = pos; result0 = parse_delta_seconds(); if (result0 !== null) { result0 = (function(offset, expires) {data = expires; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Event() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_event_type(); if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_generic_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_generic_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, event_type) { data.event = event_type.join('').toLowerCase(); })(pos0, result0[0]); } if (result0 === null) { pos = pos0; } return result0; } function parse_event_type() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_token_nodot(); if (result0 !== null) { result1 = []; pos1 = pos; if (input.charCodeAt(pos) === 46) { result2 = "."; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result2 !== null) { result3 = parse_token_nodot(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; if (input.charCodeAt(pos) === 46) { result2 = "."; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result2 !== null) { result3 = parse_token_nodot(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_From() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_SIP_URI_noparams(); if (result0 === null) { result0 = parse_name_addr(); } if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_from_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_from_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { var tag = data.tag; try { data = new NameAddrHeader(data.uri, data.display_name, data.params); if (tag) {data.setParam('tag',tag)} } catch(e) { data = -1; }})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_from_param() { var result0; result0 = parse_tag_param(); if (result0 === null) { result0 = parse_generic_param(); } return result0; } function parse_tag_param() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 3).toLowerCase() === "tag") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"tag\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_token(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, tag) {data.tag = tag; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_Max_Forwards() { var result0, result1; var pos0; pos0 = pos; result1 = parse_DIGIT(); if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_DIGIT(); } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset, forwards) { data = parseInt(forwards.join('')); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Min_Expires() { var result0; var pos0; pos0 = pos; result0 = parse_delta_seconds(); if (result0 !== null) { result0 = (function(offset, min_expires) {data = min_expires; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Name_Addr_Header() { var result0, result1, result2, result3, result4, result5, result6; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = []; result1 = parse_display_name(); while (result1 !== null) { result0.push(result1); result1 = parse_display_name(); } if (result0 !== null) { result1 = parse_LAQUOT(); if (result1 !== null) { result2 = parse_SIP_URI(); if (result2 !== null) { result3 = parse_RAQUOT(); if (result3 !== null) { result4 = []; pos2 = pos; result5 = parse_SEMI(); if (result5 !== null) { result6 = parse_generic_param(); if (result6 !== null) { result5 = [result5, result6]; } else { result5 = null; pos = pos2; } } else { result5 = null; pos = pos2; } while (result5 !== null) { result4.push(result5); pos2 = pos; result5 = parse_SEMI(); if (result5 !== null) { result6 = parse_generic_param(); if (result6 !== null) { result5 = [result5, result6]; } else { result5 = null; pos = pos2; } } else { result5 = null; pos = pos2; } } if (result4 !== null) { result0 = [result0, result1, result2, result3, result4]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { try { data = new NameAddrHeader(data.uri, data.display_name, data.params); } catch(e) { data = -1; }})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Proxy_Authenticate() { var result0; result0 = parse_challenge(); return result0; } function parse_challenge() { var result0, result1, result2, result3, result4, result5; var pos0, pos1; pos0 = pos; if (input.substr(pos, 6).toLowerCase() === "digest") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"Digest\""); } } if (result0 !== null) { result1 = parse_LWS(); if (result1 !== null) { result2 = parse_digest_cln(); if (result2 !== null) { result3 = []; pos1 = pos; result4 = parse_COMMA(); if (result4 !== null) { result5 = parse_digest_cln(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos1; } } else { result4 = null; pos = pos1; } while (result4 !== null) { result3.push(result4); pos1 = pos; result4 = parse_COMMA(); if (result4 !== null) { result5 = parse_digest_cln(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos1; } } else { result4 = null; pos = pos1; } } if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } if (result0 === null) { result0 = parse_other_challenge(); } return result0; } function parse_other_challenge() { var result0, result1, result2, result3, result4, result5; var pos0, pos1; pos0 = pos; result0 = parse_token(); if (result0 !== null) { result1 = parse_LWS(); if (result1 !== null) { result2 = parse_auth_param(); if (result2 !== null) { result3 = []; pos1 = pos; result4 = parse_COMMA(); if (result4 !== null) { result5 = parse_auth_param(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos1; } } else { result4 = null; pos = pos1; } while (result4 !== null) { result3.push(result4); pos1 = pos; result4 = parse_COMMA(); if (result4 !== null) { result5 = parse_auth_param(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos1; } } else { result4 = null; pos = pos1; } } if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_auth_param() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_token(); if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_token(); if (result2 === null) { result2 = parse_quoted_string(); } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_digest_cln() { var result0; result0 = parse_realm(); if (result0 === null) { result0 = parse_domain(); if (result0 === null) { result0 = parse_nonce(); if (result0 === null) { result0 = parse_opaque(); if (result0 === null) { result0 = parse_stale(); if (result0 === null) { result0 = parse_algorithm(); if (result0 === null) { result0 = parse_qop_options(); if (result0 === null) { result0 = parse_auth_param(); } } } } } } } return result0; } function parse_realm() { var result0, result1, result2; var pos0; pos0 = pos; if (input.substr(pos, 5).toLowerCase() === "realm") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"realm\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_realm_value(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_realm_value() { var result0; var pos0; pos0 = pos; result0 = parse_quoted_string_clean(); if (result0 !== null) { result0 = (function(offset, realm) { data.realm = realm; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_domain() { var result0, result1, result2, result3, result4, result5, result6; var pos0, pos1; pos0 = pos; if (input.substr(pos, 6).toLowerCase() === "domain") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"domain\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_LDQUOT(); if (result2 !== null) { result3 = parse_URI(); if (result3 !== null) { result4 = []; pos1 = pos; result6 = parse_SP(); if (result6 !== null) { result5 = []; while (result6 !== null) { result5.push(result6); result6 = parse_SP(); } } else { result5 = null; } if (result5 !== null) { result6 = parse_URI(); if (result6 !== null) { result5 = [result5, result6]; } else { result5 = null; pos = pos1; } } else { result5 = null; pos = pos1; } while (result5 !== null) { result4.push(result5); pos1 = pos; result6 = parse_SP(); if (result6 !== null) { result5 = []; while (result6 !== null) { result5.push(result6); result6 = parse_SP(); } } else { result5 = null; } if (result5 !== null) { result6 = parse_URI(); if (result6 !== null) { result5 = [result5, result6]; } else { result5 = null; pos = pos1; } } else { result5 = null; pos = pos1; } } if (result4 !== null) { result5 = parse_RDQUOT(); if (result5 !== null) { result0 = [result0, result1, result2, result3, result4, result5]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_URI() { var result0; result0 = parse_absoluteURI(); if (result0 === null) { result0 = parse_abs_path(); } return result0; } function parse_nonce() { var result0, result1, result2; var pos0; pos0 = pos; if (input.substr(pos, 5).toLowerCase() === "nonce") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"nonce\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_nonce_value(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_nonce_value() { var result0; var pos0; pos0 = pos; result0 = parse_quoted_string_clean(); if (result0 !== null) { result0 = (function(offset, nonce) { data.nonce=nonce; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_opaque() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 6).toLowerCase() === "opaque") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"opaque\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_quoted_string_clean(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, opaque) { data.opaque=opaque; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_stale() { var result0, result1, result2; var pos0, pos1; pos0 = pos; if (input.substr(pos, 5).toLowerCase() === "stale") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"stale\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { pos1 = pos; if (input.substr(pos, 4).toLowerCase() === "true") { result2 = input.substr(pos, 4); pos += 4; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"true\""); } } if (result2 !== null) { result2 = (function(offset) { data.stale=true; })(pos1); } if (result2 === null) { pos = pos1; } if (result2 === null) { pos1 = pos; if (input.substr(pos, 5).toLowerCase() === "false") { result2 = input.substr(pos, 5); pos += 5; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"false\""); } } if (result2 !== null) { result2 = (function(offset) { data.stale=false; })(pos1); } if (result2 === null) { pos = pos1; } } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_algorithm() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 9).toLowerCase() === "algorithm") { result0 = input.substr(pos, 9); pos += 9; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"algorithm\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { if (input.substr(pos, 3).toLowerCase() === "md5") { result2 = input.substr(pos, 3); pos += 3; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"MD5\""); } } if (result2 === null) { if (input.substr(pos, 8).toLowerCase() === "md5-sess") { result2 = input.substr(pos, 8); pos += 8; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"MD5-sess\""); } } if (result2 === null) { result2 = parse_token(); } } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, algorithm) { data.algorithm=algorithm.toUpperCase(); })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_qop_options() { var result0, result1, result2, result3, result4, result5, result6; var pos0, pos1, pos2; pos0 = pos; if (input.substr(pos, 3).toLowerCase() === "qop") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"qop\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_LDQUOT(); if (result2 !== null) { pos1 = pos; result3 = parse_qop_value(); if (result3 !== null) { result4 = []; pos2 = pos; if (input.charCodeAt(pos) === 44) { result5 = ","; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\",\""); } } if (result5 !== null) { result6 = parse_qop_value(); if (result6 !== null) { result5 = [result5, result6]; } else { result5 = null; pos = pos2; } } else { result5 = null; pos = pos2; } while (result5 !== null) { result4.push(result5); pos2 = pos; if (input.charCodeAt(pos) === 44) { result5 = ","; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\",\""); } } if (result5 !== null) { result6 = parse_qop_value(); if (result6 !== null) { result5 = [result5, result6]; } else { result5 = null; pos = pos2; } } else { result5 = null; pos = pos2; } } if (result4 !== null) { result3 = [result3, result4]; } else { result3 = null; pos = pos1; } } else { result3 = null; pos = pos1; } if (result3 !== null) { result4 = parse_RDQUOT(); if (result4 !== null) { result0 = [result0, result1, result2, result3, result4]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_qop_value() { var result0; var pos0; pos0 = pos; if (input.substr(pos, 8).toLowerCase() === "auth-int") { result0 = input.substr(pos, 8); pos += 8; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"auth-int\""); } } if (result0 === null) { if (input.substr(pos, 4).toLowerCase() === "auth") { result0 = input.substr(pos, 4); pos += 4; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"auth\""); } } if (result0 === null) { result0 = parse_token(); } } if (result0 !== null) { result0 = (function(offset, qop_value) { data.qop || (data.qop=[]); data.qop.push(qop_value.toLowerCase()); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Proxy_Require() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_token(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Record_Route() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_rec_route(); if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_rec_route(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_rec_route(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { var idx, length; length = data.multi_header.length; for (idx = 0; idx < length; idx++) { if (data.multi_header[idx].parsed === null) { data = null; break; } } if (data !== null) { data = data.multi_header; } else { data = -1; }})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_rec_route() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_name_addr(); if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_generic_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_generic_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { var header; if(!data.multi_header) data.multi_header = []; try { header = new NameAddrHeader(data.uri, data.display_name, data.params); delete data.uri; delete data.display_name; delete data.params; } catch(e) { header = null; } data.multi_header.push( { 'possition': pos, 'offset': offset, 'parsed': header });})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Reason() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; if (input.substr(pos, 3).toLowerCase() === "sip") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"SIP\""); } } if (result0 === null) { result0 = parse_token(); } if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_reason_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_reason_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, protocol) { data.protocol = protocol.toLowerCase(); if (!data.params) data.params = {}; if (data.params.text && data.params.text[0] === '"') { var text = data.params.text; data.text = text.substring(1, text.length-1); delete data.params.text; } })(pos0, result0[0]); } if (result0 === null) { pos = pos0; } return result0; } function parse_reason_param() { var result0; result0 = parse_reason_cause(); if (result0 === null) { result0 = parse_generic_param(); } return result0; } function parse_reason_cause() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 5).toLowerCase() === "cause") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"cause\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result3 = parse_DIGIT(); if (result3 !== null) { result2 = []; while (result3 !== null) { result2.push(result3); result3 = parse_DIGIT(); } } else { result2 = null; } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, cause) { data.cause = parseInt(cause.join('')); })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_Require() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_token(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Route() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_route_param(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_route_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_route_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_route_param() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_name_addr(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_generic_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_generic_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Subscription_State() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_substate_value(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_subexp_params(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_subexp_params(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_substate_value() { var result0; var pos0; pos0 = pos; if (input.substr(pos, 6).toLowerCase() === "active") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"active\""); } } if (result0 === null) { if (input.substr(pos, 7).toLowerCase() === "pending") { result0 = input.substr(pos, 7); pos += 7; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"pending\""); } } if (result0 === null) { if (input.substr(pos, 10).toLowerCase() === "terminated") { result0 = input.substr(pos, 10); pos += 10; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"terminated\""); } } if (result0 === null) { result0 = parse_token(); } } } if (result0 !== null) { result0 = (function(offset) { data.state = input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_subexp_params() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 6).toLowerCase() === "reason") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"reason\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_event_reason_value(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, reason) { if (typeof reason !== 'undefined') data.reason = reason; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } if (result0 === null) { pos0 = pos; pos1 = pos; if (input.substr(pos, 7).toLowerCase() === "expires") { result0 = input.substr(pos, 7); pos += 7; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"expires\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_delta_seconds(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, expires) { if (typeof expires !== 'undefined') data.expires = expires; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } if (result0 === null) { pos0 = pos; pos1 = pos; if (input.substr(pos, 11).toLowerCase() === "retry_after") { result0 = input.substr(pos, 11); pos += 11; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"retry_after\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_delta_seconds(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, retry_after) { if (typeof retry_after !== 'undefined') data.retry_after = retry_after; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } if (result0 === null) { result0 = parse_generic_param(); } } } return result0; } function parse_event_reason_value() { var result0; if (input.substr(pos, 11).toLowerCase() === "deactivated") { result0 = input.substr(pos, 11); pos += 11; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"deactivated\""); } } if (result0 === null) { if (input.substr(pos, 9).toLowerCase() === "probation") { result0 = input.substr(pos, 9); pos += 9; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"probation\""); } } if (result0 === null) { if (input.substr(pos, 8).toLowerCase() === "rejected") { result0 = input.substr(pos, 8); pos += 8; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"rejected\""); } } if (result0 === null) { if (input.substr(pos, 7).toLowerCase() === "timeout") { result0 = input.substr(pos, 7); pos += 7; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"timeout\""); } } if (result0 === null) { if (input.substr(pos, 6).toLowerCase() === "giveup") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"giveup\""); } } if (result0 === null) { if (input.substr(pos, 10).toLowerCase() === "noresource") { result0 = input.substr(pos, 10); pos += 10; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"noresource\""); } } if (result0 === null) { if (input.substr(pos, 9).toLowerCase() === "invariant") { result0 = input.substr(pos, 9); pos += 9; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"invariant\""); } } if (result0 === null) { result0 = parse_token(); } } } } } } } return result0; } function parse_Subject() { var result0; result0 = parse_TEXT_UTF8_TRIM(); result0 = result0 !== null ? result0 : ""; return result0; } function parse_Supported() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_token(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } result0 = result0 !== null ? result0 : ""; return result0; } function parse_To() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_SIP_URI_noparams(); if (result0 === null) { result0 = parse_name_addr(); } if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_to_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_to_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { var tag = data.tag; try { data = new NameAddrHeader(data.uri, data.display_name, data.params); if (tag) {data.setParam('tag',tag)} } catch(e) { data = -1; }})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_to_param() { var result0; result0 = parse_tag_param(); if (result0 === null) { result0 = parse_generic_param(); } return result0; } function parse_Via() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_via_param(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_via_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_via_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_via_param() { var result0, result1, result2, result3, result4, result5; var pos0, pos1; pos0 = pos; result0 = parse_sent_protocol(); if (result0 !== null) { result1 = parse_LWS(); if (result1 !== null) { result2 = parse_sent_by(); if (result2 !== null) { result3 = []; pos1 = pos; result4 = parse_SEMI(); if (result4 !== null) { result5 = parse_via_params(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos1; } } else { result4 = null; pos = pos1; } while (result4 !== null) { result3.push(result4); pos1 = pos; result4 = parse_SEMI(); if (result4 !== null) { result5 = parse_via_params(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos1; } } else { result4 = null; pos = pos1; } } if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_via_params() { var result0; result0 = parse_via_ttl(); if (result0 === null) { result0 = parse_via_maddr(); if (result0 === null) { result0 = parse_via_received(); if (result0 === null) { result0 = parse_via_branch(); if (result0 === null) { result0 = parse_response_port(); if (result0 === null) { result0 = parse_generic_param(); } } } } } return result0; } function parse_via_ttl() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 3).toLowerCase() === "ttl") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"ttl\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_ttl(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, via_ttl_value) { data.ttl = via_ttl_value; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_via_maddr() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 5).toLowerCase() === "maddr") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"maddr\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_host(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, via_maddr) { data.maddr = via_maddr; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_via_received() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 8).toLowerCase() === "received") { result0 = input.substr(pos, 8); pos += 8; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"received\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_IPv4address(); if (result2 === null) { result2 = parse_IPv6address(); } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, via_received) { data.received = via_received; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_via_branch() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 6).toLowerCase() === "branch") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"branch\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_token(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, via_branch) { data.branch = via_branch; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_response_port() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; if (input.substr(pos, 5).toLowerCase() === "rport") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"rport\""); } } if (result0 !== null) { pos2 = pos; result1 = parse_EQUAL(); if (result1 !== null) { result2 = []; result3 = parse_DIGIT(); while (result3 !== null) { result2.push(result3); result3 = parse_DIGIT(); } if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { if(typeof response_port !== 'undefined') data.rport = response_port.join(''); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_sent_protocol() { var result0, result1, result2, result3, result4; var pos0; pos0 = pos; result0 = parse_protocol_name(); if (result0 !== null) { result1 = parse_SLASH(); if (result1 !== null) { result2 = parse_token(); if (result2 !== null) { result3 = parse_SLASH(); if (result3 !== null) { result4 = parse_transport(); if (result4 !== null) { result0 = [result0, result1, result2, result3, result4]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_protocol_name() { var result0; var pos0; pos0 = pos; if (input.substr(pos, 3).toLowerCase() === "sip") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"SIP\""); } } if (result0 === null) { result0 = parse_token(); } if (result0 !== null) { result0 = (function(offset, via_protocol) { data.protocol = via_protocol; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_transport() { var result0; var pos0; pos0 = pos; if (input.substr(pos, 3).toLowerCase() === "udp") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"UDP\""); } } if (result0 === null) { if (input.substr(pos, 3).toLowerCase() === "tcp") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"TCP\""); } } if (result0 === null) { if (input.substr(pos, 3).toLowerCase() === "tls") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"TLS\""); } } if (result0 === null) { if (input.substr(pos, 4).toLowerCase() === "sctp") { result0 = input.substr(pos, 4); pos += 4; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"SCTP\""); } } if (result0 === null) { result0 = parse_token(); } } } } if (result0 !== null) { result0 = (function(offset, via_transport) { data.transport = via_transport; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_sent_by() { var result0, result1, result2; var pos0, pos1; pos0 = pos; result0 = parse_via_host(); if (result0 !== null) { pos1 = pos; result1 = parse_COLON(); if (result1 !== null) { result2 = parse_via_port(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos1; } } else { result1 = null; pos = pos1; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_via_host() { var result0; var pos0; pos0 = pos; result0 = parse_IPv4address(); if (result0 === null) { result0 = parse_IPv6reference(); if (result0 === null) { result0 = parse_hostname(); } } if (result0 !== null) { result0 = (function(offset) { data.host = input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_via_port() { var result0, result1, result2, result3, result4; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_DIGIT(); result0 = result0 !== null ? result0 : ""; if (result0 !== null) { result1 = parse_DIGIT(); result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result2 = parse_DIGIT(); result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result3 = parse_DIGIT(); result3 = result3 !== null ? result3 : ""; if (result3 !== null) { result4 = parse_DIGIT(); result4 = result4 !== null ? result4 : ""; if (result4 !== null) { result0 = [result0, result1, result2, result3, result4]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, via_sent_by_port) { data.port = parseInt(via_sent_by_port.join('')); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_ttl() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_DIGIT(); if (result0 !== null) { result1 = parse_DIGIT(); result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result2 = parse_DIGIT(); result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, ttl) { return parseInt(ttl.join('')); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_WWW_Authenticate() { var result0; result0 = parse_challenge(); return result0; } function parse_Session_Expires() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_s_e_expires(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_s_e_params(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_s_e_params(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_s_e_expires() { var result0; var pos0; pos0 = pos; result0 = parse_delta_seconds(); if (result0 !== null) { result0 = (function(offset, expires) { data.expires = expires; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_s_e_params() { var result0; result0 = parse_s_e_refresher(); if (result0 === null) { result0 = parse_generic_param(); } return result0; } function parse_s_e_refresher() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 9).toLowerCase() === "refresher") { result0 = input.substr(pos, 9); pos += 9; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"refresher\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { if (input.substr(pos, 3).toLowerCase() === "uac") { result2 = input.substr(pos, 3); pos += 3; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"uac\""); } } if (result2 === null) { if (input.substr(pos, 3).toLowerCase() === "uas") { result2 = input.substr(pos, 3); pos += 3; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"uas\""); } } } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, s_e_refresher_value) { data.refresher = s_e_refresher_value.toLowerCase(); })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_extension_header() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_token(); if (result0 !== null) { result1 = parse_HCOLON(); if (result1 !== null) { result2 = parse_header_value(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_header_value() { var result0, result1; result0 = []; result1 = parse_TEXT_UTF8char(); if (result1 === null) { result1 = parse_UTF8_CONT(); if (result1 === null) { result1 = parse_LWS(); } } while (result1 !== null) { result0.push(result1); result1 = parse_TEXT_UTF8char(); if (result1 === null) { result1 = parse_UTF8_CONT(); if (result1 === null) { result1 = parse_LWS(); } } } return result0; } function parse_message_body() { var result0, result1; result0 = []; result1 = parse_OCTET(); while (result1 !== null) { result0.push(result1); result1 = parse_OCTET(); } return result0; } function parse_uuid_URI() { var result0, result1; var pos0; pos0 = pos; if (input.substr(pos, 5) === "uuid:") { result0 = "uuid:"; pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"uuid:\""); } } if (result0 !== null) { result1 = parse_uuid(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_uuid() { var result0, result1, result2, result3, result4, result5, result6, result7, result8; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_hex8(); if (result0 !== null) { if (input.charCodeAt(pos) === 45) { result1 = "-"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result1 !== null) { result2 = parse_hex4(); if (result2 !== null) { if (input.charCodeAt(pos) === 45) { result3 = "-"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result3 !== null) { result4 = parse_hex4(); if (result4 !== null) { if (input.charCodeAt(pos) === 45) { result5 = "-"; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result5 !== null) { result6 = parse_hex4(); if (result6 !== null) { if (input.charCodeAt(pos) === 45) { result7 = "-"; pos++; } else { result7 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result7 !== null) { result8 = parse_hex12(); if (result8 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, uuid) { data = input.substring(pos+5, offset); })(pos0, result0[0]); } if (result0 === null) { pos = pos0; } return result0; } function parse_hex4() { var result0, result1, result2, result3; var pos0; pos0 = pos; result0 = parse_HEXDIG(); if (result0 !== null) { result1 = parse_HEXDIG(); if (result1 !== null) { result2 = parse_HEXDIG(); if (result2 !== null) { result3 = parse_HEXDIG(); if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_hex8() { var result0, result1; var pos0; pos0 = pos; result0 = parse_hex4(); if (result0 !== null) { result1 = parse_hex4(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_hex12() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_hex4(); if (result0 !== null) { result1 = parse_hex4(); if (result1 !== null) { result2 = parse_hex4(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Refer_To() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_SIP_URI_noparams(); if (result0 === null) { result0 = parse_name_addr(); } if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_generic_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_generic_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { try { data = new NameAddrHeader(data.uri, data.display_name, data.params); } catch(e) { data = -1; }})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Replaces() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_call_id(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_replaces_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_replaces_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_call_id() { var result0, result1, result2; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_word(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 64) { result1 = "@"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result1 !== null) { result2 = parse_word(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { data.call_id = input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_replaces_param() { var result0; result0 = parse_to_tag(); if (result0 === null) { result0 = parse_from_tag(); if (result0 === null) { result0 = parse_early_flag(); if (result0 === null) { result0 = parse_generic_param(); } } } return result0; } function parse_to_tag() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 6) === "to-tag") { result0 = "to-tag"; pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"to-tag\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_token(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, to_tag) { data.to_tag = to_tag; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_from_tag() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 8) === "from-tag") { result0 = "from-tag"; pos += 8; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"from-tag\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_token(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, from_tag) { data.from_tag = from_tag; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_early_flag() { var result0; var pos0; pos0 = pos; if (input.substr(pos, 10) === "early-only") { result0 = "early-only"; pos += 10; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"early-only\""); } } if (result0 !== null) { result0 = (function(offset) { data.early_only = true; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function cleanupExpected(expected) { expected.sort(); var lastExpected = null; var cleanExpected = []; for (var i = 0; i < expected.length; i++) { if (expected[i] !== lastExpected) { cleanExpected.push(expected[i]); lastExpected = expected[i]; } } return cleanExpected; } function computeErrorPosition() { /* * The first idea was to use |String.split| to break the input up to the * error position along newlines and derive the line and column from * there. However IE's |split| implementation is so broken that it was * enough to prevent it. */ var line = 1; var column = 1; var seenCR = false; for (var i = 0; i < Math.max(pos, rightmostFailuresPos); i++) { var ch = input.charAt(i); if (ch === "\n") { if (!seenCR) { line++; } column = 1; seenCR = false; } else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") { line++; column = 1; seenCR = true; } else { column++; seenCR = false; } } return { line: line, column: column }; } var URI = require('./URI'); var NameAddrHeader = require('./NameAddrHeader'); var data = {}; var result = parseFunctions[startRule](); /* * The parser is now in one of the following three states: * * 1. The parser successfully parsed the whole input. * * - |result !== null| * - |pos === input.length| * - |rightmostFailuresExpected| may or may not contain something * * 2. The parser successfully parsed only a part of the input. * * - |result !== null| * - |pos < input.length| * - |rightmostFailuresExpected| may or may not contain something * * 3. The parser did not successfully parse any part of the input. * * - |result === null| * - |pos === 0| * - |rightmostFailuresExpected| contains at least one failure * * All code following this comment (including called functions) must * handle these states. */ if (result === null || pos !== input.length) { var offset = Math.max(pos, rightmostFailuresPos); var found = offset < input.length ? input.charAt(offset) : null; var errorPosition = computeErrorPosition(); new this.SyntaxError( cleanupExpected(rightmostFailuresExpected), found, offset, errorPosition.line, errorPosition.column ); return -1; } return data; }, /* Returns the parser source code. */ toSource: function() { return this._source; } }; /* Thrown when a parser encounters a syntax error. */ result.SyntaxError = function(expected, found, offset, line, column) { function buildMessage(expected, found) { var expectedHumanized, foundHumanized; switch (expected.length) { case 0: expectedHumanized = "end of input"; break; case 1: expectedHumanized = expected[0]; break; default: expectedHumanized = expected.slice(0, expected.length - 1).join(", ") + " or " + expected[expected.length - 1]; } foundHumanized = found ? quote(found) : "end of input"; return "Expected " + expectedHumanized + " but " + foundHumanized + " found."; } this.name = "SyntaxError"; this.expected = expected; this.found = found; this.message = buildMessage(expected, found); this.offset = offset; this.line = line; this.column = column; }; result.SyntaxError.prototype = Error.prototype; return result; })(); },{"./NameAddrHeader":9,"./URI":24}],7:[function(require,module,exports){ /** * Dependencies. */ var debug = require('debug')('JsSIP'); var adapter = require('webrtc-adapter'); var pkg = require('../package.json'); debug('version %s', pkg.version); var C = require('./Constants'); var Exceptions = require('./Exceptions'); var Utils = require('./Utils'); var UA = require('./UA'); var URI = require('./URI'); var NameAddrHeader = require('./NameAddrHeader'); var Grammar = require('./Grammar'); var WebSocketInterface = require('./WebSocketInterface'); /** * Expose the JsSIP module. */ var JsSIP = module.exports = { C: C, Exceptions: Exceptions, Utils: Utils, UA: UA, URI: URI, NameAddrHeader: NameAddrHeader, WebSocketInterface: WebSocketInterface, Grammar: Grammar, // Expose the debug module. debug: require('debug'), // Expose the adapter module. adapter: adapter }; Object.defineProperties(JsSIP, { name: { get: function() { return pkg.title; } }, version: { get: function() { return pkg.version; } } }); },{"../package.json":50,"./Constants":1,"./Exceptions":5,"./Grammar":6,"./NameAddrHeader":9,"./UA":23,"./URI":24,"./Utils":25,"./WebSocketInterface":26,"debug":34,"webrtc-adapter":41}],8:[function(require,module,exports){ module.exports = Message; /** * Dependencies. */ var util = require('util'); var events = require('events'); var JsSIP_C = require('./Constants'); var SIPMessage = require('./SIPMessage'); var Utils = require('./Utils'); var RequestSender = require('./RequestSender'); var Transactions = require('./Transactions'); var Exceptions = require('./Exceptions'); function Message(ua) { this.ua = ua; // Custom message empty object for high level use this.data = {}; events.EventEmitter.call(this); } util.inherits(Message, events.EventEmitter); Message.prototype.send = function(target, body, options) { var request_sender, event, contentType, eventHandlers, extraHeaders, originalTarget = target; if (target === undefined || body === undefined) { throw new TypeError('Not enough arguments'); } // Check target validity target = this.ua.normalizeTarget(target); if (!target) { throw new TypeError('Invalid target: '+ originalTarget); } // Get call options options = options || {}; extraHeaders = options.extraHeaders && options.extraHeaders.slice() || []; eventHandlers = options.eventHandlers || {}; contentType = options.contentType || 'text/plain'; this.content_type = contentType; // Set event handlers for (event in eventHandlers) { this.on(event, eventHandlers[event]); } this.closed = false; this.ua.applicants[this] = this; extraHeaders.push('Content-Type: '+ contentType); this.request = new SIPMessage.OutgoingRequest(JsSIP_C.MESSAGE, target, this.ua, null, extraHeaders); if(body) { this.request.body = body; this.content = body; } else { this.content = null; } request_sender = new RequestSender(this, this.ua); this.newMessage('local', this.request); request_sender.send(); }; Message.prototype.receiveResponse = function(response) { var cause; if(this.closed) { return; } switch(true) { case /^1[0-9]{2}$/.test(response.status_code): // Ignore provisional responses. break; case /^2[0-9]{2}$/.test(response.status_code): delete this.ua.applicants[this]; this.emit('succeeded', { originator: 'remote', response: response }); break; default: delete this.ua.applicants[this]; cause = Utils.sipErrorCause(response.status_code); this.emit('failed', { originator: 'remote', response: response, cause: cause }); break; } }; Message.prototype.onRequestTimeout = function() { if(this.closed) { return; } this.emit('failed', { originator: 'system', cause: JsSIP_C.causes.REQUEST_TIMEOUT }); }; Message.prototype.onTransportError = function() { if(this.closed) { return; } this.emit('failed', { originator: 'system', cause: JsSIP_C.causes.CONNECTION_ERROR }); }; Message.prototype.close = function() { this.closed = true; delete this.ua.applicants[this]; }; Message.prototype.init_incoming = function(request) { var transaction; this.request = request; this.content_type = request.getHeader('Content-Type'); if (request.body) { this.content = request.body; } else { this.content = null; } this.newMessage('remote', request); transaction = this.ua.transactions.nist[request.via_branch]; if (transaction && (transaction.state === Transactions.C.STATUS_TRYING || transaction.state === Transactions.C.STATUS_PROCEEDING)) { request.reply(200); } }; /** * Accept the incoming Message * Only valid for incoming Messages */ Message.prototype.accept = function(options) { options = options || {}; var extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], body = options.body; if (this.direction !== 'incoming') { throw new Exceptions.NotSupportedError('"accept" not supported for outgoing Message'); } this.request.reply(200, null, extraHeaders, body); }; /** * Reject the incoming Message * Only valid for incoming Messages */ Message.prototype.reject = function(options) { options = options || {}; var status_code = options.status_code || 480, reason_phrase = options.reason_phrase, extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], body = options.body; if (this.direction !== 'incoming') { throw new Exceptions.NotSupportedError('"reject" not supported for outgoing Message'); } if (status_code < 300 || status_code >= 700) { throw new TypeError('Invalid status_code: '+ status_code); } this.request.reply(status_code, reason_phrase, extraHeaders, body); }; /** * Internal Callbacks */ Message.prototype.newMessage = function(originator, request) { if (originator === 'remote') { this.direction = 'incoming'; this.local_identity = request.to; this.remote_identity = request.from; } else if (originator === 'local'){ this.direction = 'outgoing'; this.local_identity = request.from; this.remote_identity = request.to; } this.ua.newMessage({ originator: originator, message: this, request: request }); }; },{"./Constants":1,"./Exceptions":5,"./RequestSender":17,"./SIPMessage":18,"./Transactions":21,"./Utils":25,"events":28,"util":32}],9:[function(require,module,exports){ module.exports = NameAddrHeader; /** * Dependencies. */ var URI = require('./URI'); var Grammar = require('./Grammar'); function NameAddrHeader(uri, display_name, parameters) { var param; // Checks if(!uri || !(uri instanceof URI)) { throw new TypeError('missing or invalid "uri" parameter'); } // Initialize parameters this.uri = uri; this.parameters = {}; for (param in parameters) { this.setParam(param, parameters[param]); } Object.defineProperties(this, { display_name: { get: function() { return display_name; }, set: function(value) { display_name = (value === 0) ? '0' : value; } } }); } NameAddrHeader.prototype = { setParam: function(key, value) { if (key) { this.parameters[key.toLowerCase()] = (typeof value === 'undefined' || value === null) ? null : value.toString(); } }, getParam: function(key) { if(key) { return this.parameters[key.toLowerCase()]; } }, hasParam: function(key) { if(key) { return (this.parameters.hasOwnProperty(key.toLowerCase()) && true) || false; } }, deleteParam: function(parameter) { var value; parameter = parameter.toLowerCase(); if (this.parameters.hasOwnProperty(parameter)) { value = this.parameters[parameter]; delete this.parameters[parameter]; return value; } }, clearParams: function() { this.parameters = {}; }, clone: function() { return new NameAddrHeader( this.uri.clone(), this.display_name, JSON.parse(JSON.stringify(this.parameters))); }, toString: function() { var body, parameter; body = (this.display_name || this.display_name === 0) ? '"' + this.display_name + '" ' : ''; body += '<' + this.uri.toString() + '>'; for (parameter in this.parameters) { body += ';' + parameter; if (this.parameters[parameter] !== null) { body += '='+ this.parameters[parameter]; } } return body; } }; /** * Parse the given string and returns a NameAddrHeader instance or undefined if * it is an invalid NameAddrHeader. */ NameAddrHeader.parse = function(name_addr_header) { name_addr_header = Grammar.parse(name_addr_header,'Name_Addr_Header'); if (name_addr_header !== -1) { return name_addr_header; } else { return undefined; } }; },{"./Grammar":6,"./URI":24}],10:[function(require,module,exports){ var Parser = {}; module.exports = Parser; /** * Dependencies. */ var debugerror = require('debug')('JsSIP:ERROR:Parser'); debugerror.log = console.warn.bind(console); var Grammar = require('./Grammar'); var SIPMessage = require('./SIPMessage'); /** * Extract and parse every header of a SIP message. */ function getHeader(data, headerStart) { var // 'start' position of the header. start = headerStart, // 'end' position of the header. end = 0, // 'partial end' position of the header. partialEnd = 0; //End of message. if (data.substring(start, start + 2).match(/(^\r\n)/)) { return -2; } while(end === 0) { // Partial End of Header. partialEnd = data.indexOf('\r\n', start); // 'indexOf' returns -1 if the value to be found never occurs. if (partialEnd === -1) { return partialEnd; } if(!data.substring(partialEnd + 2, partialEnd + 4).match(/(^\r\n)/) && data.charAt(partialEnd + 2).match(/(^\s+)/)) { // Not the end of the message. Continue from the next position. start = partialEnd + 2; } else { end = partialEnd; } } return end; } function parseHeader(message, data, headerStart, headerEnd) { var header, idx, length, parsed, hcolonIndex = data.indexOf(':', headerStart), headerName = data.substring(headerStart, hcolonIndex).trim(), headerValue = data.substring(hcolonIndex + 1, headerEnd).trim(); // If header-field is well-known, parse it. switch(headerName.toLowerCase()) { case 'via': case 'v': message.addHeader('via', headerValue); if(message.getHeaders('via').length === 1) { parsed = message.parseHeader('Via'); if(parsed) { message.via = parsed; message.via_branch = parsed.branch; } } else { parsed = 0; } break; case 'from': case 'f': message.setHeader('from', headerValue); parsed = message.parseHeader('from'); if(parsed) { message.from = parsed; message.from_tag = parsed.getParam('tag'); } break; case 'to': case 't': message.setHeader('to', headerValue); parsed = message.parseHeader('to'); if(parsed) { message.to = parsed; message.to_tag = parsed.getParam('tag'); } break; case 'record-route': parsed = Grammar.parse(headerValue, 'Record_Route'); if (parsed === -1) { parsed = undefined; } else { length = parsed.length; for (idx = 0; idx < length; idx++) { header = parsed[idx]; message.addHeader('record-route', headerValue.substring(header.possition, header.offset)); message.headers['Record-Route'][message.getHeaders('record-route').length - 1].parsed = header.parsed; } } break; case 'call-id': case 'i': message.setHeader('call-id', headerValue); parsed = message.parseHeader('call-id'); if(parsed) { message.call_id = headerValue; } break; case 'contact': case 'm': parsed = Grammar.parse(headerValue, 'Contact'); if (parsed === -1) { parsed = undefined; } else { length = parsed.length; for (idx = 0; idx < length; idx++) { header = parsed[idx]; message.addHeader('contact', headerValue.substring(header.possition, header.offset)); message.headers.Contact[message.getHeaders('contact').length - 1].parsed = header.parsed; } } break; case 'content-length': case 'l': message.setHeader('content-length', headerValue); parsed = message.parseHeader('content-length'); break; case 'content-type': case 'c': message.setHeader('content-type', headerValue); parsed = message.parseHeader('content-type'); break; case 'cseq': message.setHeader('cseq', headerValue); parsed = message.parseHeader('cseq'); if(parsed) { message.cseq = parsed.value; } if(message instanceof SIPMessage.IncomingResponse) { message.method = parsed.method; } break; case 'max-forwards': message.setHeader('max-forwards', headerValue); parsed = message.parseHeader('max-forwards'); break; case 'www-authenticate': message.setHeader('www-authenticate', headerValue); parsed = message.parseHeader('www-authenticate'); break; case 'proxy-authenticate': message.setHeader('proxy-authenticate', headerValue); parsed = message.parseHeader('proxy-authenticate'); break; case 'session-expires': case 'x': message.setHeader('session-expires', headerValue); parsed = message.parseHeader('session-expires'); if (parsed) { message.session_expires = parsed.expires; message.session_expires_refresher = parsed.refresher; } break; case 'refer-to': case 'r': message.setHeader('refer-to', headerValue); parsed = message.parseHeader('refer-to'); if(parsed) { message.refer_to = parsed; } break; case 'replaces': message.setHeader('replaces', headerValue); parsed = message.parseHeader('replaces'); if(parsed) { message.replaces = parsed; } break; case 'event': case 'o': message.setHeader('event', headerValue); parsed = message.parseHeader('event'); if(parsed) { message.event = parsed; } break; default: // Do not parse this header. message.setHeader(headerName, headerValue); parsed = 0; } if (parsed === undefined) { return { error: 'error parsing header "'+ headerName +'"' }; } else { return true; } } /** * Parse SIP Message */ Parser.parseMessage = function(data, ua) { var message, firstLine, contentLength, bodyStart, parsed, headerStart = 0, headerEnd = data.indexOf('\r\n'); if(headerEnd === -1) { debugerror('parseMessage() | no CRLF found, not a SIP message'); return; } // Parse first line. Check if it is a Request or a Reply. firstLine = data.substring(0, headerEnd); parsed = Grammar.parse(firstLine, 'Request_Response'); if(parsed === -1) { debugerror('parseMessage() | error parsing first line of SIP message: "' + firstLine + '"'); return; } else if(!parsed.status_code) { message = new SIPMessage.IncomingRequest(ua); message.method = parsed.method; message.ruri = parsed.uri; } else { message = new SIPMessage.IncomingResponse(); message.status_code = parsed.status_code; message.reason_phrase = parsed.reason_phrase; } message.data = data; headerStart = headerEnd + 2; /* Loop over every line in data. Detect the end of each header and parse * it or simply add to the headers collection. */ while(true) { headerEnd = getHeader(data, headerStart); // The SIP message has normally finished. if(headerEnd === -2) { bodyStart = headerStart + 2; break; } // data.indexOf returned -1 due to a malformed message. else if(headerEnd === -1) { debugerror('parseMessage() | malformed message'); return; } parsed = parseHeader(message, data, headerStart, headerEnd); if(parsed !== true) { debugerror('parseMessage() |', parsed.error); return; } headerStart = headerEnd + 2; } /* RFC3261 18.3. * If there are additional bytes in the transport packet * beyond the end of the body, they MUST be discarded. */ if(message.hasHeader('content-length')) { contentLength = message.getHeader('content-length'); message.body = data.substr(bodyStart, contentLength); } else { message.body = data.substring(bodyStart); } return message; }; },{"./Grammar":6,"./SIPMessage":18,"debug":34}],11:[function(require,module,exports){ /* globals RTCPeerConnection: false, RTCSessionDescription: false */ module.exports = RTCSession; var C = { // RTCSession states STATUS_NULL: 0, STATUS_INVITE_SENT: 1, STATUS_1XX_RECEIVED: 2, STATUS_INVITE_RECEIVED: 3, STATUS_WAITING_FOR_ANSWER: 4, STATUS_ANSWERED: 5, STATUS_WAITING_FOR_ACK: 6, STATUS_CANCELED: 7, STATUS_TERMINATED: 8, STATUS_CONFIRMED: 9 }; /** * Expose C object. */ RTCSession.C = C; /** * Dependencies. */ var util = require('util'); var events = require('events'); var debug = require('debug')('JsSIP:RTCSession'); var debugerror = require('debug')('JsSIP:ERROR:RTCSession'); debugerror.log = console.warn.bind(console); var sdp_transform = require('sdp-transform'); var JsSIP_C = require('./Constants'); var Exceptions = require('./Exceptions'); var Transactions = require('./Transactions'); var Utils = require('./Utils'); var Timers = require('./Timers'); var SIPMessage = require('./SIPMessage'); var Dialog = require('./Dialog'); var RequestSender = require('./RequestSender'); var RTCSession_Request = require('./RTCSession/Request'); var RTCSession_DTMF = require('./RTCSession/DTMF'); var RTCSession_ReferNotifier = require('./RTCSession/ReferNotifier'); var RTCSession_ReferSubscriber = require('./RTCSession/ReferSubscriber'); /** * Local variables. */ var holdMediaTypes = ['audio', 'video']; function RTCSession(ua) { debug('new'); this.ua = ua; this.status = C.STATUS_NULL; this.dialog = null; this.earlyDialogs = {}; this.connection = null; // The RTCPeerConnection instance (public attribute). // RTCSession confirmation flag this.is_confirmed = false; // is late SDP being negotiated this.late_sdp = false; // Default rtcOfferConstraints and rtcAnswerConstrainsts (passed in connect() or answer()). this.rtcOfferConstraints = null; this.rtcAnswerConstraints = null; // Local MediaStream. this.localMediaStream = null; this.localMediaStreamLocallyGenerated = false; // Flag to indicate PeerConnection ready for new actions. this.rtcReady = true; // SIP Timers this.timers = { ackTimer: null, expiresTimer: null, invite2xxTimer: null, userNoAnswerTimer: null }; // Session info this.direction = null; this.local_identity = null; this.remote_identity = null; this.start_time = null; this.end_time = null; this.tones = null; // Mute/Hold state this.audioMuted = false; this.videoMuted = false; this.localHold = false; this.remoteHold = false; // Session Timers (RFC 4028) this.sessionTimers = { enabled: this.ua.configuration.session_timers, defaultExpires: JsSIP_C.SESSION_EXPIRES, currentExpires: null, running: false, refresher: false, timer: null // A setTimeout. }; // Map of ReferSubscriber instances indexed by the REFER's CSeq number this.referSubscribers = {}; // Custom session empty object for high level use this.data = {}; // Expose session failed/ended causes as a property of the RTCSession instance this.causes = JsSIP_C.causes; events.EventEmitter.call(this); } util.inherits(RTCSession, events.EventEmitter); /** * User API */ RTCSession.prototype.isInProgress = function() { switch(this.status) { case C.STATUS_NULL: case C.STATUS_INVITE_SENT: case C.STATUS_1XX_RECEIVED: case C.STATUS_INVITE_RECEIVED: case C.STATUS_WAITING_FOR_ANSWER: return true; default: return false; } }; RTCSession.prototype.isEstablished = function() { switch(this.status) { case C.STATUS_ANSWERED: case C.STATUS_WAITING_FOR_ACK: case C.STATUS_CONFIRMED: return true; default: return false; } }; RTCSession.prototype.isEnded = function() { switch(this.status) { case C.STATUS_CANCELED: case C.STATUS_TERMINATED: return true; default: return false; } }; RTCSession.prototype.isMuted = function() { return { audio: this.audioMuted, video: this.videoMuted }; }; RTCSession.prototype.isOnHold = function() { return { local: this.localHold, remote: this.remoteHold }; }; /** * Check if RTCSession is ready for an outgoing re-INVITE or UPDATE with SDP. */ RTCSession.prototype.isReadyToReOffer = function() { if (! this.rtcReady) { debug('isReadyToReOffer() | internal WebRTC status not ready'); return false; } // No established yet. if (! this.dialog) { debug('isReadyToReOffer() | session not established yet'); return false; } // Another INVITE transaction is in progress if (this.dialog.uac_pending_reply === true || this.dialog.uas_pending_reply === true) { debug('isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress'); return false; } return true; }; RTCSession.prototype.connect = function(target, options, initCallback) { debug('connect()'); options = options || {}; var event, requestParams, originalTarget = target, eventHandlers = options.eventHandlers || {}, extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], mediaConstraints = options.mediaConstraints || {audio: true, video: true}, mediaStream = options.mediaStream || null, pcConfig = options.pcConfig || {iceServers:[]}, rtcConstraints = options.rtcConstraints || null, rtcOfferConstraints = options.rtcOfferConstraints || null; this.rtcOfferConstraints = rtcOfferConstraints; this.rtcAnswerConstraints = options.rtcAnswerConstraints || null; // Session Timers. if (this.sessionTimers.enabled) { if (Utils.isDecimal(options.sessionTimersExpires)) { if (options.sessionTimersExpires >= JsSIP_C.MIN_SESSION_EXPIRES) { this.sessionTimers.defaultExpires = options.sessionTimersExpires; } else { this.sessionTimers.defaultExpires = JsSIP_C.SESSION_EXPIRES; } } } this.data = options.data || this.data; if (target === undefined) { throw new TypeError('Not enough arguments'); } // Check WebRTC support. if (!window.RTCPeerConnection) { throw new Exceptions.NotSupportedError('WebRTC not supported'); } // Check target validity target = this.ua.normalizeTarget(target); if (!target) { throw new TypeError('Invalid target: '+ originalTarget); } // Check Session Status if (this.status !== C.STATUS_NULL) { throw new Exceptions.InvalidStateError(this.status); } // Set event handlers for (event in eventHandlers) { this.on(event, eventHandlers[event]); } // Session parameter initialization this.from_tag = Utils.newTag(); // Set anonymous property this.anonymous = options.anonymous || false; // OutgoingSession specific parameters this.isCanceled = false; requestParams = {from_tag: this.from_tag}; this.contact = this.ua.contact.toString({ anonymous: this.anonymous, outbound: true }); if (this.anonymous) { requestParams.from_display_name = 'Anonymous'; requestParams.from_uri = 'sip:[email protected]'; extraHeaders.push('P-Preferred-Identity: '+ this.ua.configuration.uri.toString()); extraHeaders.push('Privacy: id'); } extraHeaders.push('Contact: '+ this.contact); extraHeaders.push('Content-Type: application/sdp'); if (this.sessionTimers.enabled) { extraHeaders.push('Session-Expires: ' + this.sessionTimers.defaultExpires); } this.request = new SIPMessage.OutgoingRequest(JsSIP_C.INVITE, target, this.ua, requestParams, extraHeaders); this.id = this.request.call_id + this.from_tag; // Create a new RTCPeerConnection instance. createRTCConnection.call(this, pcConfig, rtcConstraints); // Save the session into the ua sessions collection. this.ua.sessions[this.id] = this; // Set internal properties this.direction = 'outgoing'; this.local_identity = this.request.from; this.remote_identity = this.request.to; // User explicitly provided a newRTCSession callback for this session if (initCallback) { initCallback(this); } else { newRTCSession.call(this, 'local', this.request); } sendInitialRequest.call(this, mediaConstraints, rtcOfferConstraints, mediaStream); }; RTCSession.prototype.init_incoming = function(request, initCallback) { debug('init_incoming()'); var expires, self = this, contentType = request.getHeader('Content-Type'); // Check body and content type if (request.body && (contentType !== 'application/sdp')) { request.reply(415); return; } // Session parameter initialization this.status = C.STATUS_INVITE_RECEIVED; this.from_tag = request.from_tag; this.id = request.call_id + this.from_tag; this.request = request; this.contact = this.ua.contact.toString(); // Save the session into the ua sessions collection. this.ua.sessions[this.id] = this; // Get the Expires header value if exists if (request.hasHeader('expires')) { expires = request.getHeader('expires') * 1000; } /* Set the to_tag before * replying a response code that will create a dialog. */ request.to_tag = Utils.newTag(); // An error on dialog creation will fire 'failed' event if (! createDialog.call(this, request, 'UAS', true)) { request.reply(500, 'Missing Contact header field'); return; } if (request.body) { this.late_sdp = false; } else { this.late_sdp = true; } this.status = C.STATUS_WAITING_FOR_ANSWER; // Set userNoAnswerTimer this.timers.userNoAnswerTimer = setTimeout(function() { request.reply(408); failed.call(self, 'local',null, JsSIP_C.causes.NO_ANSWER); }, this.ua.configuration.no_answer_timeout ); /* Set expiresTimer * RFC3261 13.3.1 */ if (expires) { this.timers.expiresTimer = setTimeout(function() { if(self.status === C.STATUS_WAITING_FOR_ANSWER) { request.reply(487); failed.call(self, 'system', null, JsSIP_C.causes.EXPIRES); } }, expires ); } // Set internal properties this.direction = 'incoming'; this.local_identity = request.to; this.remote_identity = request.from; // A init callback was specifically defined if (initCallback) { initCallback(this); // Fire 'newRTCSession' event. } else { newRTCSession.call(this, 'remote', request); } // The user may have rejected the call in the 'newRTCSession' event. if (this.status === C.STATUS_TERMINATED) { return; } // Reply 180. request.reply(180, null, ['Contact: ' + self.contact]); // Fire 'progress' event. // TODO: Document that 'response' field in 'progress' event is null for // incoming calls. progress.call(self, 'local', null); }; /** * Answer the call. */ RTCSession.prototype.answer = function(options) { debug('answer()'); options = options || {}; var idx, length, sdp, tracks, peerHasAudioLine = false, peerHasVideoLine = false, peerOffersFullAudio = false, peerOffersFullVideo = false, self = this, request = this.request, extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], mediaConstraints = options.mediaConstraints || {}, mediaStream = options.mediaStream || null, pcConfig = options.pcConfig || {iceServers:[]}, rtcConstraints = options.rtcConstraints || null, rtcAnswerConstraints = options.rtcAnswerConstraints || null; this.rtcAnswerConstraints = rtcAnswerConstraints; this.rtcOfferConstraints = options.rtcOfferConstraints || null; // Session Timers. if (this.sessionTimers.enabled) { if (Utils.isDecimal(options.sessionTimersExpires)) { if (options.sessionTimersExpires >= JsSIP_C.MIN_SESSION_EXPIRES) { this.sessionTimers.defaultExpires = options.sessionTimersExpires; } else { this.sessionTimers.defaultExpires = JsSIP_C.SESSION_EXPIRES; } } } this.data = options.data || this.data; // Check Session Direction and Status if (this.direction !== 'incoming') { throw new Exceptions.NotSupportedError('"answer" not supported for outgoing RTCSession'); } else if (this.status !== C.STATUS_WAITING_FOR_ANSWER) { throw new Exceptions.InvalidStateError(this.status); } this.status = C.STATUS_ANSWERED; // An error on dialog creation will fire 'failed' event if (! createDialog.call(this, request, 'UAS')) { request.reply(500, 'Error creating dialog'); return; } clearTimeout(this.timers.userNoAnswerTimer); extraHeaders.unshift('Contact: ' + self.contact); // Determine incoming media from incoming SDP offer (if any). sdp = request.parseSDP(); // Make sure sdp.media is an array, not the case if there is only one media if (! Array.isArray(sdp.media)) { sdp.media = [sdp.media]; } // Go through all medias in SDP to find offered capabilities to answer with idx = sdp.media.length; while(idx--) { var m = sdp.media[idx]; if (m.type === 'audio') { peerHasAudioLine = true; if (!m.direction || m.direction === 'sendrecv') { peerOffersFullAudio = true; } } if (m.type === 'video') { peerHasVideoLine = true; if (!m.direction || m.direction === 'sendrecv') { peerOffersFullVideo = true; } } } // Remove audio from mediaStream if suggested by mediaConstraints if (mediaStream && mediaConstraints.audio === false) { tracks = mediaStream.getAudioTracks(); length = tracks.length; for (idx=0; idx<length; idx++) { mediaStream.removeTrack(tracks[idx]); } } // Remove video from mediaStream if suggested by mediaConstraints if (mediaStream && mediaConstraints.video === false) { tracks = mediaStream.getVideoTracks(); length = tracks.length; for (idx=0; idx<length; idx++) { mediaStream.removeTrack(tracks[idx]); } } // Set audio constraints based on incoming stream if not supplied if (!mediaStream && mediaConstraints.audio === undefined) { mediaConstraints.audio = peerOffersFullAudio; } // Set video constraints based on incoming stream if not supplied if (!mediaStream && mediaConstraints.video === undefined) { mediaConstraints.video = peerOffersFullVideo; } // Don't ask for audio if the incoming offer has no audio section if (!mediaStream && !peerHasAudioLine) { mediaConstraints.audio = false; } // Don't ask for video if the incoming offer has no video section if (!mediaStream && !peerHasVideoLine) { mediaConstraints.video = false; } // Create a new RTCPeerConnection instance. // TODO: This may throw an error, should react. createRTCConnection.call(this, pcConfig, rtcConstraints); // If a local MediaStream is given use it. if (mediaStream) { userMediaSucceeded(mediaStream); // If at least audio or video is requested prompt getUserMedia. } else if (mediaConstraints.audio || mediaConstraints.video) { self.localMediaStreamLocallyGenerated = true; navigator.mediaDevices.getUserMedia(mediaConstraints) .then(userMediaSucceeded) .catch(function(error) { userMediaFailed(error); self.emit('getusermediafailed', error); }); // Otherwise don't prompt getUserMedia. } else { userMediaSucceeded(null); } // User media succeeded function userMediaSucceeded(stream) { if (self.status === C.STATUS_TERMINATED) { return; } self.localMediaStream = stream; if (stream) { self.connection.addStream(stream); } // If it's an incoming INVITE without SDP notify the app with the // RTCPeerConnection so it can do stuff on it before generating the offer. if (! self.request.body) { self.emit('peerconnection', { peerconnection: self.connection }); } if (! self.late_sdp) { var e = {originator:'remote', type:'offer', sdp:request.body}; var offer = new RTCSessionDescription({type:'offer', sdp:e.sdp}); self.emit('sdp', e); self.connection.setRemoteDescription(offer) .then(remoteDescriptionSucceededOrNotNeeded) .catch(function(error) { request.reply(488); failed.call(self, 'system', null, JsSIP_C.causes.WEBRTC_ERROR); self.emit('peerconnection:setremotedescriptionfailed', error); }); } else { remoteDescriptionSucceededOrNotNeeded(); } } // User media failed function userMediaFailed() { if (self.status === C.STATUS_TERMINATED) { return; } request.reply(480); failed.call(self, 'local', null, JsSIP_C.causes.USER_DENIED_MEDIA_ACCESS); } function remoteDescriptionSucceededOrNotNeeded() { connecting.call(self, request); if (! self.late_sdp) { createLocalDescription.call(self, 'answer', rtcSucceeded, rtcFailed, rtcAnswerConstraints); } else { createLocalDescription.call(self, 'offer', rtcSucceeded, rtcFailed, self.rtcOfferConstraints); } } function rtcSucceeded(desc) { if (self.status === C.STATUS_TERMINATED) { return; } // run for reply success callback function replySucceeded() { self.status = C.STATUS_WAITING_FOR_ACK; setInvite2xxTimer.call(self, request, desc); setACKTimer.call(self); accepted.call(self, 'local'); } // run for reply failure callback function replyFailed() { failed.call(self, 'system', null, JsSIP_C.causes.CONNECTION_ERROR); } handleSessionTimersInIncomingRequest.call(self, request, extraHeaders); request.reply(200, null, extraHeaders, desc, replySucceeded, replyFailed ); } function rtcFailed() { if (self.status === C.STATUS_TERMINATED) { return; } request.reply(500); failed.call(self, 'system', null, JsSIP_C.causes.WEBRTC_ERROR); } }; /** * Terminate the call. */ RTCSession.prototype.terminate = function(options) { debug('terminate()'); options = options || {}; var cancel_reason, dialog, cause = options.cause || JsSIP_C.causes.BYE, status_code = options.status_code, reason_phrase = options.reason_phrase, extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], body = options.body, self = this; // Check Session Status if (this.status === C.STATUS_TERMINATED) { throw new Exceptions.InvalidStateError(this.status); } switch(this.status) { // - UAC - case C.STATUS_NULL: case C.STATUS_INVITE_SENT: case C.STATUS_1XX_RECEIVED: debug('canceling session'); if (status_code && (status_code < 200 || status_code >= 700)) { throw new TypeError('Invalid status_code: '+ status_code); } else if (status_code) { reason_phrase = reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || ''; cancel_reason = 'SIP ;cause=' + status_code + ' ;text="' + reason_phrase + '"'; } // Check Session Status if (this.status === C.STATUS_NULL) { this.isCanceled = true; this.cancelReason = cancel_reason; } else if (this.status === C.STATUS_INVITE_SENT) { this.isCanceled = true; this.cancelReason = cancel_reason; } else if(this.status === C.STATUS_1XX_RECEIVED) { this.request.cancel(cancel_reason); } this.status = C.STATUS_CANCELED; failed.call(this, 'local', null, JsSIP_C.causes.CANCELED); break; // - UAS - case C.STATUS_WAITING_FOR_ANSWER: case C.STATUS_ANSWERED: debug('rejecting session'); status_code = status_code || 480; if (status_code < 300 || status_code >= 700) { throw new TypeError('Invalid status_code: '+ status_code); } this.request.reply(status_code, reason_phrase, extraHeaders, body); failed.call(this, 'local', null, JsSIP_C.causes.REJECTED); break; case C.STATUS_WAITING_FOR_ACK: case C.STATUS_CONFIRMED: debug('terminating session'); reason_phrase = options.reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || ''; if (status_code && (status_code < 200 || status_code >= 700)) { throw new TypeError('Invalid status_code: '+ status_code); } else if (status_code) { extraHeaders.push('Reason: SIP ;cause=' + status_code + '; text="' + reason_phrase + '"'); } /* RFC 3261 section 15 (Terminating a session): * * "...the callee's UA MUST NOT send a BYE on a confirmed dialog * until it has received an ACK for its 2xx response or until the server * transaction times out." */ if (this.status === C.STATUS_WAITING_FOR_ACK && this.direction === 'incoming' && this.request.server_transaction.state !== Transactions.C.STATUS_TERMINATED) { // Save the dialog for later restoration dialog = this.dialog; // Send the BYE as soon as the ACK is received... this.receiveRequest = function(request) { if(request.method === JsSIP_C.ACK) { sendRequest.call(this, JsSIP_C.BYE, { extraHeaders: extraHeaders, body: body }); dialog.terminate(); } }; // .., or when the INVITE transaction times out this.request.server_transaction.on('stateChanged', function(){ if (this.state === Transactions.C.STATUS_TERMINATED) { sendRequest.call(self, JsSIP_C.BYE, { extraHeaders: extraHeaders, body: body }); dialog.terminate(); } }); ended.call(this, 'local', null, cause); // Restore the dialog into 'this' in order to be able to send the in-dialog BYE :-) this.dialog = dialog; // Restore the dialog into 'ua' so the ACK can reach 'this' session this.ua.dialogs[dialog.id.toString()] = dialog; } else { sendRequest.call(this, JsSIP_C.BYE, { extraHeaders: extraHeaders, body: body }); ended.call(this, 'local', null, cause); } } }; RTCSession.prototype.close = function() { debug('close()'); var idx; if (this.status === C.STATUS_TERMINATED) { return; } // Terminate RTC. if (this.connection) { try { this.connection.close(); } catch(error) { debugerror('close() | error closing the RTCPeerConnection: %o', error); } } // Close local MediaStream if it was not given by the user. if (this.localMediaStream && this.localMediaStreamLocallyGenerated) { debug('close() | closing local MediaStream'); Utils.closeMediaStream(this.localMediaStream); } // Terminate signaling. // Clear SIP timers for(idx in this.timers) { clearTimeout(this.timers[idx]); } // Clear Session Timers. clearTimeout(this.sessionTimers.timer); // Terminate confirmed dialog if (this.dialog) { this.dialog.terminate(); delete this.dialog; } // Terminate early dialogs for(idx in this.earlyDialogs) { this.earlyDialogs[idx].terminate(); delete this.earlyDialogs[idx]; } this.status = C.STATUS_TERMINATED; delete this.ua.sessions[this.id]; }; RTCSession.prototype.sendDTMF = function(tones, options) { debug('sendDTMF() | tones: %s', tones); var duration, interToneGap, position = 0, self = this; options = options || {}; duration = options.duration || null; interToneGap = options.interToneGap || null; if (tones === undefined) { throw new TypeError('Not enough arguments'); } // Check Session Status if (this.status !== C.STATUS_CONFIRMED && this.status !== C.STATUS_WAITING_FOR_ACK) { throw new Exceptions.InvalidStateError(this.status); } // Convert to string if(typeof tones === 'number') { tones = tones.toString(); } // Check tones if (!tones || typeof tones !== 'string' || !tones.match(/^[0-9A-DR#*,]+$/i)) { throw new TypeError('Invalid tones: '+ tones); } // Check duration if (duration && !Utils.isDecimal(duration)) { throw new TypeError('Invalid tone duration: '+ duration); } else if (!duration) { duration = RTCSession_DTMF.C.DEFAULT_DURATION; } else if (duration < RTCSession_DTMF.C.MIN_DURATION) { debug('"duration" value is lower than the minimum allowed, setting it to '+ RTCSession_DTMF.C.MIN_DURATION+ ' milliseconds'); duration = RTCSession_DTMF.C.MIN_DURATION; } else if (duration > RTCSession_DTMF.C.MAX_DURATION) { debug('"duration" value is greater than the maximum allowed, setting it to '+ RTCSession_DTMF.C.MAX_DURATION +' milliseconds'); duration = RTCSession_DTMF.C.MAX_DURATION; } else { duration = Math.abs(duration); } options.duration = duration; // Check interToneGap if (interToneGap && !Utils.isDecimal(interToneGap)) { throw new TypeError('Invalid interToneGap: '+ interToneGap); } else if (!interToneGap) { interToneGap = RTCSession_DTMF.C.DEFAULT_INTER_TONE_GAP; } else if (interToneGap < RTCSession_DTMF.C.MIN_INTER_TONE_GAP) { debug('"interToneGap" value is lower than the minimum allowed, setting it to '+ RTCSession_DTMF.C.MIN_INTER_TONE_GAP +' milliseconds'); interToneGap = RTCSession_DTMF.C.MIN_INTER_TONE_GAP; } else { interToneGap = Math.abs(interToneGap); } if (this.tones) { // Tones are already queued, just add to the queue this.tones += tones; return; } this.tones = tones; // Send the first tone _sendDTMF(); function _sendDTMF() { var tone, timeout; if (self.status === C.STATUS_TERMINATED || !self.tones || position >= self.tones.length) { // Stop sending DTMF self.tones = null; return; } tone = self.tones[position]; position += 1; if (tone === ',') { timeout = 2000; } else { var dtmf = new RTCSession_DTMF(self); options.eventHandlers = { onFailed: function() { self.tones = null; } }; dtmf.send(tone, options); timeout = duration + interToneGap; } // Set timeout for the next tone setTimeout(_sendDTMF, timeout); } }; /** * Mute */ RTCSession.prototype.mute = function(options) { debug('mute()'); options = options || {audio:true, video:false}; var audioMuted = false, videoMuted = false; if (this.audioMuted === false && options.audio) { audioMuted = true; this.audioMuted = true; toogleMuteAudio.call(this, true); } if (this.videoMuted === false && options.video) { videoMuted = true; this.videoMuted = true; toogleMuteVideo.call(this, true); } if (audioMuted === true || videoMuted === true) { onmute.call(this, { audio: audioMuted, video: videoMuted }); } }; /** * Unmute */ RTCSession.prototype.unmute = function(options) { debug('unmute()'); options = options || {audio:true, video:true}; var audioUnMuted = false, videoUnMuted = false; if (this.audioMuted === true && options.audio) { audioUnMuted = true; this.audioMuted = false; if (this.localHold === false) { toogleMuteAudio.call(this, false); } } if (this.videoMuted === true && options.video) { videoUnMuted = true; this.videoMuted = false; if (this.localHold === false) { toogleMuteVideo.call(this, false); } } if (audioUnMuted === true || videoUnMuted === true) { onunmute.call(this, { audio: audioUnMuted, video: videoUnMuted }); } }; /** * Hold */ RTCSession.prototype.hold = function(options, done) { debug('hold()'); options = options || {}; var self = this, eventHandlers; if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) { return false; } if (this.localHold === true) { return false; } if (! this.isReadyToReOffer()) { return false; } this.localHold = true; onhold.call(this, 'local'); eventHandlers = { succeeded: function() { if (done) { done(); } }, failed: function() { self.terminate({ cause: JsSIP_C.causes.WEBRTC_ERROR, status_code: 500, reason_phrase: 'Hold Failed' }); } }; if (options.useUpdate) { sendUpdate.call(this, { sdpOffer: true, eventHandlers: eventHandlers, extraHeaders: options.extraHeaders }); } else { sendReinvite.call(this, { eventHandlers: eventHandlers, extraHeaders: options.extraHeaders }); } return true; }; RTCSession.prototype.unhold = function(options, done) { debug('unhold()'); options = options || {}; var self = this, eventHandlers; if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) { return false; } if (this.localHold === false) { return false; } if (! this.isReadyToReOffer()) { return false; } this.localHold = false; onunhold.call(this, 'local'); eventHandlers = { succeeded: function() { if (done) { done(); } }, failed: function() { self.terminate({ cause: JsSIP_C.causes.WEBRTC_ERROR, status_code: 500, reason_phrase: 'Unhold Failed' }); } }; if (options.useUpdate) { sendUpdate.call(this, { sdpOffer: true, eventHandlers: eventHandlers, extraHeaders: options.extraHeaders }); } else { sendReinvite.call(this, { eventHandlers: eventHandlers, extraHeaders: options.extraHeaders }); } return true; }; RTCSession.prototype.renegotiate = function(options, done) { debug('renegotiate()'); options = options || {}; var self = this, eventHandlers, rtcOfferConstraints = options.rtcOfferConstraints || null; if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) { return false; } if (! this.isReadyToReOffer()) { return false; } eventHandlers = { succeeded: function() { if (done) { done(); } }, failed: function() { self.terminate({ cause: JsSIP_C.causes.WEBRTC_ERROR, status_code: 500, reason_phrase: 'Media Renegotiation Failed' }); } }; setLocalMediaStatus.call(this); if (options.useUpdate) { sendUpdate.call(this, { sdpOffer: true, eventHandlers: eventHandlers, rtcOfferConstraints: rtcOfferConstraints, extraHeaders: options.extraHeaders }); } else { sendReinvite.call(this, { eventHandlers: eventHandlers, rtcOfferConstraints: rtcOfferConstraints, extraHeaders: options.extraHeaders }); } return true; }; /** * Refer */ RTCSession.prototype.refer = function(target, options) { debug('refer()'); var self = this, originalTarget = target, referSubscriber, id; if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) { return false; } // Check target validity target = this.ua.normalizeTarget(target); if (!target) { throw new TypeError('Invalid target: '+ originalTarget); } referSubscriber = new RTCSession_ReferSubscriber(this); referSubscriber.sendRefer(target, options); // Store in the map id = referSubscriber.outgoingRequest.cseq; this.referSubscribers[id] = referSubscriber; // Listen for ending events so we can remove it from the map referSubscriber.on('requestFailed', function() { delete self.referSubscribers[id]; }); referSubscriber.on('accepted', function() { delete self.referSubscribers[id]; }); referSubscriber.on('failed', function() { delete self.referSubscribers[id]; }); return referSubscriber; }; /** * In dialog Request Reception */ RTCSession.prototype.receiveRequest = function(request) { debug('receiveRequest()'); var contentType, self = this; if(request.method === JsSIP_C.CANCEL) { /* RFC3261 15 States that a UAS may have accepted an invitation while a CANCEL * was in progress and that the UAC MAY continue with the session established by * any 2xx response, or MAY terminate with BYE. JsSIP does continue with the * established session. So the CANCEL is processed only if the session is not yet * established. */ /* * Terminate the whole session in case the user didn't accept (or yet send the answer) * nor reject the request opening the session. */ if(this.status === C.STATUS_WAITING_FOR_ANSWER || this.status === C.STATUS_ANSWERED) { this.status = C.STATUS_CANCELED; this.request.reply(487); failed.call(this, 'remote', request, JsSIP_C.causes.CANCELED); } } else { // Requests arriving here are in-dialog requests. switch(request.method) { case JsSIP_C.ACK: if (this.status !== C.STATUS_WAITING_FOR_ACK) { return; } // Update signaling status. this.status = C.STATUS_CONFIRMED; clearTimeout(this.timers.ackTimer); clearTimeout(this.timers.invite2xxTimer); if (this.late_sdp) { if (!request.body) { this.terminate({ cause: JsSIP_C.causes.MISSING_SDP, status_code: 400 }); break; } var e = {originator:'remote', type:'answer', sdp:request.body}; var answer = new RTCSessionDescription({type:'answer', sdp:e.sdp}); this.emit('sdp', e); this.connection.setRemoteDescription(answer) .then(function() { if (!self.is_confirmed) { confirmed.call(self, 'remote', request); } }) .catch(function(error) { self.terminate({ cause: JsSIP_C.causes.BAD_MEDIA_DESCRIPTION, status_code: 488 }); self.emit('peerconnection:setremotedescriptionfailed', error); }); } else { if (!this.is_confirmed) { confirmed.call(this, 'remote', request); } } break; case JsSIP_C.BYE: if(this.status === C.STATUS_CONFIRMED) { request.reply(200); ended.call(this, 'remote', request, JsSIP_C.causes.BYE); } else if (this.status === C.STATUS_INVITE_RECEIVED) { request.reply(200); this.request.reply(487, 'BYE Received'); ended.call(this, 'remote', request, JsSIP_C.causes.BYE); } else { request.reply(403, 'Wrong Status'); } break; case JsSIP_C.INVITE: if(this.status === C.STATUS_CONFIRMED) { if (request.hasHeader('replaces')) { receiveReplaces.call(this, request); } else { receiveReinvite.call(this, request); } } else { request.reply(403, 'Wrong Status'); } break; case JsSIP_C.INFO: if(this.status === C.STATUS_CONFIRMED || this.status === C.STATUS_WAITING_FOR_ACK || this.status === C.STATUS_INVITE_RECEIVED) { contentType = request.getHeader('content-type'); if (contentType && (contentType.match(/^application\/dtmf-relay/i))) { new RTCSession_DTMF(this).init_incoming(request); } else { request.reply(415); } } else { request.reply(403, 'Wrong Status'); } break; case JsSIP_C.UPDATE: if(this.status === C.STATUS_CONFIRMED) { receiveUpdate.call(this, request); } else { request.reply(403, 'Wrong Status'); } break; case JsSIP_C.REFER: if(this.status === C.STATUS_CONFIRMED) { receiveRefer.call(this, request); } else { request.reply(403, 'Wrong Status'); } break; case JsSIP_C.NOTIFY: if(this.status === C.STATUS_CONFIRMED) { receiveNotify.call(this, request); } else { request.reply(403, 'Wrong Status'); } break; default: request.reply(501); } } }; /** * Session Callbacks */ RTCSession.prototype.onTransportError = function() { debugerror('onTransportError()'); if(this.status !== C.STATUS_TERMINATED) { this.terminate({ status_code: 500, reason_phrase: JsSIP_C.causes.CONNECTION_ERROR, cause: JsSIP_C.causes.CONNECTION_ERROR }); } }; RTCSession.prototype.onRequestTimeout = function() { debug('onRequestTimeout'); if(this.status !== C.STATUS_TERMINATED) { this.terminate({ status_code: 408, reason_phrase: JsSIP_C.causes.REQUEST_TIMEOUT, cause: JsSIP_C.causes.REQUEST_TIMEOUT }); } }; RTCSession.prototype.onDialogError = function() { debugerror('onDialogError()'); if(this.status !== C.STATUS_TERMINATED) { this.terminate({ status_code: 500, reason_phrase: JsSIP_C.causes.DIALOG_ERROR, cause: JsSIP_C.causes.DIALOG_ERROR }); } }; // Called from DTMF handler. RTCSession.prototype.newDTMF = function(data) { debug('newDTMF()'); this.emit('newDTMF', data); }; RTCSession.prototype.resetLocalMedia = function() { debug('resetLocalMedia()'); // Reset all but remoteHold. this.localHold = false; this.audioMuted = false; this.videoMuted = false; setLocalMediaStatus.call(this); }; /** * Private API. */ /** * RFC3261 13.3.1.4 * Response retransmissions cannot be accomplished by transaction layer * since it is destroyed when receiving the first 2xx answer */ function setInvite2xxTimer(request, body) { var self = this, timeout = Timers.T1; this.timers.invite2xxTimer = setTimeout(function invite2xxRetransmission() { if (self.status !== C.STATUS_WAITING_FOR_ACK) { return; } request.reply(200, null, ['Contact: '+ self.contact], body); if (timeout < Timers.T2) { timeout = timeout * 2; if (timeout > Timers.T2) { timeout = Timers.T2; } } self.timers.invite2xxTimer = setTimeout( invite2xxRetransmission, timeout ); }, timeout); } /** * RFC3261 14.2 * If a UAS generates a 2xx response and never receives an ACK, * it SHOULD generate a BYE to terminate the dialog. */ function setACKTimer() { var self = this; this.timers.ackTimer = setTimeout(function() { if(self.status === C.STATUS_WAITING_FOR_ACK) { debug('no ACK received, terminating the session'); clearTimeout(self.timers.invite2xxTimer); sendRequest.call(self, JsSIP_C.BYE); ended.call(self, 'remote', null, JsSIP_C.causes.NO_ACK); } }, Timers.TIMER_H); } function createRTCConnection(pcConfig, rtcConstraints) { var self = this; this.connection = new RTCPeerConnection(pcConfig, rtcConstraints); this.connection.addEventListener('iceconnectionstatechange', function() { var state = self.connection.iceConnectionState; // TODO: Do more with different states. if (state === 'failed') { self.terminate({ cause: JsSIP_C.causes.RTP_TIMEOUT, status_code: 200, reason_phrase: JsSIP_C.causes.RTP_TIMEOUT }); } }); } function createLocalDescription(type, onSuccess, onFailure, constraints) { debug('createLocalDescription()'); var self = this; var connection = this.connection; this.rtcReady = false; if (type === 'offer') { connection.createOffer(constraints) .then(createSucceeded) .catch(function(error) { self.rtcReady = true; if (onFailure) { onFailure(error); } self.emit('peerconnection:createofferfailed', error); }); } else if (type === 'answer') { connection.createAnswer(constraints) .then(createSucceeded) .catch(function(error) { self.rtcReady = true; if (onFailure) { onFailure(error); } self.emit('peerconnection:createanswerfailed', error); }); } else { throw new Error('createLocalDescription() | type must be "offer" or "answer", but "' +type+ '" was given'); } // createAnswer or createOffer succeeded function createSucceeded(desc) { var listener; connection.addEventListener('icecandidate', listener = function(event) { var candidate = event.candidate; if (! candidate) { connection.removeEventListener('icecandidate', listener); self.rtcReady = true; if (onSuccess) { var e = {originator:'local', type:type, sdp:connection.localDescription.sdp}; self.emit('sdp', e); onSuccess(e.sdp); } onSuccess = null; } }); connection.setLocalDescription(desc) .then(function() { if (connection.iceGatheringState === 'complete') { self.rtcReady = true; if (onSuccess) { var e = {originator:'local', type:type, sdp:connection.localDescription.sdp}; self.emit('sdp', e); onSuccess(e.sdp); onSuccess = null; } } }) .catch(function(error) { self.rtcReady = true; if (onFailure) { onFailure(error); } self.emit('peerconnection:setlocaldescriptionfailed', error); }); } } /** * Dialog Management */ function createDialog(message, type, early) { var dialog, early_dialog, local_tag = (type === 'UAS') ? message.to_tag : message.from_tag, remote_tag = (type === 'UAS') ? message.from_tag : message.to_tag, id = message.call_id + local_tag + remote_tag; early_dialog = this.earlyDialogs[id]; // Early Dialog if (early) { if (early_dialog) { return true; } else { early_dialog = new Dialog(this, message, type, Dialog.C.STATUS_EARLY); // Dialog has been successfully created. if(early_dialog.error) { debug(early_dialog.error); failed.call(this, 'remote', message, JsSIP_C.causes.INTERNAL_ERROR); return false; } else { this.earlyDialogs[id] = early_dialog; return true; } } } // Confirmed Dialog else { this.from_tag = message.from_tag; this.to_tag = message.to_tag; // In case the dialog is in _early_ state, update it if (early_dialog) { early_dialog.update(message, type); this.dialog = early_dialog; delete this.earlyDialogs[id]; return true; } // Otherwise, create a _confirmed_ dialog dialog = new Dialog(this, message, type); if(dialog.error) { debug(dialog.error); failed.call(this, 'remote', message, JsSIP_C.causes.INTERNAL_ERROR); return false; } else { this.dialog = dialog; return true; } } } /** * In dialog INVITE Reception */ function receiveReinvite(request) { debug('receiveReinvite()'); var sdp, idx, direction, m, self = this, contentType = request.getHeader('Content-Type'), hold = false, rejected = false, data = { request: request, callback: undefined, reject: reject.bind(this) }; function reject(options) { options = options || {}; rejected = true; var status_code = options.status_code || 403, reason_phrase = options.reason_phrase || '', extraHeaders = options.extraHeaders && options.extraHeaders.slice() || []; if (this.status !== C.STATUS_CONFIRMED) { return false; } if (status_code < 300 || status_code >= 700) { throw new TypeError('Invalid status_code: '+ status_code); } request.reply(status_code, reason_phrase, extraHeaders); } // Emit 'reinvite'. this.emit('reinvite', data); if (rejected) { return; } if (request.body) { this.late_sdp = false; if (contentType !== 'application/sdp') { debug('invalid Content-Type'); request.reply(415); return; } sdp = request.parseSDP(); for (idx=0; idx < sdp.media.length; idx++) { m = sdp.media[idx]; if (holdMediaTypes.indexOf(m.type) === -1) { continue; } direction = m.direction || sdp.direction || 'sendrecv'; if (direction === 'sendonly' || direction === 'inactive') { hold = true; } // If at least one of the streams is active don't emit 'hold'. else { hold = false; break; } } var e = {originator:'remote', type:'offer', sdp:request.body}; var offer = new RTCSessionDescription({type:'offer', sdp:e.sdp}); this.emit('sdp', e); this.connection.setRemoteDescription(offer) .then(doAnswer) .catch(function(error) { request.reply(488); self.emit('peerconnection:setremotedescriptionfailed', error); }); } else { this.late_sdp = true; doAnswer(); } function doAnswer() { createSdp( // onSuccess function(sdp) { var extraHeaders = ['Contact: ' + self.contact]; handleSessionTimersInIncomingRequest.call(self, request, extraHeaders); if (self.late_sdp) { sdp = mangleOffer.call(self, sdp); } request.reply(200, null, extraHeaders, sdp, function() { self.status = C.STATUS_WAITING_FOR_ACK; setInvite2xxTimer.call(self, request, sdp); setACKTimer.call(self); } ); // If callback is given execute it. if (typeof data.callback === 'function') { data.callback(); } }, // onFailure function() { request.reply(500); } ); } function createSdp(onSuccess, onFailure) { if (! self.late_sdp) { if (self.remoteHold === true && hold === false) { self.remoteHold = false; onunhold.call(self, 'remote'); } else if (self.remoteHold === false && hold === true) { self.remoteHold = true; onhold.call(self, 'remote'); } createLocalDescription.call(self, 'answer', onSuccess, onFailure, self.rtcAnswerConstraints); } else { createLocalDescription.call(self, 'offer', onSuccess, onFailure, self.rtcOfferConstraints); } } } /** * In dialog UPDATE Reception */ function receiveUpdate(request) { debug('receiveUpdate()'); var sdp, idx, direction, m, self = this, contentType = request.getHeader('Content-Type'), rejected = false, hold = false, data = { request: request, callback: undefined, reject: reject.bind(this) }; function reject(options) { options = options || {}; rejected = true; var status_code = options.status_code || 403, reason_phrase = options.reason_phrase || '', extraHeaders = options.extraHeaders && options.extraHeaders.slice() || []; if (this.status !== C.STATUS_CONFIRMED) { return false; } if (status_code < 300 || status_code >= 700) { throw new TypeError('Invalid status_code: '+ status_code); } request.reply(status_code, reason_phrase, extraHeaders); } // Emit 'update'. this.emit('update', data); if (rejected) { return; } if (! request.body) { var extraHeaders = []; handleSessionTimersInIncomingRequest.call(this, request, extraHeaders); request.reply(200, null, extraHeaders); return; } if (contentType !== 'application/sdp') { debug('invalid Content-Type'); request.reply(415); return; } sdp = request.parseSDP(); for (idx=0; idx < sdp.media.length; idx++) { m = sdp.media[idx]; if (holdMediaTypes.indexOf(m.type) === -1) { continue; } direction = m.direction || sdp.direction || 'sendrecv'; if (direction === 'sendonly' || direction === 'inactive') { hold = true; } // If at least one of the streams is active don't emit 'hold'. else { hold = false; break; } } var e = {originator:'remote', type:'offer', sdp:request.body}; var offer = new RTCSessionDescription({type:'offer', sdp:e.sdp}); this.emit('sdp', e); this.connection.setRemoteDescription(offer) .then(function() { if (self.remoteHold === true && hold === false) { self.remoteHold = false; onunhold.call(self, 'remote'); } else if (self.remoteHold === false && hold === true) { self.remoteHold = true; onhold.call(self, 'remote'); } createLocalDescription.call(self, 'answer', // success function(sdp) { var extraHeaders = ['Contact: ' + self.contact]; handleSessionTimersInIncomingRequest.call(self, request, extraHeaders); request.reply(200, null, extraHeaders, sdp); // If callback is given execute it. if (typeof data.callback === 'function') { data.callback(); } }, // failure function() { request.reply(500); } ); }) .catch(function(error) { request.reply(488); self.emit('peerconnection:setremotedescriptionfailed', error); }); } /** * In dialog Refer Reception */ function receiveRefer(request) { debug('receiveRefer()'); var notifier, self = this; function accept(initCallback, options) { var session, replaces; options = options || {}; initCallback = (typeof initCallback === 'function')? initCallback : null; if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) { return false; } session = new RTCSession(this.ua); session.on('progress', function(e) { notifier.notify(e.response.status_code, e.response.reason_phrase); }); session.on('accepted', function(e) { notifier.notify(e.response.status_code, e.response.reason_phrase); }); session.on('failed', function(e) { if (e.message) { notifier.notify(e.message.status_code, e.message.reason_phrase); } else { notifier.notify(487, e.cause); } }); // Consider the Replaces header present in the Refer-To URI if (request.refer_to.uri.hasHeader('replaces')) { replaces = decodeURIComponent(request.refer_to.uri.getHeader('replaces')); options.extraHeaders = options.extraHeaders || []; options.extraHeaders.push('Replaces: '+ replaces); } session.connect(request.refer_to.uri.toAor(), options, initCallback); } function reject() { notifier.notify(603); } if (typeof request.refer_to === undefined) { debug('no Refer-To header field present in REFER'); request.reply(400); return; } if (request.refer_to.uri.scheme !== JsSIP_C.SIP) { debug('Refer-To header field points to a non-SIP URI scheme'); request.reply(416); return; } // reply before the transaction timer expires request.reply(202); notifier = new RTCSession_ReferNotifier(this, request.cseq); // Emit 'refer'. this.emit('refer', { request: request, accept: function(initCallback, options) { accept.call(self, initCallback, options); }, reject: function() { reject.call(self); } }); } /** * In dialog Notify Reception */ function receiveNotify(request) { debug('receiveNotify()'); if (typeof request.event === undefined) { request.reply(400); } switch (request.event.event) { case 'refer': { var id = request.event.params.id; var referSubscriber = this.referSubscribers[id]; if (!referSubscriber) { request.reply(481, 'Subscription does not exist'); return; } referSubscriber.receiveNotify(request); request.reply(200); break; } default: { request.reply(489); } } } /** * INVITE with Replaces Reception */ function receiveReplaces(request) { debug('receiveReplaces()'); var self = this; function accept(initCallback) { var session; if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) { return false; } session = new RTCSession(this.ua); // terminate the current session when the new one is confirmed session.on('confirmed', function() { self.terminate(); }); session.init_incoming(request, initCallback); } function reject() { debug('Replaced INVITE rejected by the user'); request.reply(486); } // Emit 'replace'. this.emit('replaces', { request: request, accept: function(initCallback) { accept.call(self, initCallback); }, reject: function() { reject.call(self); } }); } /** * Initial Request Sender */ function sendInitialRequest(mediaConstraints, rtcOfferConstraints, mediaStream) { var self = this; var request_sender = new RequestSender(self, this.ua); this.receiveResponse = function(response) { receiveInviteResponse.call(self, response); }; // If a local MediaStream is given use it. if (mediaStream) { // Wait a bit so the app can set events such as 'peerconnection' and 'connecting'. setTimeout(function() { userMediaSucceeded(mediaStream); }); // If at least audio or video is requested prompt getUserMedia. } else if (mediaConstraints.audio || mediaConstraints.video) { this.localMediaStreamLocallyGenerated = true; navigator.mediaDevices.getUserMedia(mediaConstraints) .then(userMediaSucceeded) .catch(function(error) { userMediaFailed(error); self.emit('getusermediafailed', error); }); // Otherwise don't prompt getUserMedia. } else { userMediaSucceeded(null); } // User media succeeded function userMediaSucceeded(stream) { if (self.status === C.STATUS_TERMINATED) { return; } self.localMediaStream = stream; if (stream) { self.connection.addStream(stream); } // Notify the app with the RTCPeerConnection so it can do stuff on it // before generating the offer. self.emit('peerconnection', { peerconnection: self.connection }); connecting.call(self, self.request); createLocalDescription.call(self, 'offer', rtcSucceeded, rtcFailed, rtcOfferConstraints); } // User media failed function userMediaFailed() { if (self.status === C.STATUS_TERMINATED) { return; } failed.call(self, 'local', null, JsSIP_C.causes.USER_DENIED_MEDIA_ACCESS); } function rtcSucceeded(desc) { if (self.isCanceled || self.status === C.STATUS_TERMINATED) { return; } self.request.body = desc; self.status = C.STATUS_INVITE_SENT; // Emit 'sending' so the app can mangle the body before the request // is sent. self.emit('sending', { request: self.request }); request_sender.send(); } function rtcFailed() { if (self.status === C.STATUS_TERMINATED) { return; } failed.call(self, 'system', null, JsSIP_C.causes.WEBRTC_ERROR); } } /** * Reception of Response for Initial INVITE */ function receiveInviteResponse(response) { debug('receiveInviteResponse()'); var cause, dialog, e, self = this; // Handle 2XX retransmissions and responses from forked requests if (this.dialog && (response.status_code >=200 && response.status_code <=299)) { /* * If it is a retransmission from the endpoint that established * the dialog, send an ACK */ if (this.dialog.id.call_id === response.call_id && this.dialog.id.local_tag === response.from_tag && this.dialog.id.remote_tag === response.to_tag) { sendRequest.call(this, JsSIP_C.ACK); return; } // If not, send an ACK and terminate else { dialog = new Dialog(this, response, 'UAC'); if (dialog.error !== undefined) { debug(dialog.error); return; } dialog.sendRequest({ owner: {status: C.STATUS_TERMINATED}, onRequestTimeout: function(){}, onTransportError: function(){}, onDialogError: function(){}, receiveResponse: function(){} }, JsSIP_C.ACK); dialog.sendRequest({ owner: {status: C.STATUS_TERMINATED}, onRequestTimeout: function(){}, onTransportError: function(){}, onDialogError: function(){}, receiveResponse: function(){} }, JsSIP_C.BYE); return; } } // Proceed to cancellation if the user requested. if(this.isCanceled) { // Remove the flag. We are done. this.isCanceled = false; if(response.status_code >= 100 && response.status_code < 200) { this.request.cancel(this.cancelReason); } else if(response.status_code >= 200 && response.status_code < 299) { acceptAndTerminate.call(this, response); } return; } if(this.status !== C.STATUS_INVITE_SENT && this.status !== C.STATUS_1XX_RECEIVED) { return; } switch(true) { case /^100$/.test(response.status_code): this.status = C.STATUS_1XX_RECEIVED; break; case /^1[0-9]{2}$/.test(response.status_code): // Do nothing with 1xx responses without To tag. if (!response.to_tag) { debug('1xx response received without to tag'); break; } // Create Early Dialog if 1XX comes with contact if (response.hasHeader('contact')) { // An error on dialog creation will fire 'failed' event if(! createDialog.call(this, response, 'UAC', true)) { break; } } this.status = C.STATUS_1XX_RECEIVED; progress.call(this, 'remote', response); if (!response.body) { break; } e = {originator:'remote', type:'pranswer', sdp:response.body}; this.emit('sdp', e); var pranswer = new RTCSessionDescription({type:'pranswer', sdp:e.sdp}); this.connection.setRemoteDescription(pranswer) .catch(function(error) { self.emit('peerconnection:setremotedescriptionfailed', error); }); break; case /^2[0-9]{2}$/.test(response.status_code): this.status = C.STATUS_CONFIRMED; if(!response.body) { acceptAndTerminate.call(this, response, 400, JsSIP_C.causes.MISSING_SDP); failed.call(this, 'remote', response, JsSIP_C.causes.BAD_MEDIA_DESCRIPTION); break; } // An error on dialog creation will fire 'failed' event if (! createDialog.call(this, response, 'UAC')) { break; } e = {originator:'remote', type:'answer', sdp:response.body}; this.emit('sdp', e); var answer = new RTCSessionDescription({type:'answer', sdp:e.sdp}); this.connection.setRemoteDescription(answer) .then(function() { // Handle Session Timers. handleSessionTimersInIncomingResponse.call(self, response); accepted.call(self, 'remote', response); sendRequest.call(self, JsSIP_C.ACK); confirmed.call(self, 'local', null); }) .catch(function(error) { acceptAndTerminate.call(self, response, 488, 'Not Acceptable Here'); failed.call(self, 'remote', response, JsSIP_C.causes.BAD_MEDIA_DESCRIPTION); self.emit('peerconnection:setremotedescriptionfailed', error); }); break; default: cause = Utils.sipErrorCause(response.status_code); failed.call(this, 'remote', response, cause); } } /** * Send Re-INVITE */ function sendReinvite(options) { debug('sendReinvite()'); options = options || {}; var self = this, extraHeaders = options.extraHeaders || [], eventHandlers = options.eventHandlers || {}, rtcOfferConstraints = options.rtcOfferConstraints || this.rtcOfferConstraints || null, succeeded = false; extraHeaders.push('Contact: ' + this.contact); extraHeaders.push('Content-Type: application/sdp'); // Session Timers. if (this.sessionTimers.running) { extraHeaders.push('Session-Expires: ' + this.sessionTimers.currentExpires + ';refresher=' + (this.sessionTimers.refresher ? 'uac' : 'uas')); } createLocalDescription.call(this, 'offer', // success function(sdp) { sdp = mangleOffer.call(self, sdp); var request = new RTCSession_Request(self, JsSIP_C.INVITE); request.send({ extraHeaders: extraHeaders, body: sdp, eventHandlers: { onSuccessResponse: function(response) { onSucceeded(response); succeeded = true; }, onErrorResponse: function(response) { onFailed(response); }, onTransportError: function() { self.onTransportError(); // Do nothing because session ends. }, onRequestTimeout: function() { self.onRequestTimeout(); // Do nothing because session ends. }, onDialogError: function() { self.onDialogError(); // Do nothing because session ends. } } }); }, // failure function() { onFailed(); }, // RTC constraints. rtcOfferConstraints ); function onSucceeded(response) { if (self.status === C.STATUS_TERMINATED) { return; } sendRequest.call(self, JsSIP_C.ACK); // If it is a 2XX retransmission exit now. if (succeeded) { return; } // Handle Session Timers. handleSessionTimersInIncomingResponse.call(self, response); // Must have SDP answer. if(! response.body) { onFailed(); return; } else if (response.getHeader('Content-Type') !== 'application/sdp') { onFailed(); return; } var e = {originator:'remote', type:'answer', sdp:response.body}; var answer = new RTCSessionDescription({type:'answer', sdp:e.sdp}); self.emit('sdp', e); self.connection.setRemoteDescription(answer) .then(function() { if (eventHandlers.succeeded) { eventHandlers.succeeded(response); } }) .catch(function(error) { onFailed(); self.emit('peerconnection:setremotedescriptionfailed', error); }); } function onFailed(response) { if (eventHandlers.failed) { eventHandlers.failed(response); } } } /** * Send UPDATE */ function sendUpdate(options) { debug('sendUpdate()'); options = options || {}; var self = this, extraHeaders = options.extraHeaders || [], eventHandlers = options.eventHandlers || {}, rtcOfferConstraints = options.rtcOfferConstraints || this.rtcOfferConstraints || null, sdpOffer = options.sdpOffer || false, succeeded = false; extraHeaders.push('Contact: ' + this.contact); // Session Timers. if (this.sessionTimers.running) { extraHeaders.push('Session-Expires: ' + this.sessionTimers.currentExpires + ';refresher=' + (this.sessionTimers.refresher ? 'uac' : 'uas')); } if (sdpOffer) { extraHeaders.push('Content-Type: application/sdp'); createLocalDescription.call(this, 'offer', // success function(sdp) { sdp = mangleOffer.call(self, sdp); var request = new RTCSession_Request(self, JsSIP_C.UPDATE); request.send({ extraHeaders: extraHeaders, body: sdp, eventHandlers: { onSuccessResponse: function(response) { onSucceeded(response); succeeded = true; }, onErrorResponse: function(response) { onFailed(response); }, onTransportError: function() { self.onTransportError(); // Do nothing because session ends. }, onRequestTimeout: function() { self.onRequestTimeout(); // Do nothing because session ends. }, onDialogError: function() { self.onDialogError(); // Do nothing because session ends. } } }); }, // failure function() { onFailed(); }, // RTC constraints. rtcOfferConstraints ); } // No SDP. else { var request = new RTCSession_Request(self, JsSIP_C.UPDATE); request.send({ extraHeaders: extraHeaders, eventHandlers: { onSuccessResponse: function(response) { onSucceeded(response); }, onErrorResponse: function(response) { onFailed(response); }, onTransportError: function() { self.onTransportError(); // Do nothing because session ends. }, onRequestTimeout: function() { self.onRequestTimeout(); // Do nothing because session ends. }, onDialogError: function() { self.onDialogError(); // Do nothing because session ends. } } }); } function onSucceeded(response) { if (self.status === C.STATUS_TERMINATED) { return; } // If it is a 2XX retransmission exit now. if (succeeded) { return; } // Handle Session Timers. handleSessionTimersInIncomingResponse.call(self, response); // Must have SDP answer. if (sdpOffer) { if(! response.body) { onFailed(); return; } else if (response.getHeader('Content-Type') !== 'application/sdp') { onFailed(); return; } var e = {originator:'remote', type:'answer', sdp:response.body}; var answer = new RTCSessionDescription({type:'answer', sdp:e.sdp}); self.emit('sdp', e); self.connection.setRemoteDescription(answer) .then(function() { if (eventHandlers.succeeded) { eventHandlers.succeeded(response); } }) .catch(function(error) { onFailed(); self.emit('peerconnection:setremotedescriptionfailed', error); }); } // No SDP answer. else { if (eventHandlers.succeeded) { eventHandlers.succeeded(response); } } } function onFailed(response) { if (eventHandlers.failed) { eventHandlers.failed(response); } } } function acceptAndTerminate(response, status_code, reason_phrase) { debug('acceptAndTerminate()'); var extraHeaders = []; if (status_code) { reason_phrase = reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || ''; extraHeaders.push('Reason: SIP ;cause=' + status_code + '; text="' + reason_phrase + '"'); } // An error on dialog creation will fire 'failed' event if (this.dialog || createDialog.call(this, response, 'UAC')) { sendRequest.call(this, JsSIP_C.ACK); sendRequest.call(this, JsSIP_C.BYE, { extraHeaders: extraHeaders }); } // Update session status. this.status = C.STATUS_TERMINATED; } /** * Send a generic in-dialog Request */ function sendRequest(method, options) { debug('sendRequest()'); var request = new RTCSession_Request(this, method); request.send(options); } /** * Correctly set the SDP direction attributes if the call is on local hold */ function mangleOffer(sdp) { var idx, length, m; if (! this.localHold && ! this.remoteHold) { return sdp; } sdp = sdp_transform.parse(sdp); // Local hold. if (this.localHold && ! this.remoteHold) { debug('mangleOffer() | me on hold, mangling offer'); length = sdp.media.length; for (idx=0; idx<length; idx++) { m = sdp.media[idx]; if (holdMediaTypes.indexOf(m.type) === -1) { continue; } if (!m.direction) { m.direction = 'sendonly'; } else if (m.direction === 'sendrecv') { m.direction = 'sendonly'; } else if (m.direction === 'recvonly') { m.direction = 'inactive'; } } } // Local and remote hold. else if (this.localHold && this.remoteHold) { debug('mangleOffer() | both on hold, mangling offer'); length = sdp.media.length; for (idx=0; idx<length; idx++) { m = sdp.media[idx]; if (holdMediaTypes.indexOf(m.type) === -1) { continue; } m.direction = 'inactive'; } } // Remote hold. else if (this.remoteHold) { debug('mangleOffer() | remote on hold, mangling offer'); length = sdp.media.length; for (idx=0; idx<length; idx++) { m = sdp.media[idx]; if (holdMediaTypes.indexOf(m.type) === -1) { continue; } if (!m.direction) { m.direction = 'recvonly'; } else if (m.direction === 'sendrecv') { m.direction = 'recvonly'; } else if (m.direction === 'recvonly') { m.direction = 'inactive'; } } } return sdp_transform.write(sdp); } function setLocalMediaStatus() { var enableAudio = true, enableVideo = true; if (this.localHold || this.remoteHold) { enableAudio = false; enableVideo = false; } if (this.audioMuted) { enableAudio = false; } if (this.videoMuted) { enableVideo = false; } toogleMuteAudio.call(this, !enableAudio); toogleMuteVideo.call(this, !enableVideo); } /** * Handle SessionTimers for an incoming INVITE or UPDATE. * @param {IncomingRequest} request * @param {Array} responseExtraHeaders Extra headers for the 200 response. */ function handleSessionTimersInIncomingRequest(request, responseExtraHeaders) { if (! this.sessionTimers.enabled) { return; } var session_expires_refresher; if (request.session_expires && request.session_expires >= JsSIP_C.MIN_SESSION_EXPIRES) { this.sessionTimers.currentExpires = request.session_expires; session_expires_refresher = request.session_expires_refresher || 'uas'; } else { this.sessionTimers.currentExpires = this.sessionTimers.defaultExpires; session_expires_refresher = 'uas'; } responseExtraHeaders.push('Session-Expires: ' + this.sessionTimers.currentExpires + ';refresher=' + session_expires_refresher); this.sessionTimers.refresher = (session_expires_refresher === 'uas'); runSessionTimer.call(this); } /** * Handle SessionTimers for an incoming response to INVITE or UPDATE. * @param {IncomingResponse} response */ function handleSessionTimersInIncomingResponse(response) { if (! this.sessionTimers.enabled) { return; } var session_expires_refresher; if (response.session_expires && response.session_expires >= JsSIP_C.MIN_SESSION_EXPIRES) { this.sessionTimers.currentExpires = response.session_expires; session_expires_refresher = response.session_expires_refresher || 'uac'; } else { this.sessionTimers.currentExpires = this.sessionTimers.defaultExpires; session_expires_refresher = 'uac'; } this.sessionTimers.refresher = (session_expires_refresher === 'uac'); runSessionTimer.call(this); } function runSessionTimer() { var self = this; var expires = this.sessionTimers.currentExpires; this.sessionTimers.running = true; clearTimeout(this.sessionTimers.timer); // I'm the refresher. if (this.sessionTimers.refresher) { this.sessionTimers.timer = setTimeout(function() { if (self.status === C.STATUS_TERMINATED) { return; } debug('runSessionTimer() | sending session refresh request'); sendUpdate.call(self, { eventHandlers: { succeeded: function(response) { handleSessionTimersInIncomingResponse.call(self, response); } } }); }, expires * 500); // Half the given interval (as the RFC states). } // I'm not the refresher. else { this.sessionTimers.timer = setTimeout(function() { if (self.status === C.STATUS_TERMINATED) { return; } debugerror('runSessionTimer() | timer expired, terminating the session'); self.terminate({ cause: JsSIP_C.causes.REQUEST_TIMEOUT, status_code: 408, reason_phrase: 'Session Timer Expired' }); }, expires * 1100); } } function toogleMuteAudio(mute) { var streamIdx, trackIdx, streamsLength, tracksLength, tracks, localStreams = this.connection.getLocalStreams(); streamsLength = localStreams.length; for (streamIdx = 0; streamIdx < streamsLength; streamIdx++) { tracks = localStreams[streamIdx].getAudioTracks(); tracksLength = tracks.length; for (trackIdx = 0; trackIdx < tracksLength; trackIdx++) { tracks[trackIdx].enabled = !mute; } } } function toogleMuteVideo(mute) { var streamIdx, trackIdx, streamsLength, tracksLength, tracks, localStreams = this.connection.getLocalStreams(); streamsLength = localStreams.length; for (streamIdx = 0; streamIdx < streamsLength; streamIdx++) { tracks = localStreams[streamIdx].getVideoTracks(); tracksLength = tracks.length; for (trackIdx = 0; trackIdx < tracksLength; trackIdx++) { tracks[trackIdx].enabled = !mute; } } } function newRTCSession(originator, request) { debug('newRTCSession'); this.ua.newRTCSession({ originator: originator, session: this, request: request }); } function connecting(request) { debug('session connecting'); this.emit('connecting', { request: request }); } function progress(originator, response) { debug('session progress'); this.emit('progress', { originator: originator, response: response || null }); } function accepted(originator, message) { debug('session accepted'); this.start_time = new Date(); this.emit('accepted', { originator: originator, response: message || null }); } function confirmed(originator, ack) { debug('session confirmed'); this.is_confirmed = true; this.emit('confirmed', { originator: originator, ack: ack || null }); } function ended(originator, message, cause) { debug('session ended'); this.end_time = new Date(); this.close(); this.emit('ended', { originator: originator, message: message || null, cause: cause }); } function failed(originator, message, cause) { debug('session failed'); this.close(); this.emit('failed', { originator: originator, message: message || null, cause: cause }); } function onhold(originator) { debug('session onhold'); setLocalMediaStatus.call(this); this.emit('hold', { originator: originator }); } function onunhold(originator) { debug('session onunhold'); setLocalMediaStatus.call(this); this.emit('unhold', { originator: originator }); } function onmute(options) { debug('session onmute'); setLocalMediaStatus.call(this); this.emit('muted', { audio: options.audio, video: options.video }); } function onunmute(options) { debug('session onunmute'); setLocalMediaStatus.call(this); this.emit('unmuted', { audio: options.audio, video: options.video }); } },{"./Constants":1,"./Dialog":2,"./Exceptions":5,"./RTCSession/DTMF":12,"./RTCSession/ReferNotifier":13,"./RTCSession/ReferSubscriber":14,"./RTCSession/Request":15,"./RequestSender":17,"./SIPMessage":18,"./Timers":20,"./Transactions":21,"./Utils":25,"debug":34,"events":28,"sdp-transform":37,"util":32}],12:[function(require,module,exports){ module.exports = DTMF; var C = { MIN_DURATION: 70, MAX_DURATION: 6000, DEFAULT_DURATION: 100, MIN_INTER_TONE_GAP: 50, DEFAULT_INTER_TONE_GAP: 500 }; /** * Expose C object. */ DTMF.C = C; /** * Dependencies. */ var util = require('util'); var events = require('events'); var debug = require('debug')('JsSIP:RTCSession:DTMF'); var debugerror = require('debug')('JsSIP:ERROR:RTCSession:DTMF'); debugerror.log = console.warn.bind(console); var JsSIP_C = require('../Constants'); var Exceptions = require('../Exceptions'); var RTCSession = require('../RTCSession'); function DTMF(session) { this.owner = session; this.direction = null; this.tone = null; this.duration = null; events.EventEmitter.call(this); } util.inherits(DTMF, events.EventEmitter); DTMF.prototype.send = function(tone, options) { var extraHeaders, body; if (tone === undefined) { throw new TypeError('Not enough arguments'); } this.direction = 'outgoing'; // Check RTCSession Status if (this.owner.status !== RTCSession.C.STATUS_CONFIRMED && this.owner.status !== RTCSession.C.STATUS_WAITING_FOR_ACK) { throw new Exceptions.InvalidStateError(this.owner.status); } // Get DTMF options options = options || {}; extraHeaders = options.extraHeaders ? options.extraHeaders.slice() : []; this.eventHandlers = options.eventHandlers || {}; // Check tone type if (typeof tone === 'string' ) { tone = tone.toUpperCase(); } else if (typeof tone === 'number') { tone = tone.toString(); } else { throw new TypeError('Invalid tone: '+ tone); } // Check tone value if (!tone.match(/^[0-9A-DR#*]$/)) { throw new TypeError('Invalid tone: '+ tone); } else { this.tone = tone; } // Duration is checked/corrected in RTCSession this.duration = options.duration; extraHeaders.push('Content-Type: application/dtmf-relay'); body = 'Signal=' + this.tone + '\r\n'; body += 'Duration=' + this.duration; this.owner.newDTMF({ originator: 'local', dtmf: this, request: this.request }); this.owner.dialog.sendRequest(this, JsSIP_C.INFO, { extraHeaders: extraHeaders, body: body }); }; DTMF.prototype.receiveResponse = function(response) { switch(true) { case /^1[0-9]{2}$/.test(response.status_code): // Ignore provisional responses. break; case /^2[0-9]{2}$/.test(response.status_code): this.emit('succeeded', { originator: 'remote', response: response }); break; default: if (this.eventHandlers.onFailed) { this.eventHandlers.onFailed(); } this.emit('failed', { originator: 'remote', response: response }); break; } }; DTMF.prototype.onRequestTimeout = function() { debugerror('onRequestTimeout'); this.owner.onRequestTimeout(); }; DTMF.prototype.onTransportError = function() { debugerror('onTransportError'); this.owner.onTransportError(); }; DTMF.prototype.onDialogError = function() { debugerror('onDialogError'); this.owner.onDialogError(); }; DTMF.prototype.init_incoming = function(request) { var body, reg_tone = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/, reg_duration = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/; this.direction = 'incoming'; this.request = request; request.reply(200); if (request.body) { body = request.body.split('\n'); if (body.length >= 1) { if (reg_tone.test(body[0])) { this.tone = body[0].replace(reg_tone,'$2'); } } if (body.length >=2) { if (reg_duration.test(body[1])) { this.duration = parseInt(body[1].replace(reg_duration,'$2'), 10); } } } if (!this.duration) { this.duration = C.DEFAULT_DURATION; } if (!this.tone) { debug('invalid INFO DTMF received, discarded'); } else { this.owner.newDTMF({ originator: 'remote', dtmf: this, request: request }); } }; },{"../Constants":1,"../Exceptions":5,"../RTCSession":11,"debug":34,"events":28,"util":32}],13:[function(require,module,exports){ module.exports = ReferNotifier; var C = { event_type: 'refer', body_type: 'message/sipfrag;version=2.0', expires: 300 }; /** * Dependencies. */ var debug = require('debug')('JsSIP:RTCSession:ReferNotifier'); var JsSIP_C = require('../Constants'); var RTCSession_Request = require('./Request'); function ReferNotifier(session, id, expires) { this.session = session; this.id = id; this.expires = expires || C.expires; this.active = true; // The creation of a Notifier results in an immediate NOTIFY this.notify(100); } ReferNotifier.prototype.notify = function(code, reason) { debug('notify()'); var state, self = this; if (this.active === false) { return; } reason = reason || JsSIP_C.REASON_PHRASE[code] || ''; if (code >= 200) { state = 'terminated;reason=noresource'; } else { state = 'active;expires='+ this.expires; } // put this in a try/catch block var request = new RTCSession_Request(this.session, JsSIP_C.NOTIFY); request.send({ extraHeaders: [ 'Event: '+ C.event_type +';id='+ self.id, 'Subscription-State: '+ state, 'Content-Type: '+ C.body_type ], body: 'SIP/2.0 ' + code + ' ' + reason, eventHandlers: { // if a negative response is received, subscription is canceled onErrorResponse: function() { self.active = false; } } }); }; },{"../Constants":1,"./Request":15,"debug":34}],14:[function(require,module,exports){ module.exports = ReferSubscriber; var C = { expires: 120 }; /** * Dependencies. */ var util = require('util'); var events = require('events'); var debug = require('debug')('JsSIP:RTCSession:ReferSubscriber'); var JsSIP_C = require('../Constants'); var Grammar = require('../Grammar'); var RTCSession_Request = require('./Request'); function ReferSubscriber(session) { this.session = session; this.timer = null; // Instance of REFER OutgoingRequest this.outgoingRequest = null; events.EventEmitter.call(this); } util.inherits(ReferSubscriber, events.EventEmitter); ReferSubscriber.prototype.sendRefer = function(target, options) { debug('sendRefer()'); var extraHeaders, eventHandlers, referTo, replaces = null, self = this; // Get REFER options options = options || {}; extraHeaders = options.extraHeaders ? options.extraHeaders.slice() : []; eventHandlers = options.eventHandlers || {}; // Set event handlers for (var event in eventHandlers) { this.on(event, eventHandlers[event]); } // Replaces URI header field if (options.replaces) { replaces = options.replaces.request.call_id; replaces += ';to-tag='+ options.replaces.to_tag; replaces += ';from-tag='+ options.replaces.from_tag; replaces = encodeURIComponent(replaces); } // Refer-To header field referTo = 'Refer-To: <'+ target + (replaces?'?Replaces='+ replaces:'') +'>'; extraHeaders.push(referTo); var request = new RTCSession_Request(this.session, JsSIP_C.REFER); this.timer = setTimeout(function() { removeSubscriber.call(self); }, C.expires * 1000); request.send({ extraHeaders: extraHeaders, eventHandlers: { onSuccessResponse: function(response) { self.emit('requestSucceeded', { response: response }); }, onErrorResponse: function(response) { self.emit('requestFailed', { response: response, cause: JsSIP_C.causes.REJECTED }); }, onTransportError: function() { removeSubscriber.call(self); self.emit('requestFailed', { response: null, cause: JsSIP_C.causes.CONNECTION_ERROR }); }, onRequestTimeout: function() { removeSubscriber.call(self); self.emit('requestFailed', { response: null, cause: JsSIP_C.causes.REQUEST_TIMEOUT }); }, onDialogError: function() { removeSubscriber.call(self); self.emit('requestFailed', { response: null, cause: JsSIP_C.causes.DIALOG_ERROR }); } } }); this.outgoingRequest = request.outgoingRequest; }; ReferSubscriber.prototype.receiveNotify = function(request) { debug('receiveNotify()'); var status_line; if (!request.body) { return; } status_line = Grammar.parse(request.body, 'Status_Line'); if(status_line === -1) { debug('receiveNotify() | error parsing NOTIFY body: "' + request.body + '"'); return; } switch(true) { case /^100$/.test(status_line.status_code): this.emit('trying', { request: request, status_line: status_line }); break; case /^1[0-9]{2}$/.test(status_line.status_code): this.emit('progress', { request: request, status_line: status_line }); break; case /^2[0-9]{2}$/.test(status_line.status_code): removeSubscriber.call(this); this.emit('accepted', { request: request, status_line: status_line }); break; default: removeSubscriber.call(this); this.emit('failed', { request: request, status_line: status_line }); break; } }; // remove refer subscriber from the session function removeSubscriber() { console.log('removeSubscriber()'); clearTimeout(this.timer); this.session.referSubscriber = null; } },{"../Constants":1,"../Grammar":6,"./Request":15,"debug":34,"events":28,"util":32}],15:[function(require,module,exports){ module.exports = Request; /** * Dependencies. */ var debug = require('debug')('JsSIP:RTCSession:Request'); var debugerror = require('debug')('JsSIP:ERROR:RTCSession:Request'); debugerror.log = console.warn.bind(console); var JsSIP_C = require('../Constants'); var Exceptions = require('../Exceptions'); var RTCSession = require('../RTCSession'); function Request(session, method) { debug('new | %s', method); this.session = session; this.method = method; // Instance of OutgoingRequest this.outgoingRequest = null; // Check RTCSession Status if (this.session.status !== RTCSession.C.STATUS_1XX_RECEIVED && this.session.status !== RTCSession.C.STATUS_WAITING_FOR_ANSWER && this.session.status !== RTCSession.C.STATUS_WAITING_FOR_ACK && this.session.status !== RTCSession.C.STATUS_CONFIRMED && this.session.status !== RTCSession.C.STATUS_TERMINATED) { throw new Exceptions.InvalidStateError(this.session.status); } /* * Allow sending BYE in TERMINATED status since the RTCSession * could had been terminated before the ACK had arrived. * RFC3261 Section 15, Paragraph 2 */ else if (this.session.status === RTCSession.C.STATUS_TERMINATED && method !== JsSIP_C.BYE) { throw new Exceptions.InvalidStateError(this.session.status); } } Request.prototype.send = function(options) { options = options || {}; var extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], body = options.body || null; this.eventHandlers = options.eventHandlers || {}; this.outgoingRequest = this.session.dialog.sendRequest(this, this.method, { extraHeaders: extraHeaders, body: body }); }; Request.prototype.receiveResponse = function(response) { switch(true) { case /^1[0-9]{2}$/.test(response.status_code): debug('onProgressResponse'); if (this.eventHandlers.onProgressResponse) { this.eventHandlers.onProgressResponse(response); } break; case /^2[0-9]{2}$/.test(response.status_code): debug('onSuccessResponse'); if (this.eventHandlers.onSuccessResponse) { this.eventHandlers.onSuccessResponse(response); } break; default: debug('onErrorResponse'); if (this.eventHandlers.onErrorResponse) { this.eventHandlers.onErrorResponse(response); } break; } }; Request.prototype.onRequestTimeout = function() { debugerror('onRequestTimeout'); if (this.eventHandlers.onRequestTimeout) { this.eventHandlers.onRequestTimeout(); } }; Request.prototype.onTransportError = function() { debugerror('onTransportError'); if (this.eventHandlers.onTransportError) { this.eventHandlers.onTransportError(); } }; Request.prototype.onDialogError = function() { debugerror('onDialogError'); if (this.eventHandlers.onDialogError) { this.eventHandlers.onDialogError(); } }; },{"../Constants":1,"../Exceptions":5,"../RTCSession":11,"debug":34}],16:[function(require,module,exports){ module.exports = Registrator; /** * Dependecies */ var debug = require('debug')('JsSIP:Registrator'); var Utils = require('./Utils'); var JsSIP_C = require('./Constants'); var SIPMessage = require('./SIPMessage'); var RequestSender = require('./RequestSender'); function Registrator(ua, transport) { var reg_id=1; //Force reg_id to 1. this.ua = ua; this.transport = transport; this.registrar = ua.configuration.registrar_server; this.expires = ua.configuration.register_expires; // Call-ID and CSeq values RFC3261 10.2 this.call_id = Utils.createRandomToken(22); this.cseq = 0; // this.to_uri this.to_uri = ua.configuration.uri; this.registrationTimer = null; // Set status this.registered = false; // Contact header this.contact = this.ua.contact.toString(); // sip.ice media feature tag (RFC 5768) this.contact += ';+sip.ice'; // Custom headers for REGISTER and un-REGISTER. this.extraHeaders = []; // Custom Contact header params for REGISTER and un-REGISTER. this.extraContactParams = ''; if(reg_id) { this.contact += ';reg-id='+ reg_id; this.contact += ';+sip.instance="<urn:uuid:'+ this.ua.configuration.instance_id+'>"'; } } Registrator.prototype = { setExtraHeaders: function(extraHeaders) { if (! Array.isArray(extraHeaders)) { extraHeaders = []; } this.extraHeaders = extraHeaders.slice(); }, setExtraContactParams: function(extraContactParams) { if (! (extraContactParams instanceof Object)) { extraContactParams = {}; } // Reset it. this.extraContactParams = ''; for(var param_key in extraContactParams) { var param_value = extraContactParams[param_key]; this.extraContactParams += (';' + param_key); if (param_value) { this.extraContactParams += ('=' + param_value); } } }, register: function() { var request_sender, cause, extraHeaders, self = this; extraHeaders = this.extraHeaders.slice(); extraHeaders.push('Contact: ' + this.contact + ';expires=' + this.expires + this.extraContactParams); extraHeaders.push('Expires: '+ this.expires); this.request = new SIPMessage.OutgoingRequest(JsSIP_C.REGISTER, this.registrar, this.ua, { 'to_uri': this.to_uri, 'call_id': this.call_id, 'cseq': (this.cseq += 1) }, extraHeaders); request_sender = new RequestSender(this, this.ua); this.receiveResponse = function(response) { var contact, expires, contacts = response.getHeaders('contact').length; // Discard responses to older REGISTER/un-REGISTER requests. if(response.cseq !== this.cseq) { return; } // Clear registration timer if (this.registrationTimer !== null) { clearTimeout(this.registrationTimer); this.registrationTimer = null; } switch(true) { case /^1[0-9]{2}$/.test(response.status_code): // Ignore provisional responses. break; case /^2[0-9]{2}$/.test(response.status_code): if(response.hasHeader('expires')) { expires = response.getHeader('expires'); } // Search the Contact pointing to us and update the expires value accordingly. if (!contacts) { debug('no Contact header in response to REGISTER, response ignored'); break; } while(contacts--) { contact = response.parseHeader('contact', contacts); if(contact.uri.user === this.ua.contact.uri.user) { expires = contact.getParam('expires'); break; } else { contact = null; } } if (!contact) { debug('no Contact header pointing to us, response ignored'); break; } if(!expires) { expires = this.expires; } // Re-Register before the expiration interval has elapsed. // For that, decrease the expires value. ie: 3 seconds this.registrationTimer = setTimeout(function() { self.registrationTimer = null; self.register(); }, (expires * 1000) - 3000); //Save gruu values if (contact.hasParam('temp-gruu')) { this.ua.contact.temp_gruu = contact.getParam('temp-gruu').replace(/"/g,''); } if (contact.hasParam('pub-gruu')) { this.ua.contact.pub_gruu = contact.getParam('pub-gruu').replace(/"/g,''); } if (! this.registered) { this.registered = true; this.ua.registered({ response: response }); } break; // Interval too brief RFC3261 10.2.8 case /^423$/.test(response.status_code): if(response.hasHeader('min-expires')) { // Increase our registration interval to the suggested minimum this.expires = response.getHeader('min-expires'); // Attempt the registration again immediately this.register(); } else { //This response MUST contain a Min-Expires header field debug('423 response received for REGISTER without Min-Expires'); this.registrationFailure(response, JsSIP_C.causes.SIP_FAILURE_CODE); } break; default: cause = Utils.sipErrorCause(response.status_code); this.registrationFailure(response, cause); } }; this.onRequestTimeout = function() { this.registrationFailure(null, JsSIP_C.causes.REQUEST_TIMEOUT); }; this.onTransportError = function() { this.registrationFailure(null, JsSIP_C.causes.CONNECTION_ERROR); }; request_sender.send(); }, unregister: function(options) { var extraHeaders; if(!this.registered) { debug('already unregistered'); return; } options = options || {}; this.registered = false; // Clear the registration timer. if (this.registrationTimer !== null) { clearTimeout(this.registrationTimer); this.registrationTimer = null; } extraHeaders = this.extraHeaders.slice(); if(options.all) { extraHeaders.push('Contact: *' + this.extraContactParams); extraHeaders.push('Expires: 0'); this.request = new SIPMessage.OutgoingRequest(JsSIP_C.REGISTER, this.registrar, this.ua, { 'to_uri': this.to_uri, 'call_id': this.call_id, 'cseq': (this.cseq += 1) }, extraHeaders); } else { extraHeaders.push('Contact: '+ this.contact + ';expires=0' + this.extraContactParams); extraHeaders.push('Expires: 0'); this.request = new SIPMessage.OutgoingRequest(JsSIP_C.REGISTER, this.registrar, this.ua, { 'to_uri': this.to_uri, 'call_id': this.call_id, 'cseq': (this.cseq += 1) }, extraHeaders); } var request_sender = new RequestSender(this, this.ua); this.receiveResponse = function(response) { var cause; switch(true) { case /^1[0-9]{2}$/.test(response.status_code): // Ignore provisional responses. break; case /^2[0-9]{2}$/.test(response.status_code): this.unregistered(response); break; default: cause = Utils.sipErrorCause(response.status_code); this.unregistered(response, cause); } }; this.onRequestTimeout = function() { this.unregistered(null, JsSIP_C.causes.REQUEST_TIMEOUT); }; this.onTransportError = function() { this.unregistered(null, JsSIP_C.causes.CONNECTION_ERROR); }; request_sender.send(); }, registrationFailure: function(response, cause) { this.ua.registrationFailed({ response: response || null, cause: cause }); if (this.registered) { this.registered = false; this.ua.unregistered({ response: response || null, cause: cause }); } }, unregistered: function(response, cause) { this.registered = false; this.ua.unregistered({ response: response || null, cause: cause || null }); }, onTransportClosed: function() { if (this.registrationTimer !== null) { clearTimeout(this.registrationTimer); this.registrationTimer = null; } if(this.registered) { this.registered = false; this.ua.unregistered({}); } }, close: function() { if (this.registered) { this.unregister(); } } }; },{"./Constants":1,"./RequestSender":17,"./SIPMessage":18,"./Utils":25,"debug":34}],17:[function(require,module,exports){ module.exports = RequestSender; /** * Dependencies. */ var debug = require('debug')('JsSIP:RequestSender'); var JsSIP_C = require('./Constants'); var UA = require('./UA'); var DigestAuthentication = require('./DigestAuthentication'); var Transactions = require('./Transactions'); function RequestSender(applicant, ua) { this.ua = ua; this.applicant = applicant; this.method = applicant.request.method; this.request = applicant.request; this.auth = null; this.challenged = false; this.staled = false; // If ua is in closing process or even closed just allow sending Bye and ACK if (ua.status === UA.C.STATUS_USER_CLOSED && (this.method !== JsSIP_C.BYE || this.method !== JsSIP_C.ACK)) { this.onTransportError(); } } /** * Create the client transaction and send the message. */ RequestSender.prototype = { send: function() { switch(this.method) { case 'INVITE': this.clientTransaction = new Transactions.InviteClientTransaction(this, this.request, this.ua.transport); break; case 'ACK': this.clientTransaction = new Transactions.AckClientTransaction(this, this.request, this.ua.transport); break; default: this.clientTransaction = new Transactions.NonInviteClientTransaction(this, this.request, this.ua.transport); } this.clientTransaction.send(); }, /** * Callback fired when receiving a request timeout error from the client transaction. * To be re-defined by the applicant. */ onRequestTimeout: function() { this.applicant.onRequestTimeout(); }, /** * Callback fired when receiving a transport error from the client transaction. * To be re-defined by the applicant. */ onTransportError: function() { this.applicant.onTransportError(); }, /** * Called from client transaction when receiving a correct response to the request. * Authenticate request if needed or pass the response back to the applicant. */ receiveResponse: function(response) { var cseq, challenge, authorization_header_name, status_code = response.status_code; /* * Authentication * Authenticate once. _challenged_ flag used to avoid infinite authentications. */ if ((status_code === 401 || status_code === 407) && (this.ua.configuration.password !== null || this.ua.configuration.ha1 !== null)) { // Get and parse the appropriate WWW-Authenticate or Proxy-Authenticate header. if (response.status_code === 401) { challenge = response.parseHeader('www-authenticate'); authorization_header_name = 'authorization'; } else { challenge = response.parseHeader('proxy-authenticate'); authorization_header_name = 'proxy-authorization'; } // Verify it seems a valid challenge. if (!challenge) { debug(response.status_code + ' with wrong or missing challenge, cannot authenticate'); this.applicant.receiveResponse(response); return; } if (!this.challenged || (!this.staled && challenge.stale === true)) { if (!this.auth) { this.auth = new DigestAuthentication({ username : this.ua.configuration.authorization_user, password : this.ua.configuration.password, realm : this.ua.configuration.realm, ha1 : this.ua.configuration.ha1 }); } // Verify that the challenge is really valid. if (!this.auth.authenticate(this.request, challenge)) { this.applicant.receiveResponse(response); return; } this.challenged = true; // Update ha1 and realm in the UA. this.ua.set('realm', this.auth.get('realm')); this.ua.set('ha1', this.auth.get('ha1')); if (challenge.stale) { this.staled = true; } if (response.method === JsSIP_C.REGISTER) { cseq = this.applicant.cseq += 1; } else if (this.request.dialog) { cseq = this.request.dialog.local_seqnum += 1; } else { cseq = this.request.cseq + 1; } this.request = this.applicant.request = this.request.clone(); this.request.cseq = cseq; this.request.setHeader('cseq', cseq +' '+ this.method); this.request.setHeader(authorization_header_name, this.auth.toString()); this.send(); } else { this.applicant.receiveResponse(response); } } else { this.applicant.receiveResponse(response); } } }; },{"./Constants":1,"./DigestAuthentication":4,"./Transactions":21,"./UA":23,"debug":34}],18:[function(require,module,exports){ module.exports = { OutgoingRequest: OutgoingRequest, IncomingRequest: IncomingRequest, IncomingResponse: IncomingResponse }; /** * Dependencies. */ var debug = require('debug')('JsSIP:SIPMessage'); var sdp_transform = require('sdp-transform'); var JsSIP_C = require('./Constants'); var Utils = require('./Utils'); var NameAddrHeader = require('./NameAddrHeader'); var Grammar = require('./Grammar'); /** * -param {String} method request method * -param {String} ruri request uri * -param {UA} ua * -param {Object} params parameters that will have priority over ua.configuration parameters: * <br> * - cseq, call_id, from_tag, from_uri, from_display_name, to_uri, to_tag, route_set * -param {Object} [headers] extra headers * -param {String} [body] */ function OutgoingRequest(method, ruri, ua, params, extraHeaders, body) { var to, from, call_id, cseq; params = params || {}; // Mandatory parameters check if(!method || !ruri || !ua) { return null; } this.ua = ua; this.headers = {}; this.method = method; this.ruri = ruri; this.body = body; this.extraHeaders = extraHeaders && extraHeaders.slice() || []; // Fill the Common SIP Request Headers // Route if (params.route_set) { this.setHeader('route', params.route_set); } else if (ua.configuration.use_preloaded_route) { this.setHeader('route', '<' + ua.transport.sip_uri + ';lr>'); } // Via // Empty Via header. Will be filled by the client transaction. this.setHeader('via', ''); // Max-Forwards this.setHeader('max-forwards', JsSIP_C.MAX_FORWARDS); // To to = (params.to_display_name || params.to_display_name === 0) ? '"' + params.to_display_name + '" ' : ''; to += '<' + (params.to_uri || ruri) + '>'; to += params.to_tag ? ';tag=' + params.to_tag : ''; this.to = new NameAddrHeader.parse(to); this.setHeader('to', to); // From if (params.from_display_name || params.from_display_name === 0) { from = '"' + params.from_display_name + '" '; } else if (ua.configuration.display_name) { from = '"' + ua.configuration.display_name + '" '; } else { from = ''; } from += '<' + (params.from_uri || ua.configuration.uri) + '>;tag='; from += params.from_tag || Utils.newTag(); this.from = new NameAddrHeader.parse(from); this.setHeader('from', from); // Call-ID call_id = params.call_id || (ua.configuration.jssip_id + Utils.createRandomToken(15)); this.call_id = call_id; this.setHeader('call-id', call_id); // CSeq cseq = params.cseq || Math.floor(Math.random() * 10000); this.cseq = cseq; this.setHeader('cseq', cseq + ' ' + method); } OutgoingRequest.prototype = { /** * Replace the the given header by the given value. * -param {String} name header name * -param {String | Array} value header value */ setHeader: function(name, value) { var regexp, idx; // Remove the header from extraHeaders if present. regexp = new RegExp('^\\s*'+ name +'\\s*:','i'); for (idx=0; idx<this.extraHeaders.length; idx++) { if (regexp.test(this.extraHeaders[idx])) { this.extraHeaders.splice(idx, 1); } } this.headers[Utils.headerize(name)] = (Array.isArray(value)) ? value : [value]; }, /** * Get the value of the given header name at the given position. * -param {String} name header name * -returns {String|undefined} Returns the specified header, null if header doesn't exist. */ getHeader: function(name) { var regexp, idx, length = this.extraHeaders.length, header = this.headers[Utils.headerize(name)]; if(header) { if(header[0]) { return header[0]; } } else { regexp = new RegExp('^\\s*'+ name +'\\s*:','i'); for (idx=0; idx<length; idx++) { header = this.extraHeaders[idx]; if (regexp.test(header)) { return header.substring(header.indexOf(':')+1).trim(); } } } return; }, /** * Get the header/s of the given name. * -param {String} name header name * -returns {Array} Array with all the headers of the specified name. */ getHeaders: function(name) { var idx, length, regexp, header = this.headers[Utils.headerize(name)], result = []; if (header) { length = header.length; for (idx = 0; idx < length; idx++) { result.push(header[idx]); } return result; } else { length = this.extraHeaders.length; regexp = new RegExp('^\\s*'+ name +'\\s*:','i'); for (idx=0; idx<length; idx++) { header = this.extraHeaders[idx]; if (regexp.test(header)) { result.push(header.substring(header.indexOf(':')+1).trim()); } } return result; } }, /** * Verify the existence of the given header. * -param {String} name header name * -returns {boolean} true if header with given name exists, false otherwise */ hasHeader: function(name) { var regexp, idx, length = this.extraHeaders.length; if (this.headers[Utils.headerize(name)]) { return true; } else { regexp = new RegExp('^\\s*'+ name +'\\s*:','i'); for (idx=0; idx<length; idx++) { if (regexp.test(this.extraHeaders[idx])) { return true; } } } return false; }, /** * Parse the current body as a SDP and store the resulting object * into this.sdp. * -param {Boolean} force: Parse even if this.sdp already exists. * * Returns this.sdp. */ parseSDP: function(force) { if (!force && this.sdp) { return this.sdp; } else { this.sdp = sdp_transform.parse(this.body || ''); return this.sdp; } }, toString: function() { var msg = '', header, length, idx, supported = []; msg += this.method + ' ' + this.ruri + ' SIP/2.0\r\n'; for (header in this.headers) { length = this.headers[header].length; for (idx = 0; idx < length; idx++) { msg += header + ': ' + this.headers[header][idx] + '\r\n'; } } length = this.extraHeaders.length; for (idx = 0; idx < length; idx++) { msg += this.extraHeaders[idx].trim() +'\r\n'; } // Supported switch (this.method) { case JsSIP_C.REGISTER: supported.push('path', 'gruu'); break; case JsSIP_C.INVITE: if (this.ua.configuration.session_timers) { supported.push('timer'); } if (this.ua.contact.pub_gruu || this.ua.contact.temp_gruu) { supported.push('gruu'); } supported.push('ice','replaces'); break; case JsSIP_C.UPDATE: if (this.ua.configuration.session_timers) { supported.push('timer'); } supported.push('ice'); break; } supported.push('outbound'); // Allow msg += 'Allow: '+ JsSIP_C.ALLOWED_METHODS +'\r\n'; msg += 'Supported: ' + supported +'\r\n'; msg += 'User-Agent: ' + JsSIP_C.USER_AGENT +'\r\n'; if (this.body) { length = Utils.str_utf8_length(this.body); msg += 'Content-Length: ' + length + '\r\n\r\n'; msg += this.body; } else { msg += 'Content-Length: 0\r\n\r\n'; } return msg; }, clone: function() { var request = new OutgoingRequest(this.method, this.ruri, this.ua); Object.keys(this.headers).forEach(function(name) { request.headers[name] = this.headers[name].slice(); }, this); request.body = this.body; request.extraHeaders = this.extraHeaders && this.extraHeaders.slice() || []; request.to = this.to; request.from = this.from; request.call_id = this.call_id; request.cseq = this.cseq; return request; } }; function IncomingMessage(){ this.data = null; this.headers = null; this.method = null; this.via = null; this.via_branch = null; this.call_id = null; this.cseq = null; this.from = null; this.from_tag = null; this.to = null; this.to_tag = null; this.body = null; this.sdp = null; } IncomingMessage.prototype = { /** * Insert a header of the given name and value into the last position of the * header array. */ addHeader: function(name, value) { var header = { raw: value }; name = Utils.headerize(name); if(this.headers[name]) { this.headers[name].push(header); } else { this.headers[name] = [header]; } }, /** * Get the value of the given header name at the given position. */ getHeader: function(name) { var header = this.headers[Utils.headerize(name)]; if(header) { if(header[0]) { return header[0].raw; } } else { return; } }, /** * Get the header/s of the given name. */ getHeaders: function(name) { var idx, length, header = this.headers[Utils.headerize(name)], result = []; if(!header) { return []; } length = header.length; for (idx = 0; idx < length; idx++) { result.push(header[idx].raw); } return result; }, /** * Verify the existence of the given header. */ hasHeader: function(name) { return(this.headers[Utils.headerize(name)]) ? true : false; }, /** * Parse the given header on the given index. * -param {String} name header name * -param {Number} [idx=0] header index * -returns {Object|undefined} Parsed header object, undefined if the header is not present or in case of a parsing error. */ parseHeader: function(name, idx) { var header, value, parsed; name = Utils.headerize(name); idx = idx || 0; if(!this.headers[name]) { debug('header "' + name + '" not present'); return; } else if(idx >= this.headers[name].length) { debug('not so many "' + name + '" headers present'); return; } header = this.headers[name][idx]; value = header.raw; if(header.parsed) { return header.parsed; } //substitute '-' by '_' for grammar rule matching. parsed = Grammar.parse(value, name.replace(/-/g, '_')); if(parsed === -1) { this.headers[name].splice(idx, 1); //delete from headers debug('error parsing "' + name + '" header field with value "' + value + '"'); return; } else { header.parsed = parsed; return parsed; } }, /** * Message Header attribute selector. Alias of parseHeader. * -param {String} name header name * -param {Number} [idx=0] header index * -returns {Object|undefined} Parsed header object, undefined if the header is not present or in case of a parsing error. * * -example * message.s('via',3).port */ s: function(name, idx) { return this.parseHeader(name, idx); }, /** * Replace the value of the given header by the value. * -param {String} name header name * -param {String} value header value */ setHeader: function(name, value) { var header = { raw: value }; this.headers[Utils.headerize(name)] = [header]; }, /** * Parse the current body as a SDP and store the resulting object * into this.sdp. * -param {Boolean} force: Parse even if this.sdp already exists. * * Returns this.sdp. */ parseSDP: function(force) { if (!force && this.sdp) { return this.sdp; } else { this.sdp = sdp_transform.parse(this.body || ''); return this.sdp; } }, toString: function() { return this.data; } }; function IncomingRequest(ua) { this.ua = ua; this.headers = {}; this.ruri = null; this.transport = null; this.server_transaction = null; } IncomingRequest.prototype = new IncomingMessage(); /** * Stateful reply. * -param {Number} code status code * -param {String} reason reason phrase * -param {Object} headers extra headers * -param {String} body body * -param {Function} [onSuccess] onSuccess callback * -param {Function} [onFailure] onFailure callback */ IncomingRequest.prototype.reply = function(code, reason, extraHeaders, body, onSuccess, onFailure) { var rr, vias, length, idx, response, supported = [], to = this.getHeader('To'), r = 0, v = 0; code = code || null; reason = reason || null; // Validate code and reason values if (!code || (code < 100 || code > 699)) { throw new TypeError('Invalid status_code: '+ code); } else if (reason && typeof reason !== 'string' && !(reason instanceof String)) { throw new TypeError('Invalid reason_phrase: '+ reason); } reason = reason || JsSIP_C.REASON_PHRASE[code] || ''; extraHeaders = extraHeaders && extraHeaders.slice() || []; response = 'SIP/2.0 ' + code + ' ' + reason + '\r\n'; if(this.method === JsSIP_C.INVITE && code > 100 && code <= 200) { rr = this.getHeaders('record-route'); length = rr.length; for(r; r < length; r++) { response += 'Record-Route: ' + rr[r] + '\r\n'; } } vias = this.getHeaders('via'); length = vias.length; for(v; v < length; v++) { response += 'Via: ' + vias[v] + '\r\n'; } if(!this.to_tag && code > 100) { to += ';tag=' + Utils.newTag(); } else if(this.to_tag && !this.s('to').hasParam('tag')) { to += ';tag=' + this.to_tag; } response += 'To: ' + to + '\r\n'; response += 'From: ' + this.getHeader('From') + '\r\n'; response += 'Call-ID: ' + this.call_id + '\r\n'; response += 'CSeq: ' + this.cseq + ' ' + this.method + '\r\n'; length = extraHeaders.length; for (idx = 0; idx < length; idx++) { response += extraHeaders[idx].trim() +'\r\n'; } // Supported switch (this.method) { case JsSIP_C.INVITE: if (this.ua.configuration.session_timers) { supported.push('timer'); } if (this.ua.contact.pub_gruu || this.ua.contact.temp_gruu) { supported.push('gruu'); } supported.push('ice','replaces'); break; case JsSIP_C.UPDATE: if (this.ua.configuration.session_timers) { supported.push('timer'); } if (body) { supported.push('ice'); } supported.push('replaces'); } supported.push('outbound'); // Allow and Accept if (this.method === JsSIP_C.OPTIONS) { response += 'Allow: '+ JsSIP_C.ALLOWED_METHODS +'\r\n'; response += 'Accept: '+ JsSIP_C.ACCEPTED_BODY_TYPES +'\r\n'; } else if (code === 405) { response += 'Allow: '+ JsSIP_C.ALLOWED_METHODS +'\r\n'; } else if (code === 415 ) { response += 'Accept: '+ JsSIP_C.ACCEPTED_BODY_TYPES +'\r\n'; } response += 'Supported: ' + supported +'\r\n'; if(body) { length = Utils.str_utf8_length(body); response += 'Content-Type: application/sdp\r\n'; response += 'Content-Length: ' + length + '\r\n\r\n'; response += body; } else { response += 'Content-Length: ' + 0 + '\r\n\r\n'; } this.server_transaction.receiveResponse(code, response, onSuccess, onFailure); }; /** * Stateless reply. * -param {Number} code status code * -param {String} reason reason phrase */ IncomingRequest.prototype.reply_sl = function(code, reason) { var to, response, v = 0, vias = this.getHeaders('via'), length = vias.length; code = code || null; reason = reason || null; // Validate code and reason values if (!code || (code < 100 || code > 699)) { throw new TypeError('Invalid status_code: '+ code); } else if (reason && typeof reason !== 'string' && !(reason instanceof String)) { throw new TypeError('Invalid reason_phrase: '+ reason); } reason = reason || JsSIP_C.REASON_PHRASE[code] || ''; response = 'SIP/2.0 ' + code + ' ' + reason + '\r\n'; for(v; v < length; v++) { response += 'Via: ' + vias[v] + '\r\n'; } to = this.getHeader('To'); if(!this.to_tag && code > 100) { to += ';tag=' + Utils.newTag(); } else if(this.to_tag && !this.s('to').hasParam('tag')) { to += ';tag=' + this.to_tag; } response += 'To: ' + to + '\r\n'; response += 'From: ' + this.getHeader('From') + '\r\n'; response += 'Call-ID: ' + this.call_id + '\r\n'; response += 'CSeq: ' + this.cseq + ' ' + this.method + '\r\n'; response += 'Content-Length: ' + 0 + '\r\n\r\n'; this.transport.send(response); }; function IncomingResponse() { this.headers = {}; this.status_code = null; this.reason_phrase = null; } IncomingResponse.prototype = new IncomingMessage(); },{"./Constants":1,"./Grammar":6,"./NameAddrHeader":9,"./Utils":25,"debug":34,"sdp-transform":37}],19:[function(require,module,exports){ module.exports = Socket; /** * Interface documentation: http://jssip.net/documentation/$last_version/api/socket/ * * interface Socket { * attribute String via_transport * attribute String url * attribute String sip_uri * * method connect(); * method disconnect(); * method send(data); * * attribute EventHandler onconnect * attribute EventHandler ondisconnect * attribute EventHandler ondata * } * */ /** * Dependencies. */ var Utils = require('./Utils'); var Grammar = require('./Grammar'); var debugerror = require('debug')('JsSIP:ERROR:Socket'); debugerror.log = console.warn.bind(console); function Socket() {} Socket.isSocket = function(socket) { // Ignore if an array is given if (Array.isArray(socket)) { return false; } if (typeof socket === 'undefined') { debugerror('undefined JsSIP.Socket instance'); return false; } // Check Properties try { if (!Utils.isString(socket.url)) { debugerror('missing or invalid JsSIP.Socket url property'); throw new Error(); } if (!Utils.isString(socket.via_transport)) { debugerror('missing or invalid JsSIP.Socket via_transport property'); throw new Error(); } if (Grammar.parse(socket.sip_uri, 'SIP_URI') === -1) { debugerror('missing or invalid JsSIP.Socket sip_uri property'); throw new Error(); } } catch(e) { return false; } // Check Methods try { ['connect', 'disconnect', 'send'].forEach(function(method) { if (!Utils.isFunction(socket[method])) { debugerror('missing or invalid JsSIP.Socket method: ' + method); throw new Error(); } }); } catch(e) { return false; } return true; }; },{"./Grammar":6,"./Utils":25,"debug":34}],20:[function(require,module,exports){ var T1 = 500, T2 = 4000, T4 = 5000; var Timers = { T1: T1, T2: T2, T4: T4, TIMER_B: 64 * T1, TIMER_D: 0 * T1, TIMER_F: 64 * T1, TIMER_H: 64 * T1, TIMER_I: 0 * T1, TIMER_J: 0 * T1, TIMER_K: 0 * T4, TIMER_L: 64 * T1, TIMER_M: 64 * T1, PROVISIONAL_RESPONSE_INTERVAL: 60000 // See RFC 3261 Section 13.3.1.1 }; module.exports = Timers; },{}],21:[function(require,module,exports){ module.exports = { C: null, NonInviteClientTransaction: NonInviteClientTransaction, InviteClientTransaction: InviteClientTransaction, AckClientTransaction: AckClientTransaction, NonInviteServerTransaction: NonInviteServerTransaction, InviteServerTransaction: InviteServerTransaction, checkTransaction: checkTransaction }; var C = { // Transaction states STATUS_TRYING: 1, STATUS_PROCEEDING: 2, STATUS_CALLING: 3, STATUS_ACCEPTED: 4, STATUS_COMPLETED: 5, STATUS_TERMINATED: 6, STATUS_CONFIRMED: 7, // Transaction types NON_INVITE_CLIENT: 'nict', NON_INVITE_SERVER: 'nist', INVITE_CLIENT: 'ict', INVITE_SERVER: 'ist' }; /** * Expose C object. */ module.exports.C = C; /** * Dependencies. */ var util = require('util'); var events = require('events'); var debugnict = require('debug')('JsSIP:NonInviteClientTransaction'); var debugict = require('debug')('JsSIP:InviteClientTransaction'); var debugact = require('debug')('JsSIP:AckClientTransaction'); var debugnist = require('debug')('JsSIP:NonInviteServerTransaction'); var debugist = require('debug')('JsSIP:InviteServerTransaction'); var JsSIP_C = require('./Constants'); var Timers = require('./Timers'); function NonInviteClientTransaction(request_sender, request, transport) { var via; this.type = C.NON_INVITE_CLIENT; this.transport = transport; this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000); this.request_sender = request_sender; this.request = request; via = 'SIP/2.0/' + transport.via_transport; via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id; this.request.setHeader('via', via); this.request_sender.ua.newTransaction(this); events.EventEmitter.call(this); } util.inherits(NonInviteClientTransaction, events.EventEmitter); NonInviteClientTransaction.prototype.stateChanged = function(state) { this.state = state; this.emit('stateChanged'); }; NonInviteClientTransaction.prototype.send = function() { var tr = this; this.stateChanged(C.STATUS_TRYING); this.F = setTimeout(function() {tr.timer_F();}, Timers.TIMER_F); if(!this.transport.send(this.request)) { this.onTransportError(); } }; NonInviteClientTransaction.prototype.onTransportError = function() { debugnict('transport error occurred, deleting transaction ' + this.id); clearTimeout(this.F); clearTimeout(this.K); this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); this.request_sender.onTransportError(); }; NonInviteClientTransaction.prototype.timer_F = function() { debugnict('Timer F expired for transaction ' + this.id); this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); this.request_sender.onRequestTimeout(); }; NonInviteClientTransaction.prototype.timer_K = function() { this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); }; NonInviteClientTransaction.prototype.receiveResponse = function(response) { var tr = this, status_code = response.status_code; if(status_code < 200) { switch(this.state) { case C.STATUS_TRYING: case C.STATUS_PROCEEDING: this.stateChanged(C.STATUS_PROCEEDING); this.request_sender.receiveResponse(response); break; } } else { switch(this.state) { case C.STATUS_TRYING: case C.STATUS_PROCEEDING: this.stateChanged(C.STATUS_COMPLETED); clearTimeout(this.F); if(status_code === 408) { this.request_sender.onRequestTimeout(); } else { this.request_sender.receiveResponse(response); } this.K = setTimeout(function() {tr.timer_K();}, Timers.TIMER_K); break; case C.STATUS_COMPLETED: break; } } }; function InviteClientTransaction(request_sender, request, transport) { var via, tr = this; this.type = C.INVITE_CLIENT; this.transport = transport; this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000); this.request_sender = request_sender; this.request = request; via = 'SIP/2.0/' + transport.via_transport; via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id; this.request.setHeader('via', via); this.request_sender.ua.newTransaction(this); // TODO: Adding here the cancel() method is a hack that must be fixed. // Add the cancel property to the request. //Will be called from the request instance, not the transaction itself. this.request.cancel = function(reason) { tr.cancel_request(tr, reason); }; events.EventEmitter.call(this); } util.inherits(InviteClientTransaction, events.EventEmitter); InviteClientTransaction.prototype.stateChanged = function(state) { this.state = state; this.emit('stateChanged'); }; InviteClientTransaction.prototype.send = function() { var tr = this; this.stateChanged(C.STATUS_CALLING); this.B = setTimeout(function() { tr.timer_B(); }, Timers.TIMER_B); if(!this.transport.send(this.request)) { this.onTransportError(); } }; InviteClientTransaction.prototype.onTransportError = function() { clearTimeout(this.B); clearTimeout(this.D); clearTimeout(this.M); if (this.state !== C.STATUS_ACCEPTED) { debugict('transport error occurred, deleting transaction ' + this.id); this.request_sender.onTransportError(); } this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); }; // RFC 6026 7.2 InviteClientTransaction.prototype.timer_M = function() { debugict('Timer M expired for transaction ' + this.id); if(this.state === C.STATUS_ACCEPTED) { clearTimeout(this.B); this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); } }; // RFC 3261 17.1.1 InviteClientTransaction.prototype.timer_B = function() { debugict('Timer B expired for transaction ' + this.id); if(this.state === C.STATUS_CALLING) { this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); this.request_sender.onRequestTimeout(); } }; InviteClientTransaction.prototype.timer_D = function() { debugict('Timer D expired for transaction ' + this.id); clearTimeout(this.B); this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); }; InviteClientTransaction.prototype.sendACK = function(response) { var tr = this; this.ack = 'ACK ' + this.request.ruri + ' SIP/2.0\r\n'; this.ack += 'Via: ' + this.request.headers.Via.toString() + '\r\n'; if(this.request.headers.Route) { this.ack += 'Route: ' + this.request.headers.Route.toString() + '\r\n'; } this.ack += 'To: ' + response.getHeader('to') + '\r\n'; this.ack += 'From: ' + this.request.headers.From.toString() + '\r\n'; this.ack += 'Call-ID: ' + this.request.headers['Call-ID'].toString() + '\r\n'; this.ack += 'CSeq: ' + this.request.headers.CSeq.toString().split(' ')[0]; this.ack += ' ACK\r\n'; this.ack += 'Content-Length: 0\r\n\r\n'; this.D = setTimeout(function() {tr.timer_D();}, Timers.TIMER_D); this.transport.send(this.ack); }; InviteClientTransaction.prototype.cancel_request = function(tr, reason) { var request = tr.request; this.cancel = JsSIP_C.CANCEL + ' ' + request.ruri + ' SIP/2.0\r\n'; this.cancel += 'Via: ' + request.headers.Via.toString() + '\r\n'; if(this.request.headers.Route) { this.cancel += 'Route: ' + request.headers.Route.toString() + '\r\n'; } this.cancel += 'To: ' + request.headers.To.toString() + '\r\n'; this.cancel += 'From: ' + request.headers.From.toString() + '\r\n'; this.cancel += 'Call-ID: ' + request.headers['Call-ID'].toString() + '\r\n'; this.cancel += 'CSeq: ' + request.headers.CSeq.toString().split(' ')[0] + ' CANCEL\r\n'; if(reason) { this.cancel += 'Reason: ' + reason + '\r\n'; } this.cancel += 'Content-Length: 0\r\n\r\n'; // Send only if a provisional response (>100) has been received. if(this.state === C.STATUS_PROCEEDING) { this.transport.send(this.cancel); } }; InviteClientTransaction.prototype.receiveResponse = function(response) { var tr = this, status_code = response.status_code; if(status_code >= 100 && status_code <= 199) { switch(this.state) { case C.STATUS_CALLING: this.stateChanged(C.STATUS_PROCEEDING); this.request_sender.receiveResponse(response); break; case C.STATUS_PROCEEDING: this.request_sender.receiveResponse(response); break; } } else if(status_code >= 200 && status_code <= 299) { switch(this.state) { case C.STATUS_CALLING: case C.STATUS_PROCEEDING: this.stateChanged(C.STATUS_ACCEPTED); this.M = setTimeout(function() { tr.timer_M(); }, Timers.TIMER_M); this.request_sender.receiveResponse(response); break; case C.STATUS_ACCEPTED: this.request_sender.receiveResponse(response); break; } } else if(status_code >= 300 && status_code <= 699) { switch(this.state) { case C.STATUS_CALLING: case C.STATUS_PROCEEDING: this.stateChanged(C.STATUS_COMPLETED); this.sendACK(response); this.request_sender.receiveResponse(response); break; case C.STATUS_COMPLETED: this.sendACK(response); break; } } }; function AckClientTransaction(request_sender, request, transport) { var via; this.transport = transport; this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000); this.request_sender = request_sender; this.request = request; via = 'SIP/2.0/' + transport.via_transport; via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id; this.request.setHeader('via', via); events.EventEmitter.call(this); } util.inherits(AckClientTransaction, events.EventEmitter); AckClientTransaction.prototype.send = function() { if(!this.transport.send(this.request)) { this.onTransportError(); } }; AckClientTransaction.prototype.onTransportError = function() { debugact('transport error occurred for transaction ' + this.id); this.request_sender.onTransportError(); }; function NonInviteServerTransaction(request, ua) { this.type = C.NON_INVITE_SERVER; this.id = request.via_branch; this.request = request; this.transport = request.transport; this.ua = ua; this.last_response = ''; request.server_transaction = this; this.state = C.STATUS_TRYING; ua.newTransaction(this); events.EventEmitter.call(this); } util.inherits(NonInviteServerTransaction, events.EventEmitter); NonInviteServerTransaction.prototype.stateChanged = function(state) { this.state = state; this.emit('stateChanged'); }; NonInviteServerTransaction.prototype.timer_J = function() { debugnist('Timer J expired for transaction ' + this.id); this.stateChanged(C.STATUS_TERMINATED); this.ua.destroyTransaction(this); }; NonInviteServerTransaction.prototype.onTransportError = function() { if (!this.transportError) { this.transportError = true; debugnist('transport error occurred, deleting transaction ' + this.id); clearTimeout(this.J); this.stateChanged(C.STATUS_TERMINATED); this.ua.destroyTransaction(this); } }; NonInviteServerTransaction.prototype.receiveResponse = function(status_code, response, onSuccess, onFailure) { var tr = this; if(status_code === 100) { /* RFC 4320 4.1 * 'A SIP element MUST NOT * send any provisional response with a * Status-Code other than 100 to a non-INVITE request.' */ switch(this.state) { case C.STATUS_TRYING: this.stateChanged(C.STATUS_PROCEEDING); if(!this.transport.send(response)) { this.onTransportError(); } break; case C.STATUS_PROCEEDING: this.last_response = response; if(!this.transport.send(response)) { this.onTransportError(); if (onFailure) { onFailure(); } } else if (onSuccess) { onSuccess(); } break; } } else if(status_code >= 200 && status_code <= 699) { switch(this.state) { case C.STATUS_TRYING: case C.STATUS_PROCEEDING: this.stateChanged(C.STATUS_COMPLETED); this.last_response = response; this.J = setTimeout(function() { tr.timer_J(); }, Timers.TIMER_J); if(!this.transport.send(response)) { this.onTransportError(); if (onFailure) { onFailure(); } } else if (onSuccess) { onSuccess(); } break; case C.STATUS_COMPLETED: break; } } }; function InviteServerTransaction(request, ua) { this.type = C.INVITE_SERVER; this.id = request.via_branch; this.request = request; this.transport = request.transport; this.ua = ua; this.last_response = ''; request.server_transaction = this; this.state = C.STATUS_PROCEEDING; ua.newTransaction(this); this.resendProvisionalTimer = null; request.reply(100); events.EventEmitter.call(this); } util.inherits(InviteServerTransaction, events.EventEmitter); InviteServerTransaction.prototype.stateChanged = function(state) { this.state = state; this.emit('stateChanged'); }; InviteServerTransaction.prototype.timer_H = function() { debugist('Timer H expired for transaction ' + this.id); if(this.state === C.STATUS_COMPLETED) { debugist('ACK not received, dialog will be terminated'); } this.stateChanged(C.STATUS_TERMINATED); this.ua.destroyTransaction(this); }; InviteServerTransaction.prototype.timer_I = function() { this.stateChanged(C.STATUS_TERMINATED); }; // RFC 6026 7.1 InviteServerTransaction.prototype.timer_L = function() { debugist('Timer L expired for transaction ' + this.id); if(this.state === C.STATUS_ACCEPTED) { this.stateChanged(C.STATUS_TERMINATED); this.ua.destroyTransaction(this); } }; InviteServerTransaction.prototype.onTransportError = function() { if (!this.transportError) { this.transportError = true; debugist('transport error occurred, deleting transaction ' + this.id); if (this.resendProvisionalTimer !== null) { clearInterval(this.resendProvisionalTimer); this.resendProvisionalTimer = null; } clearTimeout(this.L); clearTimeout(this.H); clearTimeout(this.I); this.stateChanged(C.STATUS_TERMINATED); this.ua.destroyTransaction(this); } }; InviteServerTransaction.prototype.resend_provisional = function() { if(!this.transport.send(this.last_response)) { this.onTransportError(); } }; // INVITE Server Transaction RFC 3261 17.2.1 InviteServerTransaction.prototype.receiveResponse = function(status_code, response, onSuccess, onFailure) { var tr = this; if(status_code >= 100 && status_code <= 199) { switch(this.state) { case C.STATUS_PROCEEDING: if(!this.transport.send(response)) { this.onTransportError(); } this.last_response = response; break; } } if(status_code > 100 && status_code <= 199 && this.state === C.STATUS_PROCEEDING) { // Trigger the resendProvisionalTimer only for the first non 100 provisional response. if(this.resendProvisionalTimer === null) { this.resendProvisionalTimer = setInterval(function() { tr.resend_provisional();}, Timers.PROVISIONAL_RESPONSE_INTERVAL); } } else if(status_code >= 200 && status_code <= 299) { switch(this.state) { case C.STATUS_PROCEEDING: this.stateChanged(C.STATUS_ACCEPTED); this.last_response = response; this.L = setTimeout(function() { tr.timer_L(); }, Timers.TIMER_L); if (this.resendProvisionalTimer !== null) { clearInterval(this.resendProvisionalTimer); this.resendProvisionalTimer = null; } /* falls through */ case C.STATUS_ACCEPTED: // Note that this point will be reached for proceeding tr.state also. if(!this.transport.send(response)) { this.onTransportError(); if (onFailure) { onFailure(); } } else if (onSuccess) { onSuccess(); } break; } } else if(status_code >= 300 && status_code <= 699) { switch(this.state) { case C.STATUS_PROCEEDING: if (this.resendProvisionalTimer !== null) { clearInterval(this.resendProvisionalTimer); this.resendProvisionalTimer = null; } if(!this.transport.send(response)) { this.onTransportError(); if (onFailure) { onFailure(); } } else { this.stateChanged(C.STATUS_COMPLETED); this.H = setTimeout(function() { tr.timer_H(); }, Timers.TIMER_H); if (onSuccess) { onSuccess(); } } break; } } }; /** * INVITE: * _true_ if retransmission * _false_ new request * * ACK: * _true_ ACK to non2xx response * _false_ ACK must be passed to TU (accepted state) * ACK to 2xx response * * CANCEL: * _true_ no matching invite transaction * _false_ matching invite transaction and no final response sent * * OTHER: * _true_ retransmission * _false_ new request */ function checkTransaction(ua, request) { var tr; switch(request.method) { case JsSIP_C.INVITE: tr = ua.transactions.ist[request.via_branch]; if(tr) { switch(tr.state) { case C.STATUS_PROCEEDING: tr.transport.send(tr.last_response); break; // RFC 6026 7.1 Invite retransmission //received while in C.STATUS_ACCEPTED state. Absorb it. case C.STATUS_ACCEPTED: break; } return true; } break; case JsSIP_C.ACK: tr = ua.transactions.ist[request.via_branch]; // RFC 6026 7.1 if(tr) { if(tr.state === C.STATUS_ACCEPTED) { return false; } else if(tr.state === C.STATUS_COMPLETED) { tr.state = C.STATUS_CONFIRMED; tr.I = setTimeout(function() {tr.timer_I();}, Timers.TIMER_I); return true; } } // ACK to 2XX Response. else { return false; } break; case JsSIP_C.CANCEL: tr = ua.transactions.ist[request.via_branch]; if(tr) { request.reply_sl(200); if(tr.state === C.STATUS_PROCEEDING) { return false; } else { return true; } } else { request.reply_sl(481); return true; } break; default: // Non-INVITE Server Transaction RFC 3261 17.2.2 tr = ua.transactions.nist[request.via_branch]; if(tr) { switch(tr.state) { case C.STATUS_TRYING: break; case C.STATUS_PROCEEDING: case C.STATUS_COMPLETED: tr.transport.send(tr.last_response); break; } return true; } break; } } },{"./Constants":1,"./Timers":20,"debug":34,"events":28,"util":32}],22:[function(require,module,exports){ module.exports = Transport; /** * Dependencies. */ var Socket = require('./Socket'); var debug = require('debug')('JsSIP:Transport'); var debugerror = require('debug')('JsSIP:ERROR:Transport'); /** * Constants */ var C = { // Transport status STATUS_CONNECTED: 0, STATUS_CONNECTING: 1, STATUS_DISCONNECTED: 2, // Socket status SOCKET_STATUS_READY: 0, SOCKET_STATUS_ERROR: 1, // Recovery options recovery_options: { min_interval: 2, // minimum interval in seconds between recover attempts max_interval: 30 // maximum interval in seconds between recover attempts } }; /* * Manages one or multiple JsSIP.Socket instances. * Is reponsible for transport recovery logic among all socket instances. * * @socket JsSIP::Socket instance */ function Transport(sockets, recovery_options) { debug('new()'); this.status = C.STATUS_DISCONNECTED; // current socket this.socket = null; // socket collection this.sockets = []; this.recovery_options = recovery_options || C.recovery_options; this.recover_attempts = 0; this.recovery_timer = null; this.close_requested = false; if (typeof sockets === 'undefined') { throw new TypeError('Invalid argument.' + ' undefined \'sockets\' argument'); } if (!(sockets instanceof Array)) { sockets = [ sockets ]; } sockets.forEach(function(socket) { if (!Socket.isSocket(socket.socket)) { throw new TypeError('Invalid argument.' + ' invalid \'JsSIP.Socket\' instance'); } if (socket.weight && !Number(socket.weight)) { throw new TypeError('Invalid argument.' + ' \'weight\' attribute is not a number'); } this.sockets.push({ socket: socket.socket, weight: socket.weight || 0, status: C.SOCKET_STATUS_READY }); }, this); // read only properties Object.defineProperties(this, { via_transport: { get: function() { return this.socket.via_transport; } }, url: { get: function() { return this.socket.url; } }, sip_uri: { get: function() { return this.socket.sip_uri; } } }); // get the socket with higher weight getSocket.call(this); } /** * Instance Methods */ Transport.prototype.connect = function() { debug('connect()'); if (this.isConnected()) { debug('Transport is already connected'); return; } else if (this.isConnecting()) { debug('Transport is connecting'); return; } this.close_requested = false; this.status = C.STATUS_CONNECTING; this.onconnecting({ socket:this.socket, attempts:this.recover_attempts }); if (!this.close_requested) { // bind socket event callbacks this.socket.onconnect = onConnect.bind(this); this.socket.ondisconnect = onDisconnect.bind(this); this.socket.ondata = onData.bind(this); this.socket.connect(); } return; }; Transport.prototype.disconnect = function() { debug('close()'); this.close_requested = true; this.recover_attempts = 0; this.status = C.STATUS_DISCONNECTED; // clear recovery_timer if (this.recovery_timer !== null) { clearTimeout(this.recovery_timer); this.recovery_timer = null; } // unbind socket event callbacks this.socket.onconnect = function() {}; this.socket.ondisconnect = function() {}; this.socket.ondata = function() {}; this.socket.disconnect(); this.ondisconnect(); }; Transport.prototype.send = function(data) { debug('send()'); if (!this.isConnected()) { debugerror('unable to send message, transport is not connected'); return false; } var message = data.toString(); debug('sending message:\n\n' + message + '\n'); return this.socket.send(message); }; Transport.prototype.isConnected = function() { return this.status === C.STATUS_CONNECTED; }; Transport.prototype.isConnecting = function() { return this.status === C.STATUS_CONNECTING; }; /** * Socket Event Handlers */ function onConnect() { this.recover_attempts = 0; this.status = C.STATUS_CONNECTED; // clear recovery_timer if (this.recovery_timer !== null) { clearTimeout(this.recovery_timer); this.recovery_timer = null; } this.onconnect( {socket:this} ); } function onDisconnect(error, code, reason) { this.status = C.STATUS_DISCONNECTED; this.ondisconnect({ socket:this.socket, error:error, code:code, reason:reason }); if (this.close_requested) { return; } // update socket status else { this.sockets.forEach(function(socket) { if (this.socket === socket.socket) { socket.status = C.SOCKET_STATUS_ERROR; } }, this); } reconnect.call(this, error); } function onData(data) { // CRLF Keep Alive response from server. Ignore it. if(data === '\r\n') { debug('received message with CRLF Keep Alive response'); return; } // binary message. else if (typeof data !== 'string') { try { data = String.fromCharCode.apply(null, new Uint8Array(data)); } catch(evt) { debug('received binary message failed to be converted into string,' + ' message discarded'); return; } debug('received binary message:\n\n' + data + '\n'); } // text message. else { debug('received text message:\n\n' + data + '\n'); } this.ondata({ transport:this, message:data }); } function reconnect() { var k, self = this; this.recover_attempts+=1; k = Math.floor((Math.random() * Math.pow(2,this.recover_attempts)) +1); if (k < this.recovery_options.min_interval) { k = this.recovery_options.min_interval; } else if (k > this.recovery_options.max_interval) { k = this.recovery_options.max_interval; } debug('reconnection attempt: '+ this.recover_attempts + '. next connection attempt in '+ k +' seconds'); this.recovery_timer = setTimeout(function() { if (!self.close_requested && !(self.isConnected() || self.isConnecting())) { // get the next available socket with higher weight getSocket.call(self); // connect the socket self.connect(); } }, k * 1000); } /** * get the next available socket with higher weight */ function getSocket() { var candidates = []; this.sockets.forEach(function(socket) { if (socket.status === C.SOCKET_STATUS_ERROR) { return; // continue the array iteration } else if (candidates.length === 0) { candidates.push(socket); } else if (socket.weight > candidates[0].weight) { candidates = [socket]; } else if (socket.weight === candidates[0].weight) { candidates.push(socket); } }); if (candidates.length === 0) { // all sockets have failed. reset sockets status this.sockets.forEach(function(socket) { socket.status = C.SOCKET_STATUS_READY; }); // get next available socket getSocket.call(this); return; } var idx = Math.floor((Math.random()* candidates.length)); this.socket = candidates[idx].socket; } },{"./Socket":19,"debug":34}],23:[function(require,module,exports){ module.exports = UA; var C = { // UA status codes STATUS_INIT : 0, STATUS_READY: 1, STATUS_USER_CLOSED: 2, STATUS_NOT_READY: 3, // UA error codes CONFIGURATION_ERROR: 1, NETWORK_ERROR: 2 }; /** * Expose C object. */ UA.C = C; /** * Dependencies. */ var util = require('util'); var events = require('events'); var debug = require('debug')('JsSIP:UA'); var debugerror = require('debug')('JsSIP:ERROR:UA'); debugerror.log = console.warn.bind(console); var JsSIP_C = require('./Constants'); var Registrator = require('./Registrator'); var RTCSession = require('./RTCSession'); var Message = require('./Message'); var Transactions = require('./Transactions'); var Transport = require('./Transport'); var Socket = require('./Socket'); var Utils = require('./Utils'); var Exceptions = require('./Exceptions'); var URI = require('./URI'); var Grammar = require('./Grammar'); var Parser = require('./Parser'); var SIPMessage = require('./SIPMessage'); var sanityCheck = require('./sanityCheck'); /** * The User-Agent class. * @class JsSIP.UA * @param {Object} configuration Configuration parameters. * @throws {JsSIP.Exceptions.ConfigurationError} If a configuration parameter is invalid. * @throws {TypeError} If no configuration is given. */ function UA(configuration) { debug('new() [configuration:%o]', configuration); this.cache = { credentials: {} }; this.configuration = {}; this.dynConfiguration = {}; this.dialogs = {}; //User actions outside any session/dialog (MESSAGE) this.applicants = {}; this.sessions = {}; this.transport = null; this.contact = null; this.status = C.STATUS_INIT; this.error = null; this.transactions = { nist: {}, nict: {}, ist: {}, ict: {} }; // Custom UA empty object for high level use this.data = {}; this.closeTimer = null; Object.defineProperties(this, { transactionsCount: { get: function() { var type, transactions = ['nist','nict','ist','ict'], count = 0; for (type in transactions) { count += Object.keys(this.transactions[transactions[type]]).length; } return count; } }, nictTransactionsCount: { get: function() { return Object.keys(this.transactions.nict).length; } }, nistTransactionsCount: { get: function() { return Object.keys(this.transactions.nist).length; } }, ictTransactionsCount: { get: function() { return Object.keys(this.transactions.ict).length; } }, istTransactionsCount: { get: function() { return Object.keys(this.transactions.ist).length; } } }); /** * Load configuration */ if(configuration === undefined) { throw new TypeError('Not enough arguments'); } try { this.loadConfig(configuration); } catch(e) { this.status = C.STATUS_NOT_READY; this.error = C.CONFIGURATION_ERROR; throw e; } // Initialize registrator this._registrator = new Registrator(this); events.EventEmitter.call(this); } util.inherits(UA, events.EventEmitter); //================= // High Level API //================= /** * Connect to the server if status = STATUS_INIT. * Resume UA after being closed. */ UA.prototype.start = function() { debug('start()'); if (this.status === C.STATUS_INIT) { this.transport.connect(); } else if(this.status === C.STATUS_USER_CLOSED) { debug('restarting UA'); // disconnect if (this.closeTimer !== null) { clearTimeout(this.closeTimer); this.closeTimer = null; this.transport.disconnect(); } // reconnect this.status = C.STATUS_INIT; this.transport.connect(); } else if (this.status === C.STATUS_READY) { debug('UA is in READY status, not restarted'); } else { debug('ERROR: connection is down, Auto-Recovery system is trying to reconnect'); } // Set dynamic configuration. this.dynConfiguration.register = this.configuration.register; }; /** * Register. */ UA.prototype.register = function() { debug('register()'); this.dynConfiguration.register = true; this._registrator.register(); }; /** * Unregister. */ UA.prototype.unregister = function(options) { debug('unregister()'); this.dynConfiguration.register = false; this._registrator.unregister(options); }; /** * Get the Registrator instance. */ UA.prototype.registrator = function() { return this._registrator; }; /** * Registration state. */ UA.prototype.isRegistered = function() { if(this._registrator.registered) { return true; } else { return false; } }; /** * Connection state. */ UA.prototype.isConnected = function() { return this.transport.isConnected(); }; /** * Make an outgoing call. * * -param {String} target * -param {Object} views * -param {Object} [options] * * -throws {TypeError} * */ UA.prototype.call = function(target, options) { debug('call()'); var session; session = new RTCSession(this); session.connect(target, options); return session; }; /** * Send a message. * * -param {String} target * -param {String} body * -param {Object} [options] * * -throws {TypeError} * */ UA.prototype.sendMessage = function(target, body, options) { debug('sendMessage()'); var message; message = new Message(this); message.send(target, body, options); return message; }; /** * Terminate ongoing sessions. */ UA.prototype.terminateSessions = function(options) { debug('terminateSessions()'); for(var idx in this.sessions) { if (!this.sessions[idx].isEnded()) { this.sessions[idx].terminate(options); } } }; /** * Gracefully close. * */ UA.prototype.stop = function() { debug('stop()'); var session; var applicant; var num_sessions; var ua = this; // Remove dynamic settings. this.dynConfiguration = {}; if(this.status === C.STATUS_USER_CLOSED) { debug('UA already closed'); return; } // Close registrator this._registrator.close(); // If there are session wait a bit so CANCEL/BYE can be sent and their responses received. num_sessions = Object.keys(this.sessions).length; // Run _terminate_ on every Session for(session in this.sessions) { debug('closing session ' + session); try { this.sessions[session].terminate(); } catch(error) {} } // Run _close_ on every applicant for(applicant in this.applicants) { try { this.applicants[applicant].close(); } catch(error) {} } this.status = C.STATUS_USER_CLOSED; if (this.nistTransactionsCount === 0 && this.nictTransactionsCount === 0 && this.ictTransactionsCount === 0 && this.istTransactionsCount === 0 && num_sessions === 0) { ua.transport.disconnect(); } else { this.closeTimer = setTimeout(function() { ua.closeTimer = null; ua.transport.disconnect(); }, 2000); } }; /** * Normalice a string into a valid SIP request URI * -param {String} target * -returns {JsSIP.URI|undefined} */ UA.prototype.normalizeTarget = function(target) { return Utils.normalizeTarget(target, this.configuration.hostport_params); }; /** * Allow retrieving configuration and autogenerated fields in runtime. */ UA.prototype.get = function(parameter) { switch(parameter) { case 'realm': return this.configuration.realm; case 'ha1': return this.configuration.ha1; default: debugerror('get() | cannot get "%s" parameter in runtime', parameter); return undefined; } return true; }; /** * Allow configuration changes in runtime. * Returns true if the parameter could be set. */ UA.prototype.set = function(parameter, value) { switch(parameter) { case 'password': { this.configuration.password = String(value); break; } case 'realm': { this.configuration.realm = String(value); break; } case 'ha1': { this.configuration.ha1 = String(value); // Delete the plain SIP password. this.configuration.password = null; break; } case 'display_name': { if (Grammar.parse('"' + value + '"', 'display_name') === -1) { debugerror('set() | wrong "display_name"'); return false; } this.configuration.display_name = value; break; } default: debugerror('set() | cannot set "%s" parameter in runtime', parameter); return false; } return true; }; //=============================== // Private (For internal use) //=============================== // UA.prototype.saveCredentials = function(credentials) { // this.cache.credentials[credentials.realm] = this.cache.credentials[credentials.realm] || {}; // this.cache.credentials[credentials.realm][credentials.uri] = credentials; // }; // UA.prototype.getCredentials = function(request) { // var realm, credentials; // realm = request.ruri.host; // if (this.cache.credentials[realm] && this.cache.credentials[realm][request.ruri]) { // credentials = this.cache.credentials[realm][request.ruri]; // credentials.method = request.method; // } // return credentials; // }; //========================== // Event Handlers //========================== /** * new Transaction */ UA.prototype.newTransaction = function(transaction) { this.transactions[transaction.type][transaction.id] = transaction; this.emit('newTransaction', { transaction: transaction }); }; /** * Transaction destroyed. */ UA.prototype.destroyTransaction = function(transaction) { delete this.transactions[transaction.type][transaction.id]; this.emit('transactionDestroyed', { transaction: transaction }); }; /** * new Message */ UA.prototype.newMessage = function(data) { this.emit('newMessage', data); }; /** * new RTCSession */ UA.prototype.newRTCSession = function(data) { this.emit('newRTCSession', data); }; /** * Registered */ UA.prototype.registered = function(data) { this.emit('registered', data); }; /** * Unregistered */ UA.prototype.unregistered = function(data) { this.emit('unregistered', data); }; /** * Registration Failed */ UA.prototype.registrationFailed = function(data) { this.emit('registrationFailed', data); }; //========================= // receiveRequest //========================= /** * Request reception */ UA.prototype.receiveRequest = function(request) { var dialog, session, message, replaces, method = request.method; // Check that request URI points to us if(request.ruri.user !== this.configuration.uri.user && request.ruri.user !== this.contact.uri.user) { debug('Request-URI does not point to us'); if (request.method !== JsSIP_C.ACK) { request.reply_sl(404); } return; } // Check request URI scheme if(request.ruri.scheme === JsSIP_C.SIPS) { request.reply_sl(416); return; } // Check transaction if(Transactions.checkTransaction(this, request)) { return; } // Create the server transaction if(method === JsSIP_C.INVITE) { new Transactions.InviteServerTransaction(request, this); } else if(method !== JsSIP_C.ACK && method !== JsSIP_C.CANCEL) { new Transactions.NonInviteServerTransaction(request, this); } /* RFC3261 12.2.2 * Requests that do not change in any way the state of a dialog may be * received within a dialog (for example, an OPTIONS request). * They are processed as if they had been received outside the dialog. */ if(method === JsSIP_C.OPTIONS) { request.reply(200); } else if (method === JsSIP_C.MESSAGE) { if (this.listeners('newMessage').length === 0) { request.reply(405); return; } message = new Message(this); message.init_incoming(request); } else if (method === JsSIP_C.INVITE) { // Initial INVITE if(!request.to_tag && this.listeners('newRTCSession').length === 0) { request.reply(405); return; } } // Initial Request if(!request.to_tag) { switch(method) { case JsSIP_C.INVITE: if (window.RTCPeerConnection) { // TODO if (request.hasHeader('replaces')) { replaces = request.replaces; dialog = this.findDialog(replaces.call_id, replaces.from_tag, replaces.to_tag); if (dialog) { session = dialog.owner; if (!session.isEnded()) { session.receiveRequest(request); } else { request.reply(603); } } else { request.reply(481); } } else { session = new RTCSession(this); session.init_incoming(request); } } else { debugerror('INVITE received but WebRTC is not supported'); request.reply(488); } break; case JsSIP_C.BYE: // Out of dialog BYE received request.reply(481); break; case JsSIP_C.CANCEL: session = this.findSession(request); if (session) { session.receiveRequest(request); } else { debug('received CANCEL request for a non existent session'); } break; case JsSIP_C.ACK: /* Absorb it. * ACK request without a corresponding Invite Transaction * and without To tag. */ break; default: request.reply(405); break; } } // In-dialog request else { dialog = this.findDialog(request.call_id, request.from_tag, request.to_tag); if(dialog) { dialog.receiveRequest(request); } else if (method === JsSIP_C.NOTIFY) { session = this.findSession(request); if(session) { session.receiveRequest(request); } else { debug('received NOTIFY request for a non existent subscription'); request.reply(481, 'Subscription does not exist'); } } /* RFC3261 12.2.2 * Request with to tag, but no matching dialog found. * Exception: ACK for an Invite request for which a dialog has not * been created. */ else { if(method !== JsSIP_C.ACK) { request.reply(481); } } } }; //================= // Utils //================= /** * Get the session to which the request belongs to, if any. */ UA.prototype.findSession = function(request) { var sessionIDa = request.call_id + request.from_tag, sessionA = this.sessions[sessionIDa], sessionIDb = request.call_id + request.to_tag, sessionB = this.sessions[sessionIDb]; if(sessionA) { return sessionA; } else if(sessionB) { return sessionB; } else { return null; } }; /** * Get the dialog to which the request belongs to, if any. */ UA.prototype.findDialog = function(call_id, from_tag, to_tag) { var id = call_id + from_tag + to_tag, dialog = this.dialogs[id]; if(dialog) { return dialog; } else { id = call_id + to_tag + from_tag; dialog = this.dialogs[id]; if(dialog) { return dialog; } else { return null; } } }; UA.prototype.loadConfig = function(configuration) { // Settings and default values var parameter, value, checked_value, hostport_params, registrar_server, settings = { /* Host address * Value to be set in Via sent_by and host part of Contact FQDN */ via_host: Utils.createRandomToken(12) + '.invalid', // SIP Contact URI contact_uri: null, // SIP authentication password password: null, // SIP authentication realm realm: null, // SIP authentication HA1 hash ha1: null, // Registration parameters register_expires: 600, register: true, registrar_server: null, use_preloaded_route: false, // Session parameters no_answer_timeout: 60, session_timers: true, }; // Pre-Configuration // Check Mandatory parameters for(parameter in UA.configuration_check.mandatory) { if(!configuration.hasOwnProperty(parameter)) { throw new Exceptions.ConfigurationError(parameter); } else { value = configuration[parameter]; checked_value = UA.configuration_check.mandatory[parameter].call(this, value); if (checked_value !== undefined) { settings[parameter] = checked_value; } else { throw new Exceptions.ConfigurationError(parameter, value); } } } // Check Optional parameters for(parameter in UA.configuration_check.optional) { if(configuration.hasOwnProperty(parameter)) { value = configuration[parameter]; /* If the parameter value is null, empty string, undefined, empty array * or it's a number with NaN value, then apply its default value. */ if (Utils.isEmpty(value)) { continue; } checked_value = UA.configuration_check.optional[parameter].call(this, value, configuration); if (checked_value !== undefined) { settings[parameter] = checked_value; } else { throw new Exceptions.ConfigurationError(parameter, value); } } } // Post Configuration Process // Allow passing 0 number as display_name. if (settings.display_name === 0) { settings.display_name = '0'; } // Instance-id for GRUU. if (!settings.instance_id) { settings.instance_id = Utils.newUUID(); } // jssip_id instance parameter. Static random tag of length 5. settings.jssip_id = Utils.createRandomToken(5); // String containing settings.uri without scheme and user. hostport_params = settings.uri.clone(); hostport_params.user = null; settings.hostport_params = hostport_params.toString().replace(/^sip:/i, ''); // Transport var sockets = []; if (settings.sockets && Array.isArray(settings.sockets)) { sockets = sockets.concat(settings.sockets); } if (sockets.length === 0) { throw new Exceptions.ConfigurationError('sockets'); } try { this.transport = new Transport(sockets, { /* recovery options */ max_interval: settings.connection_recovery_max_interval, min_interval: settings.connection_recovery_min_interval }); // Transport event callbacks this.transport.onconnecting = onTransportConnecting.bind(this); this.transport.onconnect = onTransportConnect.bind(this); this.transport.ondisconnect = onTransportDisconnect.bind(this); this.transport.ondata = onTransportData.bind(this); // transport options not needed here anymore delete settings.connection_recovery_max_interval; delete settings.connection_recovery_min_interval; delete settings.sockets; } catch (e) { debugerror(e); throw new Exceptions.ConfigurationError('sockets', sockets); } // Check whether authorization_user is explicitly defined. // Take 'settings.uri.user' value if not. if (!settings.authorization_user) { settings.authorization_user = settings.uri.user; } // If no 'registrar_server' is set use the 'uri' value without user portion and // without URI params/headers. if (!settings.registrar_server) { registrar_server = settings.uri.clone(); registrar_server.user = null; registrar_server.clearParams(); registrar_server.clearHeaders(); settings.registrar_server = registrar_server; } // User no_answer_timeout. settings.no_answer_timeout = settings.no_answer_timeout * 1000; // Via Host if (settings.contact_uri) { settings.via_host = settings.contact_uri.host; } // Contact URI else { settings.contact_uri = new URI('sip', Utils.createRandomToken(8), settings.via_host, null, {transport: 'ws'}); } this.contact = { pub_gruu: null, temp_gruu: null, uri: settings.contact_uri, toString: function(options) { options = options || {}; var anonymous = options.anonymous || null, outbound = options.outbound || null, contact = '<'; if (anonymous) { contact += this.temp_gruu || 'sip:[email protected];transport=ws'; } else { contact += this.pub_gruu || this.uri.toString(); } if (outbound && (anonymous ? !this.temp_gruu : !this.pub_gruu)) { contact += ';ob'; } contact += '>'; return contact; } }; // Fill the value of the configuration_skeleton for(parameter in settings) { UA.configuration_skeleton[parameter].value = settings[parameter]; } Object.defineProperties(this.configuration, UA.configuration_skeleton); // Clean UA.configuration_skeleton for(parameter in settings) { UA.configuration_skeleton[parameter].value = ''; } debug('configuration parameters after validation:'); for(parameter in settings) { switch(parameter) { case 'uri': case 'registrar_server': debug('- ' + parameter + ': ' + settings[parameter]); break; case 'password': case 'ha1': debug('- ' + parameter + ': ' + 'NOT SHOWN'); break; default: debug('- ' + parameter + ': ' + JSON.stringify(settings[parameter])); } } return; }; /** * Configuration Object skeleton. */ UA.configuration_skeleton = (function() { var idx, parameter, writable, skeleton = {}, parameters = [ // Internal parameters 'jssip_id', 'hostport_params', // Mandatory user configurable parameters 'uri', // Optional user configurable parameters 'authorization_user', 'contact_uri', 'display_name', 'instance_id', 'no_answer_timeout', // 30 seconds 'session_timers', // true 'password', 'realm', 'ha1', 'register_expires', // 600 seconds 'registrar_server', 'sockets', 'use_preloaded_route', // Post-configuration generated parameters 'via_core_value', 'via_host' ]; var writable_parameters = [ 'password', 'realm', 'ha1', 'display_name' ]; for(idx in parameters) { parameter = parameters[idx]; if (writable_parameters.indexOf(parameter) !== -1) { writable = true; } else { writable = false; } skeleton[parameter] = { value: '', writable: writable, configurable: false }; } skeleton.register = { value: '', writable: true, configurable: false }; return skeleton; }()); /** * Configuration checker. */ UA.configuration_check = { mandatory: { uri: function(uri) { var parsed; if (!/^sip:/i.test(uri)) { uri = JsSIP_C.SIP + ':' + uri; } parsed = URI.parse(uri); if(!parsed) { return; } else if(!parsed.user) { return; } else { return parsed; } } }, optional: { authorization_user: function(authorization_user) { if(Grammar.parse('"'+ authorization_user +'"', 'quoted_string') === -1) { return; } else { return authorization_user; } }, connection_recovery_max_interval: function(connection_recovery_max_interval) { var value; if(Utils.isDecimal(connection_recovery_max_interval)) { value = Number(connection_recovery_max_interval); if(value > 0) { return value; } } }, connection_recovery_min_interval: function(connection_recovery_min_interval) { var value; if(Utils.isDecimal(connection_recovery_min_interval)) { value = Number(connection_recovery_min_interval); if(value > 0) { return value; } } }, contact_uri: function(contact_uri) { if (typeof contact_uri === 'string') { var uri = Grammar.parse(contact_uri,'SIP_URI'); if (uri !== -1) { return uri; } } }, display_name: function(display_name) { if (Grammar.parse('"' + display_name + '"', 'display_name') === -1) { return; } else { return display_name; } }, instance_id: function(instance_id) { if ((/^uuid:/i.test(instance_id))) { instance_id = instance_id.substr(5); } if(Grammar.parse(instance_id, 'uuid') === -1) { return; } else { return instance_id; } }, no_answer_timeout: function(no_answer_timeout) { var value; if (Utils.isDecimal(no_answer_timeout)) { value = Number(no_answer_timeout); if (value > 0) { return value; } } }, session_timers: function(session_timers) { if (typeof session_timers === 'boolean') { return session_timers; } }, password: function(password) { return String(password); }, realm: function(realm) { return String(realm); }, ha1: function(ha1) { return String(ha1); }, register: function(register) { if (typeof register === 'boolean') { return register; } }, register_expires: function(register_expires) { var value; if (Utils.isDecimal(register_expires)) { value = Number(register_expires); if (value > 0) { return value; } } }, registrar_server: function(registrar_server) { var parsed; if (!/^sip:/i.test(registrar_server)) { registrar_server = JsSIP_C.SIP + ':' + registrar_server; } parsed = URI.parse(registrar_server); if(!parsed) { return; } else if(parsed.user) { return; } else { return parsed; } }, sockets: function(sockets) { var idx, length; /* Allow defining sockets parameter as: * Socket: socket * Array of Socket: [socket1, socket2] * Array of Objects: [{socket: socket1, weight:1}, {socket: Socket2, weight:0}] * Array of Objects and Socket: [{socket: socket1}, socket2] */ if (Socket.isSocket(sockets)) { sockets = [{socket: sockets}]; } else if (Array.isArray(sockets) && sockets.length) { length = sockets.length; for (idx = 0; idx < length; idx++) { if (Socket.isSocket(sockets[idx])) { sockets[idx] = {socket: sockets[idx]}; } } } else { return; } return sockets; }, use_preloaded_route: function(use_preloaded_route) { if (typeof use_preloaded_route === 'boolean') { return use_preloaded_route; } } } }; /** * Transport event handlers */ // Transport connecting event function onTransportConnecting(data) { this.emit('connecting', data); } // Transport connected event. function onTransportConnect(data) { if(this.status === C.STATUS_USER_CLOSED) { return; } this.status = C.STATUS_READY; this.error = null; this.emit('connected', data); if(this.dynConfiguration.register) { this._registrator.register(); } } // Transport disconnected event. function onTransportDisconnect(data) { // Run _onTransportError_ callback on every client transaction using _transport_ var type, idx, length, client_transactions = ['nict', 'ict', 'nist', 'ist']; length = client_transactions.length; for (type = 0; type < length; type++) { for(idx in this.transactions[client_transactions[type]]) { this.transactions[client_transactions[type]][idx].onTransportError(); } } this.emit('disconnected', data); // Call registrator _onTransportClosed_ this._registrator.onTransportClosed(); if (this.status !== C.STATUS_USER_CLOSED) { this.status = C.STATUS_NOT_READY; this.error = C.NETWORK_ERROR; } } // Transport data event function onTransportData(data) { var transaction, transport = data.transport, message = data.message; message = Parser.parseMessage(message, this); if (! message) { return; } if (this.status === UA.C.STATUS_USER_CLOSED && message instanceof SIPMessage.IncomingRequest) { return; } // Do some sanity check if(! sanityCheck(message, this, transport)) { return; } if(message instanceof SIPMessage.IncomingRequest) { message.transport = transport; this.receiveRequest(message); } else if(message instanceof SIPMessage.IncomingResponse) { /* Unike stated in 18.1.2, if a response does not match * any transaction, it is discarded here and no passed to the core * in order to be discarded there. */ switch(message.method) { case JsSIP_C.INVITE: transaction = this.transactions.ict[message.via_branch]; if(transaction) { transaction.receiveResponse(message); } break; case JsSIP_C.ACK: // Just in case ;-) break; default: transaction = this.transactions.nict[message.via_branch]; if(transaction) { transaction.receiveResponse(message); } break; } } } },{"./Constants":1,"./Exceptions":5,"./Grammar":6,"./Message":8,"./Parser":10,"./RTCSession":11,"./Registrator":16,"./SIPMessage":18,"./Socket":19,"./Transactions":21,"./Transport":22,"./URI":24,"./Utils":25,"./sanityCheck":27,"debug":34,"events":28,"util":32}],24:[function(require,module,exports){ module.exports = URI; /** * Dependencies. */ var JsSIP_C = require('./Constants'); var Utils = require('./Utils'); var Grammar = require('./Grammar'); /** * -param {String} [scheme] * -param {String} [user] * -param {String} host * -param {String} [port] * -param {Object} [parameters] * -param {Object} [headers] * */ function URI(scheme, user, host, port, parameters, headers) { var param, header; // Checks if(!host) { throw new TypeError('missing or invalid "host" parameter'); } // Initialize parameters scheme = scheme || JsSIP_C.SIP; this.parameters = {}; this.headers = {}; for (param in parameters) { this.setParam(param, parameters[param]); } for (header in headers) { this.setHeader(header, headers[header]); } Object.defineProperties(this, { scheme: { get: function(){ return scheme; }, set: function(value){ scheme = value.toLowerCase(); } }, user: { get: function(){ return user; }, set: function(value){ user = value; } }, host: { get: function(){ return host; }, set: function(value){ host = value.toLowerCase(); } }, port: { get: function(){ return port; }, set: function(value){ port = value === 0 ? value : (parseInt(value,10) || null); } } }); } URI.prototype = { setParam: function(key, value) { if(key) { this.parameters[key.toLowerCase()] = (typeof value === 'undefined' || value === null) ? null : value.toString(); } }, getParam: function(key) { if(key) { return this.parameters[key.toLowerCase()]; } }, hasParam: function(key) { if(key) { return (this.parameters.hasOwnProperty(key.toLowerCase()) && true) || false; } }, deleteParam: function(parameter) { var value; parameter = parameter.toLowerCase(); if (this.parameters.hasOwnProperty(parameter)) { value = this.parameters[parameter]; delete this.parameters[parameter]; return value; } }, clearParams: function() { this.parameters = {}; }, setHeader: function(name, value) { this.headers[Utils.headerize(name)] = (Array.isArray(value)) ? value : [value]; }, getHeader: function(name) { if(name) { return this.headers[Utils.headerize(name)]; } }, hasHeader: function(name) { if(name) { return (this.headers.hasOwnProperty(Utils.headerize(name)) && true) || false; } }, deleteHeader: function(header) { var value; header = Utils.headerize(header); if(this.headers.hasOwnProperty(header)) { value = this.headers[header]; delete this.headers[header]; return value; } }, clearHeaders: function() { this.headers = {}; }, clone: function() { return new URI( this.scheme, this.user, this.host, this.port, JSON.parse(JSON.stringify(this.parameters)), JSON.parse(JSON.stringify(this.headers))); }, toString: function(){ var header, parameter, idx, uri, headers = []; uri = this.scheme + ':'; if (this.user) { uri += Utils.escapeUser(this.user) + '@'; } uri += this.host; if (this.port || this.port === 0) { uri += ':' + this.port; } for (parameter in this.parameters) { uri += ';' + parameter; if (this.parameters[parameter] !== null) { uri += '='+ this.parameters[parameter]; } } for(header in this.headers) { for(idx = 0; idx < this.headers[header].length; idx++) { headers.push(header + '=' + this.headers[header][idx]); } } if (headers.length > 0) { uri += '?' + headers.join('&'); } return uri; }, toAor: function(show_port){ var aor; aor = this.scheme + ':'; if (this.user) { aor += Utils.escapeUser(this.user) + '@'; } aor += this.host; if (show_port && (this.port || this.port === 0)) { aor += ':' + this.port; } return aor; } }; /** * Parse the given string and returns a JsSIP.URI instance or undefined if * it is an invalid URI. */ URI.parse = function(uri) { uri = Grammar.parse(uri,'SIP_URI'); if (uri !== -1) { return uri; } else { return undefined; } }; },{"./Constants":1,"./Grammar":6,"./Utils":25}],25:[function(require,module,exports){ var Utils = {}; module.exports = Utils; /** * Dependencies. */ var JsSIP_C = require('./Constants'); var URI = require('./URI'); var Grammar = require('./Grammar'); Utils.str_utf8_length = function(string) { return unescape(encodeURIComponent(string)).length; }; Utils.isFunction = function(fn) { if (fn !== undefined) { return (Object.prototype.toString.call(fn) === '[object Function]')? true : false; } else { return false; } }; Utils.isString = function(str) { if (str !== undefined) { return (Object.prototype.toString.call(str) === '[object String]')? true : false; } else { return false; } }; Utils.isDecimal = function(num) { return !isNaN(num) && (parseFloat(num) === parseInt(num,10)); }; Utils.isEmpty = function(value) { if (value === null || value === '' || value === undefined || (Array.isArray(value) && value.length === 0) || (typeof(value) === 'number' && isNaN(value))) { return true; } }; Utils.hasMethods = function(obj /*, method list as strings */){ var i = 1, methodName; while((methodName = arguments[i++])){ if(this.isFunction(obj[methodName])) { return false; } } return true; }; Utils.createRandomToken = function(size, base) { var i, r, token = ''; base = base || 32; for( i=0; i < size; i++ ) { r = Math.random() * base|0; token += r.toString(base); } return token; }; Utils.newTag = function() { return Utils.createRandomToken(10); }; // http://stackoverflow.com/users/109538/broofa Utils.newUUID = function() { var UUID = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8); return v.toString(16); }); return UUID; }; Utils.hostType = function(host) { if (!host) { return; } else { host = Grammar.parse(host,'host'); if (host !== -1) { return host.host_type; } } }; /** * Normalize SIP URI. * NOTE: It does not allow a SIP URI without username. * Accepts 'sip', 'sips' and 'tel' URIs and convert them into 'sip'. * Detects the domain part (if given) and properly hex-escapes the user portion. * If the user portion has only 'tel' number symbols the user portion is clean of 'tel' visual separators. */ Utils.normalizeTarget = function(target, domain) { var uri, target_array, target_user, target_domain; // If no target is given then raise an error. if (!target) { return; // If a URI instance is given then return it. } else if (target instanceof URI) { return target; // If a string is given split it by '@': // - Last fragment is the desired domain. // - Otherwise append the given domain argument. } else if (typeof target === 'string') { target_array = target.split('@'); switch(target_array.length) { case 1: if (!domain) { return; } target_user = target; target_domain = domain; break; case 2: target_user = target_array[0]; target_domain = target_array[1]; break; default: target_user = target_array.slice(0, target_array.length-1).join('@'); target_domain = target_array[target_array.length-1]; } // Remove the URI scheme (if present). target_user = target_user.replace(/^(sips?|tel):/i, ''); // Remove 'tel' visual separators if the user portion just contains 'tel' number symbols. if (/^[\-\.\(\)]*\+?[0-9\-\.\(\)]+$/.test(target_user)) { target_user = target_user.replace(/[\-\.\(\)]/g, ''); } // Build the complete SIP URI. target = JsSIP_C.SIP + ':' + Utils.escapeUser(target_user) + '@' + target_domain; // Finally parse the resulting URI. if ((uri = URI.parse(target))) { return uri; } else { return; } } else { return; } }; /** * Hex-escape a SIP URI user. */ Utils.escapeUser = function(user) { // Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F). return encodeURIComponent(decodeURIComponent(user)).replace(/%3A/ig, ':').replace(/%2B/ig, '+').replace(/%3F/ig, '?').replace(/%2F/ig, '/'); }; Utils.headerize = function(string) { var exceptions = { 'Call-Id': 'Call-ID', 'Cseq': 'CSeq', 'Www-Authenticate': 'WWW-Authenticate' }, name = string.toLowerCase().replace(/_/g,'-').split('-'), hname = '', parts = name.length, part; for (part = 0; part < parts; part++) { if (part !== 0) { hname +='-'; } hname += name[part].charAt(0).toUpperCase()+name[part].substring(1); } if (exceptions[hname]) { hname = exceptions[hname]; } return hname; }; Utils.sipErrorCause = function(status_code) { var cause; for (cause in JsSIP_C.SIP_ERROR_CAUSES) { if (JsSIP_C.SIP_ERROR_CAUSES[cause].indexOf(status_code) !== -1) { return JsSIP_C.causes[cause]; } } return JsSIP_C.causes.SIP_FAILURE_CODE; }; /** * Generate a random Test-Net IP (http://tools.ietf.org/html/rfc5735) */ Utils.getRandomTestNetIP = function() { function getOctet(from,to) { return Math.floor(Math.random()*(to-from+1)+from); } return '192.0.2.' + getOctet(1, 254); }; // MD5 (Message-Digest Algorithm) http://www.webtoolkit.info Utils.calculateMD5 = function(string) { 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 doF(x,y,z) { return (x & y) | ((~x) & z); } function doG(x,y,z) { return (x & z) | (y & (~z)); } function doH(x,y,z) { return (x ^ y ^ z); } function doI(x,y,z) { return (y ^ (x | (~z))); } function doFF(a,b,c,d,x,s,ac) { a = addUnsigned(a, addUnsigned(addUnsigned(doF(b, c, d), x), ac)); return addUnsigned(rotateLeft(a, s), b); } function doGG(a,b,c,d,x,s,ac) { a = addUnsigned(a, addUnsigned(addUnsigned(doG(b, c, d), x), ac)); return addUnsigned(rotateLeft(a, s), b); } function doHH(a,b,c,d,x,s,ac) { a = addUnsigned(a, addUnsigned(addUnsigned(doH(b, c, d), x), ac)); return addUnsigned(rotateLeft(a, s), b); } function doII(a,b,c,d,x,s,ac) { a = addUnsigned(a, addUnsigned(addUnsigned(doI(b, c, d), x), ac)); return addUnsigned(rotateLeft(a, s), b); } function convertToWordArray(string) { var lWordCount; var lMessageLength = string.length; var lNumberOfWords_temp1=lMessageLength + 8; var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64; var lNumberOfWords = (lNumberOfWords_temp2+1)*16; var lWordArray = new 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] | (string.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; } function utf8Encode(string) { string = string.replace(/\r\n/g, '\n'); var utftext = ''; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; } var x=[]; 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; string = utf8Encode(string); x = convertToWordArray(string); a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476; for (k=0;k<x.length;k+=16) { AA=a; BB=b; CC=c; DD=d; a=doFF(a,b,c,d,x[k+0], S11,0xD76AA478); d=doFF(d,a,b,c,x[k+1], S12,0xE8C7B756); c=doFF(c,d,a,b,x[k+2], S13,0x242070DB); b=doFF(b,c,d,a,x[k+3], S14,0xC1BDCEEE); a=doFF(a,b,c,d,x[k+4], S11,0xF57C0FAF); d=doFF(d,a,b,c,x[k+5], S12,0x4787C62A); c=doFF(c,d,a,b,x[k+6], S13,0xA8304613); b=doFF(b,c,d,a,x[k+7], S14,0xFD469501); a=doFF(a,b,c,d,x[k+8], S11,0x698098D8); d=doFF(d,a,b,c,x[k+9], S12,0x8B44F7AF); c=doFF(c,d,a,b,x[k+10],S13,0xFFFF5BB1); b=doFF(b,c,d,a,x[k+11],S14,0x895CD7BE); a=doFF(a,b,c,d,x[k+12],S11,0x6B901122); d=doFF(d,a,b,c,x[k+13],S12,0xFD987193); c=doFF(c,d,a,b,x[k+14],S13,0xA679438E); b=doFF(b,c,d,a,x[k+15],S14,0x49B40821); a=doGG(a,b,c,d,x[k+1], S21,0xF61E2562); d=doGG(d,a,b,c,x[k+6], S22,0xC040B340); c=doGG(c,d,a,b,x[k+11],S23,0x265E5A51); b=doGG(b,c,d,a,x[k+0], S24,0xE9B6C7AA); a=doGG(a,b,c,d,x[k+5], S21,0xD62F105D); d=doGG(d,a,b,c,x[k+10],S22,0x2441453); c=doGG(c,d,a,b,x[k+15],S23,0xD8A1E681); b=doGG(b,c,d,a,x[k+4], S24,0xE7D3FBC8); a=doGG(a,b,c,d,x[k+9], S21,0x21E1CDE6); d=doGG(d,a,b,c,x[k+14],S22,0xC33707D6); c=doGG(c,d,a,b,x[k+3], S23,0xF4D50D87); b=doGG(b,c,d,a,x[k+8], S24,0x455A14ED); a=doGG(a,b,c,d,x[k+13],S21,0xA9E3E905); d=doGG(d,a,b,c,x[k+2], S22,0xFCEFA3F8); c=doGG(c,d,a,b,x[k+7], S23,0x676F02D9); b=doGG(b,c,d,a,x[k+12],S24,0x8D2A4C8A); a=doHH(a,b,c,d,x[k+5], S31,0xFFFA3942); d=doHH(d,a,b,c,x[k+8], S32,0x8771F681); c=doHH(c,d,a,b,x[k+11],S33,0x6D9D6122); b=doHH(b,c,d,a,x[k+14],S34,0xFDE5380C); a=doHH(a,b,c,d,x[k+1], S31,0xA4BEEA44); d=doHH(d,a,b,c,x[k+4], S32,0x4BDECFA9); c=doHH(c,d,a,b,x[k+7], S33,0xF6BB4B60); b=doHH(b,c,d,a,x[k+10],S34,0xBEBFBC70); a=doHH(a,b,c,d,x[k+13],S31,0x289B7EC6); d=doHH(d,a,b,c,x[k+0], S32,0xEAA127FA); c=doHH(c,d,a,b,x[k+3], S33,0xD4EF3085); b=doHH(b,c,d,a,x[k+6], S34,0x4881D05); a=doHH(a,b,c,d,x[k+9], S31,0xD9D4D039); d=doHH(d,a,b,c,x[k+12],S32,0xE6DB99E5); c=doHH(c,d,a,b,x[k+15],S33,0x1FA27CF8); b=doHH(b,c,d,a,x[k+2], S34,0xC4AC5665); a=doII(a,b,c,d,x[k+0], S41,0xF4292244); d=doII(d,a,b,c,x[k+7], S42,0x432AFF97); c=doII(c,d,a,b,x[k+14],S43,0xAB9423A7); b=doII(b,c,d,a,x[k+5], S44,0xFC93A039); a=doII(a,b,c,d,x[k+12],S41,0x655B59C3); d=doII(d,a,b,c,x[k+3], S42,0x8F0CCC92); c=doII(c,d,a,b,x[k+10],S43,0xFFEFF47D); b=doII(b,c,d,a,x[k+1], S44,0x85845DD1); a=doII(a,b,c,d,x[k+8], S41,0x6FA87E4F); d=doII(d,a,b,c,x[k+15],S42,0xFE2CE6E0); c=doII(c,d,a,b,x[k+6], S43,0xA3014314); b=doII(b,c,d,a,x[k+13],S44,0x4E0811A1); a=doII(a,b,c,d,x[k+4], S41,0xF7537E82); d=doII(d,a,b,c,x[k+11],S42,0xBD3AF235); c=doII(c,d,a,b,x[k+2], S43,0x2AD7D2BB); b=doII(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); } var temp = wordToHex(a)+wordToHex(b)+wordToHex(c)+wordToHex(d); return temp.toLowerCase(); }; Utils.closeMediaStream = function(stream) { if (!stream) { return; } // Latest spec states that MediaStream has no stop() method and instead must // call stop() on every MediaStreamTrack. try { var tracks, i, len; if (stream.getTracks) { tracks = stream.getTracks(); for (i = 0, len = tracks.length; i < len; i += 1) { tracks[i].stop(); } } else { tracks = stream.getAudioTracks(); for (i = 0, len = tracks.length; i < len; i += 1) { tracks[i].stop(); } tracks = stream.getVideoTracks(); for (i = 0, len = tracks.length; i < len; i += 1) { tracks[i].stop(); } } } catch (error) { // Deprecated by the spec, but still in use. // NOTE: In Temasys IE plugin stream.stop is a callable 'object'. if (typeof stream.stop === 'function' || typeof stream.stop === 'object') { stream.stop(); } } }; },{"./Constants":1,"./Grammar":6,"./URI":24}],26:[function(require,module,exports){ module.exports = WebSocketInterface; /** * Dependencies. */ var Grammar = require('./Grammar'); var debug = require('debug')('JsSIP:WebSocketInterface'); var debugerror = require('debug')('JsSIP:ERROR:WebSocketInterface'); debugerror.log = console.warn.bind(console); function WebSocketInterface(url) { debug('new() [url:"%s"]', url); var sip_uri = null; var via_transport = null; this.ws = null; // setting the 'scheme' alters the sip_uri too (used in SIP Route header field) Object.defineProperties(this, { via_transport: { get: function() { return via_transport; }, set: function(transport) { via_transport = transport.toUpperCase(); } }, sip_uri: { get: function() { return sip_uri; }}, url: { get: function() { return url; }} }); var parsed_url = Grammar.parse(url, 'absoluteURI'); if (parsed_url === -1) { debugerror('invalid WebSocket URI: ' + url); throw new TypeError('Invalid argument: ' + url); } else if(parsed_url.scheme !== 'wss' && parsed_url.scheme !== 'ws') { debugerror('invalid WebSocket URI scheme: ' + parsed_url.scheme); throw new TypeError('Invalid argument: ' + url); } else { sip_uri = 'sip:' + parsed_url.host + (parsed_url.port ? ':' + parsed_url.port : '') + ';transport=ws'; this.via_transport = parsed_url.scheme; } } WebSocketInterface.prototype.connect = function () { debug('connect()'); if (this.isConnected()) { debug('WebSocket ' + this.url + ' is already connected'); return; } else if (this.isConnecting()) { debug('WebSocket ' + this.url + ' is connecting'); return; } if (this.ws) { this.disconnect(); } debug('connecting to WebSocket ' + this.url); try { this.ws = new WebSocket(this.url, 'sip'); this.ws.binaryType = 'arraybuffer'; this.ws.onopen = onOpen.bind(this); this.ws.onclose = onClose.bind(this); this.ws.onmessage = onMessage.bind(this); this.ws.onerror = onError.bind(this); } catch(e) { onError.call(this, e); } }; WebSocketInterface.prototype.disconnect = function() { debug('disconnect()'); if (this.ws) { // unbind websocket event callbacks this.ws.onopen = function() {}; this.ws.onclose = function() {}; this.ws.onmessage = function() {}; this.ws.onerror = function() {}; this.ws.close(); this.ws = null; } }; WebSocketInterface.prototype.send = function(message) { debug('send()'); if (this.isConnected()) { this.ws.send(message); return true; } else { debugerror('unable to send message, WebSocket is not open'); return false; } }; WebSocketInterface.prototype.isConnected = function() { return this.ws && this.ws.readyState === this.ws.OPEN; }; WebSocketInterface.prototype.isConnecting = function() { return this.ws && this.ws.readyState === this.ws.CONNECTING; }; /** * WebSocket Event Handlers */ function onOpen() { debug('WebSocket ' + this.url + ' connected'); this.onconnect(); } function onClose(e) { debug('WebSocket ' + this.url + ' closed'); if (e.wasClean === false) { debug('WebSocket abrupt disconnection'); } this.ondisconnect(e.wasClean, e.code, e.reason); } function onMessage(e) { debug('received WebSocket message'); this.ondata(e.data); } function onError(e) { debugerror('WebSocket ' + this.url + ' error: '+ e); } },{"./Grammar":6,"debug":34}],27:[function(require,module,exports){ module.exports = sanityCheck; /** * Dependencies. */ var debug = require('debug')('JsSIP:sanityCheck'); var JsSIP_C = require('./Constants'); var SIPMessage = require('./SIPMessage'); var Utils = require('./Utils'); var message, ua, transport, requests = [], responses = [], all = []; requests.push(rfc3261_8_2_2_1); requests.push(rfc3261_16_3_4); requests.push(rfc3261_18_3_request); requests.push(rfc3261_8_2_2_2); responses.push(rfc3261_8_1_3_3); responses.push(rfc3261_18_3_response); all.push(minimumHeaders); function sanityCheck(m, u, t) { var len, pass; message = m; ua = u; transport = t; len = all.length; while(len--) { pass = all[len](message); if(pass === false) { return false; } } if(message instanceof SIPMessage.IncomingRequest) { len = requests.length; while(len--) { pass = requests[len](message); if(pass === false) { return false; } } } else if(message instanceof SIPMessage.IncomingResponse) { len = responses.length; while(len--) { pass = responses[len](message); if(pass === false) { return false; } } } //Everything is OK return true; } /* * Sanity Check for incoming Messages * * Requests: * - _rfc3261_8_2_2_1_ Receive a Request with a non supported URI scheme * - _rfc3261_16_3_4_ Receive a Request already sent by us * Does not look at via sent-by but at jssip_id, which is inserted as * a prefix in all initial requests generated by the ua * - _rfc3261_18_3_request_ Body Content-Length * - _rfc3261_8_2_2_2_ Merged Requests * * Responses: * - _rfc3261_8_1_3_3_ Multiple Via headers * - _rfc3261_18_3_response_ Body Content-Length * * All: * - Minimum headers in a SIP message */ // Sanity Check functions for requests function rfc3261_8_2_2_1() { if(message.s('to').uri.scheme !== 'sip') { reply(416); return false; } } function rfc3261_16_3_4() { if(!message.to_tag) { if(message.call_id.substr(0, 5) === ua.configuration.jssip_id) { reply(482); return false; } } } function rfc3261_18_3_request() { var len = Utils.str_utf8_length(message.body), contentLength = message.getHeader('content-length'); if(len < contentLength) { reply(400); return false; } } function rfc3261_8_2_2_2() { var tr, idx, fromTag = message.from_tag, call_id = message.call_id, cseq = message.cseq; // Accept any in-dialog request. if(message.to_tag) { return; } // INVITE request. if (message.method === JsSIP_C.INVITE) { // If the branch matches the key of any IST then assume it is a retransmission // and ignore the INVITE. // TODO: we should reply the last response. if (ua.transactions.ist[message.via_branch]) { return false; } // Otherwise check whether it is a merged request. else { for(idx in ua.transactions.ist) { tr = ua.transactions.ist[idx]; if(tr.request.from_tag === fromTag && tr.request.call_id === call_id && tr.request.cseq === cseq) { reply(482); return false; } } } } // Non INVITE request. else { // If the branch matches the key of any NIST then assume it is a retransmission // and ignore the request. // TODO: we should reply the last response. if (ua.transactions.nist[message.via_branch]) { return false; } // Otherwise check whether it is a merged request. else { for(idx in ua.transactions.nist) { tr = ua.transactions.nist[idx]; if(tr.request.from_tag === fromTag && tr.request.call_id === call_id && tr.request.cseq === cseq) { reply(482); return false; } } } } } // Sanity Check functions for responses function rfc3261_8_1_3_3() { if(message.getHeaders('via').length > 1) { debug('more than one Via header field present in the response, dropping the response'); return false; } } function rfc3261_18_3_response() { var len = Utils.str_utf8_length(message.body), contentLength = message.getHeader('content-length'); if(len < contentLength) { debug('message body length is lower than the value in Content-Length header field, dropping the response'); return false; } } // Sanity Check functions for requests and responses function minimumHeaders() { var mandatoryHeaders = ['from', 'to', 'call_id', 'cseq', 'via'], idx = mandatoryHeaders.length; while(idx--) { if(!message.hasHeader(mandatoryHeaders[idx])) { debug('missing mandatory header field : ' + mandatoryHeaders[idx] + ', dropping the response'); return false; } } } // Reply function reply(status_code) { var to, response = 'SIP/2.0 ' + status_code + ' ' + JsSIP_C.REASON_PHRASE[status_code] + '\r\n', vias = message.getHeaders('via'), length = vias.length, idx = 0; for(idx; idx < length; idx++) { response += 'Via: ' + vias[idx] + '\r\n'; } to = message.getHeader('To'); if(!message.to_tag) { to += ';tag=' + Utils.newTag(); } response += 'To: ' + to + '\r\n'; response += 'From: ' + message.getHeader('From') + '\r\n'; response += 'Call-ID: ' + message.call_id + '\r\n'; response += 'CSeq: ' + message.cseq + ' ' + message.method + '\r\n'; response += '\r\n'; transport.send(response); } },{"./Constants":1,"./SIPMessage":18,"./Utils":25,"debug":34}],28:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } } else if (isObject(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else if (listeners) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.prototype.listenerCount = function(type) { if (this._events) { var evlistener = this._events[type]; if (isFunction(evlistener)) return 1; else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function(emitter, type) { return emitter.listenerCount(type); }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } },{}],29:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],30:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } },{}],31:[function(require,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } },{}],32:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(global.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = require('./support/isBuffer'); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = require('inherits'); exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./support/isBuffer":31,"_process":29,"inherits":30}],33:[function(require,module,exports){ /** * Helpers. */ var s = 1000 var m = s * 60 var h = m * 60 var d = h * 24 var y = d * 365.25 /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} options * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function (val, options) { options = options || {} var type = typeof val if (type === 'string' && val.length > 0) { return parse(val) } else if (type === 'number' && isNaN(val) === false) { return options.long ? fmtLong(val) : fmtShort(val) } throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val)) } /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str) if (str.length > 10000) { return } var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str) if (!match) { return } var n = parseFloat(match[1]) var type = (match[2] || 'ms').toLowerCase() switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y case 'days': case 'day': case 'd': return n * d case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n default: return undefined } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { if (ms >= d) { return Math.round(ms / d) + 'd' } if (ms >= h) { return Math.round(ms / h) + 'h' } if (ms >= m) { return Math.round(ms / m) + 'm' } if (ms >= s) { return Math.round(ms / s) + 's' } return ms + 'ms' } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms' } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) { return } if (ms < n * 1.5) { return Math.floor(ms / n) + ' ' + name } return Math.ceil(ms / n) + ' ' + name + 's' } },{}],34:[function(require,module,exports){ (function (process){ /** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = require('./debug'); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage(); /** * Colors. */ exports.colors = [ 'lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window && typeof window.process !== 'undefined' && window.process.type === 'renderer') { return true; } // is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document && 'WebkitAppearance' in document.documentElement.style) || // is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window && window.console && (console.firebug || (console.exception && console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || // double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ exports.formatters.j = function(v) { try { return JSON.stringify(v); } catch (err) { return '[UnexpectedJSONParseError]: ' + err.message; } }; /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return; var c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit') // the final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into var index = 0; var lastC = 0; args[0].replace(/%[a-zA-Z%]/g, function(match) { if ('%%' === match) return; index++; if ('%c' === match) { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log() { // this hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return 'object' === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (null == namespaces) { exports.storage.removeItem('debug'); } else { exports.storage.debug = namespaces; } } catch(e) {} } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { try { return exports.storage.debug; } catch(e) {} // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (typeof process !== 'undefined' && 'env' in process) { return process.env.DEBUG; } } /** * Enable namespaces listed in `localStorage.debug` initially. */ exports.enable(load()); /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { return window.localStorage; } catch (e) {} } }).call(this,require('_process')) },{"./debug":35,"_process":29}],35:[function(require,module,exports){ /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = createDebug.debug = createDebug.default = createDebug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = require('ms'); /** * The currently active debug mode names, and names to skip. */ exports.names = []; exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ exports.formatters = {}; /** * Previous log timestamp. */ var prevTime; /** * Select a color. * @param {String} namespace * @return {Number} * @api private */ function selectColor(namespace) { var hash = 0, i; for (i in namespace) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return exports.colors[Math.abs(hash) % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { function debug() { // disabled? if (!debug.enabled) return; var self = debug; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // turn the `arguments` into a proper Array var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %O args.unshift('%O'); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // apply env-specific formatting (colors, etc.) exports.formatArgs.call(self, args); var logFn = debug.log || exports.log || console.log.bind(console); logFn.apply(self, args); } debug.namespace = namespace; debug.enabled = exports.enabled(namespace); debug.useColors = exports.useColors(); debug.color = selectColor(namespace); // env-specific initialization logic for debug instances if ('function' === typeof exports.init) { exports.init(debug); } return debug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { exports.save(namespaces); var split = (namespaces || '').split(/[\s,]+/); var len = split.length; for (var i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @api public */ function disable() { exports.enable(''); } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { var i, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } },{"ms":33}],36:[function(require,module,exports){ var grammar = module.exports = { v: [{ name: 'version', reg: /^(\d*)$/ }], o: [{ //o=- 20518 0 IN IP4 203.0.113.1 // NB: sessionId will be a String in most cases because it is huge name: 'origin', reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/, names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'], format: "%s %s %d %s IP%d %s" }], // default parsing of these only (though some of these feel outdated) s: [{ name: 'name' }], i: [{ name: 'description' }], u: [{ name: 'uri' }], e: [{ name: 'email' }], p: [{ name: 'phone' }], z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly.. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly //k: [{}], // outdated thing ignored t: [{ //t=0 0 name: 'timing', reg: /^(\d*) (\d*)/, names: ['start', 'stop'], format: "%d %d" }], c: [{ //c=IN IP4 10.47.197.26 name: 'connection', reg: /^IN IP(\d) (\S*)/, names: ['version', 'ip'], format: "IN IP%d %s" }], b: [{ //b=AS:4000 push: 'bandwidth', reg: /^(TIAS|AS|CT|RR|RS):(\d*)/, names: ['type', 'limit'], format: "%s:%s" }], m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31 // NB: special - pushes to session // TODO: rtp/fmtp should be filtered by the payloads found here? reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/, names: ['type', 'port', 'protocol', 'payloads'], format: "%s %d %s %s" }], a: [ { //a=rtpmap:110 opus/48000/2 push: 'rtp', reg: /^rtpmap:(\d*) ([\w\-\.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/, names: ['payload', 'codec', 'rate', 'encoding'], format: function (o) { return (o.encoding) ? "rtpmap:%d %s/%s/%s": o.rate ? "rtpmap:%d %s/%s": "rtpmap:%d %s"; } }, { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000 //a=fmtp:111 minptime=10; useinbandfec=1 push: 'fmtp', reg: /^fmtp:(\d*) ([\S| ]*)/, names: ['payload', 'config'], format: "fmtp:%d %s" }, { //a=control:streamid=0 name: 'control', reg: /^control:(.*)/, format: "control:%s" }, { //a=rtcp:65179 IN IP4 193.84.77.194 name: 'rtcp', reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/, names: ['port', 'netType', 'ipVer', 'address'], format: function (o) { return (o.address != null) ? "rtcp:%d %s IP%d %s": "rtcp:%d"; } }, { //a=rtcp-fb:98 trr-int 100 push: 'rtcpFbTrrInt', reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/, names: ['payload', 'value'], format: "rtcp-fb:%d trr-int %d" }, { //a=rtcp-fb:98 nack rpsi push: 'rtcpFb', reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/, names: ['payload', 'type', 'subtype'], format: function (o) { return (o.subtype != null) ? "rtcp-fb:%s %s %s": "rtcp-fb:%s %s"; } }, { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset //a=extmap:1/recvonly URI-gps-string push: 'ext', reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/, names: ['value', 'uri', 'config'], // value may include "/direction" suffix format: function (o) { return (o.config != null) ? "extmap:%s %s %s": "extmap:%s %s"; } }, { //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32 push: 'crypto', reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/, names: ['id', 'suite', 'config', 'sessionConfig'], format: function (o) { return (o.sessionConfig != null) ? "crypto:%d %s %s %s": "crypto:%d %s %s"; } }, { //a=setup:actpass name: 'setup', reg: /^setup:(\w*)/, format: "setup:%s" }, { //a=mid:1 name: 'mid', reg: /^mid:([^\s]*)/, format: "mid:%s" }, { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a name: 'msid', reg: /^msid:(.*)/, format: "msid:%s" }, { //a=ptime:20 name: 'ptime', reg: /^ptime:(\d*)/, format: "ptime:%d" }, { //a=maxptime:60 name: 'maxptime', reg: /^maxptime:(\d*)/, format: "maxptime:%d" }, { //a=sendrecv name: 'direction', reg: /^(sendrecv|recvonly|sendonly|inactive)/ }, { //a=ice-lite name: 'icelite', reg: /^(ice-lite)/ }, { //a=ice-ufrag:F7gI name: 'iceUfrag', reg: /^ice-ufrag:(\S*)/, format: "ice-ufrag:%s" }, { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g name: 'icePwd', reg: /^ice-pwd:(\S*)/, format: "ice-pwd:%s" }, { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33 name: 'fingerprint', reg: /^fingerprint:(\S*) (\S*)/, names: ['type', 'hash'], format: "fingerprint:%s %s" }, { //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0 //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0 //a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0 //a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0 push:'candidates', reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/, names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation'], format: function (o) { var str = "candidate:%s %d %s %d %s %d typ %s"; str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v"; // NB: candidate has three optional chunks, so %void middles one if it's missing str += (o.tcptype != null) ? " tcptype %s" : "%v"; if (o.generation != null) { str += " generation %d"; } return str; } }, { //a=end-of-candidates (keep after the candidates line for readability) name: 'endOfCandidates', reg: /^(end-of-candidates)/ }, { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ... name: 'remoteCandidates', reg: /^remote-candidates:(.*)/, format: "remote-candidates:%s" }, { //a=ice-options:google-ice name: 'iceOptions', reg: /^ice-options:(\S*)/, format: "ice-options:%s" }, { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1 push: "ssrcs", reg: /^ssrc:(\d*) ([\w_]*):(.*)/, names: ['id', 'attribute', 'value'], format: "ssrc:%d %s:%s" }, { //a=ssrc-group:FEC 1 2 push: "ssrcGroups", reg: /^ssrc-group:(\w*) (.*)/, names: ['semantics', 'ssrcs'], format: "ssrc-group:%s %s" }, { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV name: "msidSemantic", reg: /^msid-semantic:\s?(\w*) (\S*)/, names: ['semantic', 'token'], format: "msid-semantic: %s %s" // space after ":" is not accidental }, { //a=group:BUNDLE audio video push: 'groups', reg: /^group:(\w*) (.*)/, names: ['type', 'mids'], format: "group:%s %s" }, { //a=rtcp-mux name: 'rtcpMux', reg: /^(rtcp-mux)/ }, { //a=rtcp-rsize name: 'rtcpRsize', reg: /^(rtcp-rsize)/ }, { //a=sctpmap:5000 webrtc-datachannel 1024 name: 'sctpmap', reg: /^sctpmap:([\w_\/]*) (\S*)(?: (\S*))?/, names: ['sctpmapNumber', 'app', 'maxMessageSize'], format: function (o) { return (o.maxMessageSize != null) ? "sctpmap:%s %s %s" : "sctpmap:%s %s"; } }, { // any a= that we don't understand is kepts verbatim on media.invalid push: 'invalid', names: ["value"] } ] }; // set sensible defaults to avoid polluting the grammar with boring details Object.keys(grammar).forEach(function (key) { var objs = grammar[key]; objs.forEach(function (obj) { if (!obj.reg) { obj.reg = /(.*)/; } if (!obj.format) { obj.format = "%s"; } }); }); },{}],37:[function(require,module,exports){ var parser = require('./parser'); var writer = require('./writer'); exports.write = writer; exports.parse = parser.parse; exports.parseFmtpConfig = parser.parseFmtpConfig; exports.parsePayloads = parser.parsePayloads; exports.parseRemoteCandidates = parser.parseRemoteCandidates; },{"./parser":38,"./writer":39}],38:[function(require,module,exports){ var toIntIfInt = function (v) { return String(Number(v)) === v ? Number(v) : v; }; var attachProperties = function (match, location, names, rawName) { if (rawName && !names) { location[rawName] = toIntIfInt(match[1]); } else { for (var i = 0; i < names.length; i += 1) { if (match[i+1] != null) { location[names[i]] = toIntIfInt(match[i+1]); } } } }; var parseReg = function (obj, location, content) { var needsBlank = obj.name && obj.names; if (obj.push && !location[obj.push]) { location[obj.push] = []; } else if (needsBlank && !location[obj.name]) { location[obj.name] = {}; } var keyLocation = obj.push ? {} : // blank object that will be pushed needsBlank ? location[obj.name] : location; // otherwise, named location or root attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name); if (obj.push) { location[obj.push].push(keyLocation); } }; var grammar = require('./grammar'); var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/); exports.parse = function (sdp) { var session = {} , media = [] , location = session; // points at where properties go under (one of the above) // parse lines we understand sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) { var type = l[0]; var content = l.slice(2); if (type === 'm') { media.push({rtp: [], fmtp: []}); location = media[media.length-1]; // point at latest media line } for (var j = 0; j < (grammar[type] || []).length; j += 1) { var obj = grammar[type][j]; if (obj.reg.test(content)) { return parseReg(obj, location, content); } } }); session.media = media; // link it up return session; }; var fmtpReducer = function (acc, expr) { var s = expr.split(/=(.+)/, 2); if (s.length === 2) { acc[s[0]] = toIntIfInt(s[1]); } return acc; }; exports.parseFmtpConfig = function (str) { return str.split(/\;\s?/).reduce(fmtpReducer, {}); }; exports.parsePayloads = function (str) { return str.split(' ').map(Number); }; exports.parseRemoteCandidates = function (str) { var candidates = []; var parts = str.split(' ').map(toIntIfInt); for (var i = 0; i < parts.length; i += 3) { candidates.push({ component: parts[i], ip: parts[i + 1], port: parts[i + 2] }); } return candidates; }; },{"./grammar":36}],39:[function(require,module,exports){ var grammar = require('./grammar'); // customized util.format - discards excess arguments and can void middle ones var formatRegExp = /%[sdv%]/g; var format = function (formatStr) { var i = 1; var args = arguments; var len = args.length; return formatStr.replace(formatRegExp, function (x) { if (i >= len) { return x; // missing argument } var arg = args[i]; i += 1; switch (x) { case '%%': return '%'; case '%s': return String(arg); case '%d': return Number(arg); case '%v': return ''; } }); // NB: we discard excess arguments - they are typically undefined from makeLine }; var makeLine = function (type, obj, location) { var str = obj.format instanceof Function ? (obj.format(obj.push ? location : location[obj.name])) : obj.format; var args = [type + '=' + str]; if (obj.names) { for (var i = 0; i < obj.names.length; i += 1) { var n = obj.names[i]; if (obj.name) { args.push(location[obj.name][n]); } else { // for mLine and push attributes args.push(location[obj.names[i]]); } } } else { args.push(location[obj.name]); } return format.apply(null, args); }; // RFC specified order // TODO: extend this with all the rest var defaultOuterOrder = [ 'v', 'o', 's', 'i', 'u', 'e', 'p', 'c', 'b', 't', 'r', 'z', 'a' ]; var defaultInnerOrder = ['i', 'c', 'b', 'a']; module.exports = function (session, opts) { opts = opts || {}; // ensure certain properties exist if (session.version == null) { session.version = 0; // "v=0" must be there (only defined version atm) } if (session.name == null) { session.name = " "; // "s= " must be there if no meaningful name set } session.media.forEach(function (mLine) { if (mLine.payloads == null) { mLine.payloads = ""; } }); var outerOrder = opts.outerOrder || defaultOuterOrder; var innerOrder = opts.innerOrder || defaultInnerOrder; var sdp = []; // loop through outerOrder for matching properties on session outerOrder.forEach(function (type) { grammar[type].forEach(function (obj) { if (obj.name in session && session[obj.name] != null) { sdp.push(makeLine(type, obj, session)); } else if (obj.push in session && session[obj.push] != null) { session[obj.push].forEach(function (el) { sdp.push(makeLine(type, obj, el)); }); } }); }); // then for each media line, follow the innerOrder session.media.forEach(function (mLine) { sdp.push(makeLine('m', grammar.m[0], mLine)); innerOrder.forEach(function (type) { grammar[type].forEach(function (obj) { if (obj.name in mLine && mLine[obj.name] != null) { sdp.push(makeLine(type, obj, mLine)); } else if (obj.push in mLine && mLine[obj.push] != null) { mLine[obj.push].forEach(function (el) { sdp.push(makeLine(type, obj, el)); }); } }); }); }); return sdp.join('\r\n') + '\r\n'; }; },{"./grammar":36}],40:[function(require,module,exports){ /* eslint-env node */ 'use strict'; // SDP helpers. var SDPUtils = {}; // Generate an alphanumeric identifier for cname or mids. // TODO: use UUIDs instead? https://gist.github.com/jed/982883 SDPUtils.generateIdentifier = function() { return Math.random().toString(36).substr(2, 10); }; // The RTCP CNAME used by all peerconnections from the same JS. SDPUtils.localCName = SDPUtils.generateIdentifier(); // Splits SDP into lines, dealing with both CRLF and LF. SDPUtils.splitLines = function(blob) { return blob.trim().split('\n').map(function(line) { return line.trim(); }); }; // Splits SDP into sessionpart and mediasections. Ensures CRLF. SDPUtils.splitSections = function(blob) { var parts = blob.split('\nm='); return parts.map(function(part, index) { return (index > 0 ? 'm=' + part : part).trim() + '\r\n'; }); }; // Returns lines that start with a certain prefix. SDPUtils.matchPrefix = function(blob, prefix) { return SDPUtils.splitLines(blob).filter(function(line) { return line.indexOf(prefix) === 0; }); }; // Parses an ICE candidate line. Sample input: // candidate:702786350 2 udp 41819902 8.8.8.8 60769 typ relay raddr 8.8.8.8 // rport 55996" SDPUtils.parseCandidate = function(line) { var parts; // Parse both variants. if (line.indexOf('a=candidate:') === 0) { parts = line.substring(12).split(' '); } else { parts = line.substring(10).split(' '); } var candidate = { foundation: parts[0], component: parts[1], protocol: parts[2].toLowerCase(), priority: parseInt(parts[3], 10), ip: parts[4], port: parseInt(parts[5], 10), // skip parts[6] == 'typ' type: parts[7] }; for (var i = 8; i < parts.length; i += 2) { switch (parts[i]) { case 'raddr': candidate.relatedAddress = parts[i + 1]; break; case 'rport': candidate.relatedPort = parseInt(parts[i + 1], 10); break; case 'tcptype': candidate.tcpType = parts[i + 1]; break; default: // Unknown extensions are silently ignored. break; } } return candidate; }; // Translates a candidate object into SDP candidate attribute. SDPUtils.writeCandidate = function(candidate) { var sdp = []; sdp.push(candidate.foundation); sdp.push(candidate.component); sdp.push(candidate.protocol.toUpperCase()); sdp.push(candidate.priority); sdp.push(candidate.ip); sdp.push(candidate.port); var type = candidate.type; sdp.push('typ'); sdp.push(type); if (type !== 'host' && candidate.relatedAddress && candidate.relatedPort) { sdp.push('raddr'); sdp.push(candidate.relatedAddress); // was: relAddr sdp.push('rport'); sdp.push(candidate.relatedPort); // was: relPort } if (candidate.tcpType && candidate.protocol.toLowerCase() === 'tcp') { sdp.push('tcptype'); sdp.push(candidate.tcpType); } return 'candidate:' + sdp.join(' '); }; // Parses an rtpmap line, returns RTCRtpCoddecParameters. Sample input: // a=rtpmap:111 opus/48000/2 SDPUtils.parseRtpMap = function(line) { var parts = line.substr(9).split(' '); var parsed = { payloadType: parseInt(parts.shift(), 10) // was: id }; parts = parts[0].split('/'); parsed.name = parts[0]; parsed.clockRate = parseInt(parts[1], 10); // was: clockrate // was: channels parsed.numChannels = parts.length === 3 ? parseInt(parts[2], 10) : 1; return parsed; }; // Generate an a=rtpmap line from RTCRtpCodecCapability or // RTCRtpCodecParameters. SDPUtils.writeRtpMap = function(codec) { var pt = codec.payloadType; if (codec.preferredPayloadType !== undefined) { pt = codec.preferredPayloadType; } return 'a=rtpmap:' + pt + ' ' + codec.name + '/' + codec.clockRate + (codec.numChannels !== 1 ? '/' + codec.numChannels : '') + '\r\n'; }; // Parses an a=extmap line (headerextension from RFC 5285). Sample input: // a=extmap:2 urn:ietf:params:rtp-hdrext:toffset SDPUtils.parseExtmap = function(line) { var parts = line.substr(9).split(' '); return { id: parseInt(parts[0], 10), uri: parts[1] }; }; // Generates a=extmap line from RTCRtpHeaderExtensionParameters or // RTCRtpHeaderExtension. SDPUtils.writeExtmap = function(headerExtension) { return 'a=extmap:' + (headerExtension.id || headerExtension.preferredId) + ' ' + headerExtension.uri + '\r\n'; }; // Parses an ftmp line, returns dictionary. Sample input: // a=fmtp:96 vbr=on;cng=on // Also deals with vbr=on; cng=on SDPUtils.parseFmtp = function(line) { var parsed = {}; var kv; var parts = line.substr(line.indexOf(' ') + 1).split(';'); for (var j = 0; j < parts.length; j++) { kv = parts[j].trim().split('='); parsed[kv[0].trim()] = kv[1]; } return parsed; }; // Generates an a=ftmp line from RTCRtpCodecCapability or RTCRtpCodecParameters. SDPUtils.writeFmtp = function(codec) { var line = ''; var pt = codec.payloadType; if (codec.preferredPayloadType !== undefined) { pt = codec.preferredPayloadType; } if (codec.parameters && Object.keys(codec.parameters).length) { var params = []; Object.keys(codec.parameters).forEach(function(param) { params.push(param + '=' + codec.parameters[param]); }); line += 'a=fmtp:' + pt + ' ' + params.join(';') + '\r\n'; } return line; }; // Parses an rtcp-fb line, returns RTCPRtcpFeedback object. Sample input: // a=rtcp-fb:98 nack rpsi SDPUtils.parseRtcpFb = function(line) { var parts = line.substr(line.indexOf(' ') + 1).split(' '); return { type: parts.shift(), parameter: parts.join(' ') }; }; // Generate a=rtcp-fb lines from RTCRtpCodecCapability or RTCRtpCodecParameters. SDPUtils.writeRtcpFb = function(codec) { var lines = ''; var pt = codec.payloadType; if (codec.preferredPayloadType !== undefined) { pt = codec.preferredPayloadType; } if (codec.rtcpFeedback && codec.rtcpFeedback.length) { // FIXME: special handling for trr-int? codec.rtcpFeedback.forEach(function(fb) { lines += 'a=rtcp-fb:' + pt + ' ' + fb.type + (fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') + '\r\n'; }); } return lines; }; // Parses an RFC 5576 ssrc media attribute. Sample input: // a=ssrc:3735928559 cname:something SDPUtils.parseSsrcMedia = function(line) { var sp = line.indexOf(' '); var parts = { ssrc: parseInt(line.substr(7, sp - 7), 10) }; var colon = line.indexOf(':', sp); if (colon > -1) { parts.attribute = line.substr(sp + 1, colon - sp - 1); parts.value = line.substr(colon + 1); } else { parts.attribute = line.substr(sp + 1); } return parts; }; // Extracts DTLS parameters from SDP media section or sessionpart. // FIXME: for consistency with other functions this should only // get the fingerprint line as input. See also getIceParameters. SDPUtils.getDtlsParameters = function(mediaSection, sessionpart) { var lines = SDPUtils.splitLines(mediaSection); // Search in session part, too. lines = lines.concat(SDPUtils.splitLines(sessionpart)); var fpLine = lines.filter(function(line) { return line.indexOf('a=fingerprint:') === 0; })[0].substr(14); // Note: a=setup line is ignored since we use the 'auto' role. var dtlsParameters = { role: 'auto', fingerprints: [{ algorithm: fpLine.split(' ')[0], value: fpLine.split(' ')[1] }] }; return dtlsParameters; }; // Serializes DTLS parameters to SDP. SDPUtils.writeDtlsParameters = function(params, setupType) { var sdp = 'a=setup:' + setupType + '\r\n'; params.fingerprints.forEach(function(fp) { sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\r\n'; }); return sdp; }; // Parses ICE information from SDP media section or sessionpart. // FIXME: for consistency with other functions this should only // get the ice-ufrag and ice-pwd lines as input. SDPUtils.getIceParameters = function(mediaSection, sessionpart) { var lines = SDPUtils.splitLines(mediaSection); // Search in session part, too. lines = lines.concat(SDPUtils.splitLines(sessionpart)); var iceParameters = { usernameFragment: lines.filter(function(line) { return line.indexOf('a=ice-ufrag:') === 0; })[0].substr(12), password: lines.filter(function(line) { return line.indexOf('a=ice-pwd:') === 0; })[0].substr(10) }; return iceParameters; }; // Serializes ICE parameters to SDP. SDPUtils.writeIceParameters = function(params) { return 'a=ice-ufrag:' + params.usernameFragment + '\r\n' + 'a=ice-pwd:' + params.password + '\r\n'; }; // Parses the SDP media section and returns RTCRtpParameters. SDPUtils.parseRtpParameters = function(mediaSection) { var description = { codecs: [], headerExtensions: [], fecMechanisms: [], rtcp: [] }; var lines = SDPUtils.splitLines(mediaSection); var mline = lines[0].split(' '); for (var i = 3; i < mline.length; i++) { // find all codecs from mline[3..] var pt = mline[i]; var rtpmapline = SDPUtils.matchPrefix( mediaSection, 'a=rtpmap:' + pt + ' ')[0]; if (rtpmapline) { var codec = SDPUtils.parseRtpMap(rtpmapline); var fmtps = SDPUtils.matchPrefix( mediaSection, 'a=fmtp:' + pt + ' '); // Only the first a=fmtp:<pt> is considered. codec.parameters = fmtps.length ? SDPUtils.parseFmtp(fmtps[0]) : {}; codec.rtcpFeedback = SDPUtils.matchPrefix( mediaSection, 'a=rtcp-fb:' + pt + ' ') .map(SDPUtils.parseRtcpFb); description.codecs.push(codec); // parse FEC mechanisms from rtpmap lines. switch (codec.name.toUpperCase()) { case 'RED': case 'ULPFEC': description.fecMechanisms.push(codec.name.toUpperCase()); break; default: // only RED and ULPFEC are recognized as FEC mechanisms. break; } } } SDPUtils.matchPrefix(mediaSection, 'a=extmap:').forEach(function(line) { description.headerExtensions.push(SDPUtils.parseExtmap(line)); }); // FIXME: parse rtcp. return description; }; // Generates parts of the SDP media section describing the capabilities / // parameters. SDPUtils.writeRtpDescription = function(kind, caps) { var sdp = ''; // Build the mline. sdp += 'm=' + kind + ' '; sdp += caps.codecs.length > 0 ? '9' : '0'; // reject if no codecs. sdp += ' UDP/TLS/RTP/SAVPF '; sdp += caps.codecs.map(function(codec) { if (codec.preferredPayloadType !== undefined) { return codec.preferredPayloadType; } return codec.payloadType; }).join(' ') + '\r\n'; sdp += 'c=IN IP4 0.0.0.0\r\n'; sdp += 'a=rtcp:9 IN IP4 0.0.0.0\r\n'; // Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb. caps.codecs.forEach(function(codec) { sdp += SDPUtils.writeRtpMap(codec); sdp += SDPUtils.writeFmtp(codec); sdp += SDPUtils.writeRtcpFb(codec); }); sdp += 'a=rtcp-mux\r\n'; caps.headerExtensions.forEach(function(extension) { sdp += SDPUtils.writeExtmap(extension); }); // FIXME: write fecMechanisms. return sdp; }; // Parses the SDP media section and returns an array of // RTCRtpEncodingParameters. SDPUtils.parseRtpEncodingParameters = function(mediaSection) { var encodingParameters = []; var description = SDPUtils.parseRtpParameters(mediaSection); var hasRed = description.fecMechanisms.indexOf('RED') !== -1; var hasUlpfec = description.fecMechanisms.indexOf('ULPFEC') !== -1; // filter a=ssrc:... cname:, ignore PlanB-msid var ssrcs = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:') .map(function(line) { return SDPUtils.parseSsrcMedia(line); }) .filter(function(parts) { return parts.attribute === 'cname'; }); var primarySsrc = ssrcs.length > 0 && ssrcs[0].ssrc; var secondarySsrc; var flows = SDPUtils.matchPrefix(mediaSection, 'a=ssrc-group:FID') .map(function(line) { var parts = line.split(' '); parts.shift(); return parts.map(function(part) { return parseInt(part, 10); }); }); if (flows.length > 0 && flows[0].length > 1 && flows[0][0] === primarySsrc) { secondarySsrc = flows[0][1]; } description.codecs.forEach(function(codec) { if (codec.name.toUpperCase() === 'RTX' && codec.parameters.apt) { var encParam = { ssrc: primarySsrc, codecPayloadType: parseInt(codec.parameters.apt, 10), rtx: { payloadType: codec.payloadType, ssrc: secondarySsrc } }; encodingParameters.push(encParam); if (hasRed) { encParam = JSON.parse(JSON.stringify(encParam)); encParam.fec = { ssrc: secondarySsrc, mechanism: hasUlpfec ? 'red+ulpfec' : 'red' }; encodingParameters.push(encParam); } } }); if (encodingParameters.length === 0 && primarySsrc) { encodingParameters.push({ ssrc: primarySsrc }); } // we support both b=AS and b=TIAS but interpret AS as TIAS. var bandwidth = SDPUtils.matchPrefix(mediaSection, 'b='); if (bandwidth.length) { if (bandwidth[0].indexOf('b=TIAS:') === 0) { bandwidth = parseInt(bandwidth[0].substr(7), 10); } else if (bandwidth[0].indexOf('b=AS:') === 0) { bandwidth = parseInt(bandwidth[0].substr(5), 10); } encodingParameters.forEach(function(params) { params.maxBitrate = bandwidth; }); } return encodingParameters; }; SDPUtils.writeSessionBoilerplate = function() { // FIXME: sess-id should be an NTP timestamp. return 'v=0\r\n' + 'o=thisisadapterortc 8169639915646943137 2 IN IP4 127.0.0.1\r\n' + 's=-\r\n' + 't=0 0\r\n'; }; SDPUtils.writeMediaSection = function(transceiver, caps, type, stream) { var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps); // Map ICE parameters (ufrag, pwd) to SDP. sdp += SDPUtils.writeIceParameters( transceiver.iceGatherer.getLocalParameters()); // Map DTLS parameters to SDP. sdp += SDPUtils.writeDtlsParameters( transceiver.dtlsTransport.getLocalParameters(), type === 'offer' ? 'actpass' : 'active'); sdp += 'a=mid:' + transceiver.mid + '\r\n'; if (transceiver.rtpSender && transceiver.rtpReceiver) { sdp += 'a=sendrecv\r\n'; } else if (transceiver.rtpSender) { sdp += 'a=sendonly\r\n'; } else if (transceiver.rtpReceiver) { sdp += 'a=recvonly\r\n'; } else { sdp += 'a=inactive\r\n'; } // FIXME: for RTX there might be multiple SSRCs. Not implemented in Edge yet. if (transceiver.rtpSender) { var msid = 'msid:' + stream.id + ' ' + transceiver.rtpSender.track.id + '\r\n'; sdp += 'a=' + msid; sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc + ' ' + msid; } // FIXME: this should be written by writeRtpDescription. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc + ' cname:' + SDPUtils.localCName + '\r\n'; return sdp; }; // Gets the direction from the mediaSection or the sessionpart. SDPUtils.getDirection = function(mediaSection, sessionpart) { // Look for sendrecv, sendonly, recvonly, inactive, default to sendrecv. var lines = SDPUtils.splitLines(mediaSection); for (var i = 0; i < lines.length; i++) { switch (lines[i]) { case 'a=sendrecv': case 'a=sendonly': case 'a=recvonly': case 'a=inactive': return lines[i].substr(2); default: // FIXME: What should happen here? } } if (sessionpart) { return SDPUtils.getDirection(sessionpart); } return 'sendrecv'; }; // Expose public methods. module.exports = SDPUtils; },{}],41:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; // Shimming starts here. (function() { // Utils. var logging = require('./utils').log; var browserDetails = require('./utils').browserDetails; // Export to the adapter global object visible in the browser. module.exports.browserDetails = browserDetails; module.exports.extractVersion = require('./utils').extractVersion; module.exports.disableLog = require('./utils').disableLog; // Uncomment the line below if you want logging to occur, including logging // for the switch statement below. Can also be turned on in the browser via // adapter.disableLog(false), but then logging from the switch statement below // will not appear. // require('./utils').disableLog(false); // Browser shims. var chromeShim = require('./chrome/chrome_shim') || null; var edgeShim = require('./edge/edge_shim') || null; var firefoxShim = require('./firefox/firefox_shim') || null; var safariShim = require('./safari/safari_shim') || null; // Shim browser if found. switch (browserDetails.browser) { case 'opera': // fallthrough as it uses chrome shims case 'chrome': if (!chromeShim || !chromeShim.shimPeerConnection) { logging('Chrome shim is not included in this adapter release.'); return; } logging('adapter.js shimming chrome.'); // Export to the adapter global object visible in the browser. module.exports.browserShim = chromeShim; chromeShim.shimGetUserMedia(); chromeShim.shimMediaStream(); chromeShim.shimSourceObject(); chromeShim.shimPeerConnection(); chromeShim.shimOnTrack(); break; case 'firefox': if (!firefoxShim || !firefoxShim.shimPeerConnection) { logging('Firefox shim is not included in this adapter release.'); return; } logging('adapter.js shimming firefox.'); // Export to the adapter global object visible in the browser. module.exports.browserShim = firefoxShim; firefoxShim.shimGetUserMedia(); firefoxShim.shimSourceObject(); firefoxShim.shimPeerConnection(); firefoxShim.shimOnTrack(); break; case 'edge': if (!edgeShim || !edgeShim.shimPeerConnection) { logging('MS edge shim is not included in this adapter release.'); return; } logging('adapter.js shimming edge.'); // Export to the adapter global object visible in the browser. module.exports.browserShim = edgeShim; edgeShim.shimGetUserMedia(); edgeShim.shimPeerConnection(); break; case 'safari': if (!safariShim) { logging('Safari shim is not included in this adapter release.'); return; } logging('adapter.js shimming safari.'); // Export to the adapter global object visible in the browser. module.exports.browserShim = safariShim; safariShim.shimGetUserMedia(); break; default: logging('Unsupported browser!'); } })(); },{"./chrome/chrome_shim":42,"./edge/edge_shim":44,"./firefox/firefox_shim":46,"./safari/safari_shim":48,"./utils":49}],42:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var logging = require('../utils.js').log; var browserDetails = require('../utils.js').browserDetails; var chromeShim = { shimMediaStream: function() { window.MediaStream = window.MediaStream || window.webkitMediaStream; }, shimOnTrack: function() { if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in window.RTCPeerConnection.prototype)) { Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', { get: function() { return this._ontrack; }, set: function(f) { var self = this; if (this._ontrack) { this.removeEventListener('track', this._ontrack); this.removeEventListener('addstream', this._ontrackpoly); } this.addEventListener('track', this._ontrack = f); this.addEventListener('addstream', this._ontrackpoly = function(e) { // onaddstream does not fire when a track is added to an existing // stream. But stream.onaddtrack is implemented so we use that. e.stream.addEventListener('addtrack', function(te) { var event = new Event('track'); event.track = te.track; event.receiver = {track: te.track}; event.streams = [e.stream]; self.dispatchEvent(event); }); e.stream.getTracks().forEach(function(track) { var event = new Event('track'); event.track = track; event.receiver = {track: track}; event.streams = [e.stream]; this.dispatchEvent(event); }.bind(this)); }.bind(this)); } }); } }, shimSourceObject: function() { if (typeof window === 'object') { if (window.HTMLMediaElement && !('srcObject' in window.HTMLMediaElement.prototype)) { // Shim the srcObject property, once, when HTMLMediaElement is found. Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', { get: function() { return this._srcObject; }, set: function(stream) { var self = this; // Use _srcObject as a private property for this shim this._srcObject = stream; if (this.src) { URL.revokeObjectURL(this.src); } if (!stream) { this.src = ''; return; } this.src = URL.createObjectURL(stream); // We need to recreate the blob url when a track is added or // removed. Doing it manually since we want to avoid a recursion. stream.addEventListener('addtrack', function() { if (self.src) { URL.revokeObjectURL(self.src); } self.src = URL.createObjectURL(stream); }); stream.addEventListener('removetrack', function() { if (self.src) { URL.revokeObjectURL(self.src); } self.src = URL.createObjectURL(stream); }); } }); } } }, shimPeerConnection: function() { // The RTCPeerConnection object. window.RTCPeerConnection = function(pcConfig, pcConstraints) { // Translate iceTransportPolicy to iceTransports, // see https://code.google.com/p/webrtc/issues/detail?id=4869 logging('PeerConnection'); if (pcConfig && pcConfig.iceTransportPolicy) { pcConfig.iceTransports = pcConfig.iceTransportPolicy; } var pc = new webkitRTCPeerConnection(pcConfig, pcConstraints); var origGetStats = pc.getStats.bind(pc); pc.getStats = function(selector, successCallback, errorCallback) { var self = this; var args = arguments; // If selector is a function then we are in the old style stats so just // pass back the original getStats format to avoid breaking old users. if (arguments.length > 0 && typeof selector === 'function') { return origGetStats(selector, successCallback); } var fixChromeStats_ = function(response) { var standardReport = {}; var reports = response.result(); reports.forEach(function(report) { var standardStats = { id: report.id, timestamp: report.timestamp, type: report.type }; report.names().forEach(function(name) { standardStats[name] = report.stat(name); }); standardReport[standardStats.id] = standardStats; }); return standardReport; }; // shim getStats with maplike support var makeMapStats = function(stats, legacyStats) { var map = new Map(Object.keys(stats).map(function(key) { return[key, stats[key]]; })); legacyStats = legacyStats || stats; Object.keys(legacyStats).forEach(function(key) { map[key] = legacyStats[key]; }); return map; }; if (arguments.length >= 2) { var successCallbackWrapper_ = function(response) { args[1](makeMapStats(fixChromeStats_(response))); }; return origGetStats.apply(this, [successCallbackWrapper_, arguments[0]]); } // promise-support return new Promise(function(resolve, reject) { if (args.length === 1 && typeof selector === 'object') { origGetStats.apply(self, [ function(response) { resolve(makeMapStats(fixChromeStats_(response))); }, reject]); } else { // Preserve legacy chrome stats only on legacy access of stats obj origGetStats.apply(self, [ function(response) { resolve(makeMapStats(fixChromeStats_(response), response.result())); }, reject]); } }).then(successCallback, errorCallback); }; return pc; }; window.RTCPeerConnection.prototype = webkitRTCPeerConnection.prototype; // wrap static methods. Currently just generateCertificate. if (webkitRTCPeerConnection.generateCertificate) { Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', { get: function() { return webkitRTCPeerConnection.generateCertificate; } }); } ['createOffer', 'createAnswer'].forEach(function(method) { var nativeMethod = webkitRTCPeerConnection.prototype[method]; webkitRTCPeerConnection.prototype[method] = function() { var self = this; if (arguments.length < 1 || (arguments.length === 1 && typeof arguments[0] === 'object')) { var opts = arguments.length === 1 ? arguments[0] : undefined; return new Promise(function(resolve, reject) { nativeMethod.apply(self, [resolve, reject, opts]); }); } return nativeMethod.apply(this, arguments); }; }); // add promise support -- natively available in Chrome 51 if (browserDetails.version < 51) { ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'] .forEach(function(method) { var nativeMethod = webkitRTCPeerConnection.prototype[method]; webkitRTCPeerConnection.prototype[method] = function() { var args = arguments; var self = this; var promise = new Promise(function(resolve, reject) { nativeMethod.apply(self, [args[0], resolve, reject]); }); if (args.length < 2) { return promise; } return promise.then(function() { args[1].apply(null, []); }, function(err) { if (args.length >= 3) { args[2].apply(null, [err]); } }); }; }); } // shim implicit creation of RTCSessionDescription/RTCIceCandidate ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'] .forEach(function(method) { var nativeMethod = webkitRTCPeerConnection.prototype[method]; webkitRTCPeerConnection.prototype[method] = function() { arguments[0] = new ((method === 'addIceCandidate') ? RTCIceCandidate : RTCSessionDescription)(arguments[0]); return nativeMethod.apply(this, arguments); }; }); // support for addIceCandidate(null or undefined) var nativeAddIceCandidate = RTCPeerConnection.prototype.addIceCandidate; RTCPeerConnection.prototype.addIceCandidate = function() { if (!arguments[0]) { if (arguments[1]) { arguments[1].apply(null); } return Promise.resolve(); } return nativeAddIceCandidate.apply(this, arguments); }; } }; // Expose public methods. module.exports = { shimMediaStream: chromeShim.shimMediaStream, shimOnTrack: chromeShim.shimOnTrack, shimSourceObject: chromeShim.shimSourceObject, shimPeerConnection: chromeShim.shimPeerConnection, shimGetUserMedia: require('./getusermedia') }; },{"../utils.js":49,"./getusermedia":43}],43:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var logging = require('../utils.js').log; // Expose public methods. module.exports = function() { var constraintsToChrome_ = function(c) { if (typeof c !== 'object' || c.mandatory || c.optional) { return c; } var cc = {}; Object.keys(c).forEach(function(key) { if (key === 'require' || key === 'advanced' || key === 'mediaSource') { return; } var r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]}; if (r.exact !== undefined && typeof r.exact === 'number') { r.min = r.max = r.exact; } var oldname_ = function(prefix, name) { if (prefix) { return prefix + name.charAt(0).toUpperCase() + name.slice(1); } return (name === 'deviceId') ? 'sourceId' : name; }; if (r.ideal !== undefined) { cc.optional = cc.optional || []; var oc = {}; if (typeof r.ideal === 'number') { oc[oldname_('min', key)] = r.ideal; cc.optional.push(oc); oc = {}; oc[oldname_('max', key)] = r.ideal; cc.optional.push(oc); } else { oc[oldname_('', key)] = r.ideal; cc.optional.push(oc); } } if (r.exact !== undefined && typeof r.exact !== 'number') { cc.mandatory = cc.mandatory || {}; cc.mandatory[oldname_('', key)] = r.exact; } else { ['min', 'max'].forEach(function(mix) { if (r[mix] !== undefined) { cc.mandatory = cc.mandatory || {}; cc.mandatory[oldname_(mix, key)] = r[mix]; } }); } }); if (c.advanced) { cc.optional = (cc.optional || []).concat(c.advanced); } return cc; }; var shimConstraints_ = function(constraints, func) { constraints = JSON.parse(JSON.stringify(constraints)); if (constraints && constraints.audio) { constraints.audio = constraintsToChrome_(constraints.audio); } if (constraints && typeof constraints.video === 'object') { // Shim facingMode for mobile, where it defaults to "user". var face = constraints.video.facingMode; face = face && ((typeof face === 'object') ? face : {ideal: face}); if ((face && (face.exact === 'user' || face.exact === 'environment' || face.ideal === 'user' || face.ideal === 'environment')) && !(navigator.mediaDevices.getSupportedConstraints && navigator.mediaDevices.getSupportedConstraints().facingMode)) { delete constraints.video.facingMode; if (face.exact === 'environment' || face.ideal === 'environment') { // Look for "back" in label, or use last cam (typically back cam). return navigator.mediaDevices.enumerateDevices() .then(function(devices) { devices = devices.filter(function(d) { return d.kind === 'videoinput'; }); var back = devices.find(function(d) { return d.label.toLowerCase().indexOf('back') !== -1; }) || (devices.length && devices[devices.length - 1]); if (back) { constraints.video.deviceId = face.exact ? {exact: back.deviceId} : {ideal: back.deviceId}; } constraints.video = constraintsToChrome_(constraints.video); logging('chrome: ' + JSON.stringify(constraints)); return func(constraints); }); } } constraints.video = constraintsToChrome_(constraints.video); } logging('chrome: ' + JSON.stringify(constraints)); return func(constraints); }; var shimError_ = function(e) { return { name: { PermissionDeniedError: 'NotAllowedError', ConstraintNotSatisfiedError: 'OverconstrainedError' }[e.name] || e.name, message: e.message, constraint: e.constraintName, toString: function() { return this.name + (this.message && ': ') + this.message; } }; }; var getUserMedia_ = function(constraints, onSuccess, onError) { shimConstraints_(constraints, function(c) { navigator.webkitGetUserMedia(c, onSuccess, function(e) { onError(shimError_(e)); }); }); }; navigator.getUserMedia = getUserMedia_; // Returns the result of getUserMedia as a Promise. var getUserMediaPromise_ = function(constraints) { return new Promise(function(resolve, reject) { navigator.getUserMedia(constraints, resolve, reject); }); }; if (!navigator.mediaDevices) { navigator.mediaDevices = { getUserMedia: getUserMediaPromise_, enumerateDevices: function() { return new Promise(function(resolve) { var kinds = {audio: 'audioinput', video: 'videoinput'}; return MediaStreamTrack.getSources(function(devices) { resolve(devices.map(function(device) { return {label: device.label, kind: kinds[device.kind], deviceId: device.id, groupId: ''}; })); }); }); } }; } // A shim for getUserMedia method on the mediaDevices object. // TODO(KaptenJansson) remove once implemented in Chrome stable. if (!navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia = function(constraints) { return getUserMediaPromise_(constraints); }; } else { // Even though Chrome 45 has navigator.mediaDevices and a getUserMedia // function which returns a Promise, it does not accept spec-style // constraints. var origGetUserMedia = navigator.mediaDevices.getUserMedia. bind(navigator.mediaDevices); navigator.mediaDevices.getUserMedia = function(cs) { return shimConstraints_(cs, function(c) { return origGetUserMedia(c).then(function(stream) { if (c.audio && !stream.getAudioTracks().length || c.video && !stream.getVideoTracks().length) { stream.getTracks().forEach(function(track) { track.stop(); }); throw new DOMException('', 'NotFoundError'); } return stream; }, function(e) { return Promise.reject(shimError_(e)); }); }); }; } // Dummy devicechange event methods. // TODO(KaptenJansson) remove once implemented in Chrome stable. if (typeof navigator.mediaDevices.addEventListener === 'undefined') { navigator.mediaDevices.addEventListener = function() { logging('Dummy mediaDevices.addEventListener called.'); }; } if (typeof navigator.mediaDevices.removeEventListener === 'undefined') { navigator.mediaDevices.removeEventListener = function() { logging('Dummy mediaDevices.removeEventListener called.'); }; } }; },{"../utils.js":49}],44:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var SDPUtils = require('sdp'); var browserDetails = require('../utils').browserDetails; var edgeShim = { shimPeerConnection: function() { if (window.RTCIceGatherer) { // ORTC defines an RTCIceCandidate object but no constructor. // Not implemented in Edge. if (!window.RTCIceCandidate) { window.RTCIceCandidate = function(args) { return args; }; } // ORTC does not have a session description object but // other browsers (i.e. Chrome) that will support both PC and ORTC // in the future might have this defined already. if (!window.RTCSessionDescription) { window.RTCSessionDescription = function(args) { return args; }; } // this adds an additional event listener to MediaStrackTrack that signals // when a tracks enabled property was changed. var origMSTEnabled = Object.getOwnPropertyDescriptor( MediaStreamTrack.prototype, 'enabled'); Object.defineProperty(MediaStreamTrack.prototype, 'enabled', { set: function(value) { origMSTEnabled.set.call(this, value); var ev = new Event('enabled'); ev.enabled = value; this.dispatchEvent(ev); } }); } window.RTCPeerConnection = function(config) { var self = this; var _eventTarget = document.createDocumentFragment(); ['addEventListener', 'removeEventListener', 'dispatchEvent'] .forEach(function(method) { self[method] = _eventTarget[method].bind(_eventTarget); }); this.onicecandidate = null; this.onaddstream = null; this.ontrack = null; this.onremovestream = null; this.onsignalingstatechange = null; this.oniceconnectionstatechange = null; this.onnegotiationneeded = null; this.ondatachannel = null; this.localStreams = []; this.remoteStreams = []; this.getLocalStreams = function() { return self.localStreams; }; this.getRemoteStreams = function() { return self.remoteStreams; }; this.localDescription = new RTCSessionDescription({ type: '', sdp: '' }); this.remoteDescription = new RTCSessionDescription({ type: '', sdp: '' }); this.signalingState = 'stable'; this.iceConnectionState = 'new'; this.iceGatheringState = 'new'; this.iceOptions = { gatherPolicy: 'all', iceServers: [] }; if (config && config.iceTransportPolicy) { switch (config.iceTransportPolicy) { case 'all': case 'relay': this.iceOptions.gatherPolicy = config.iceTransportPolicy; break; case 'none': // FIXME: remove once implementation and spec have added this. throw new TypeError('iceTransportPolicy "none" not supported'); default: // don't set iceTransportPolicy. break; } } this.usingBundle = config && config.bundlePolicy === 'max-bundle'; if (config && config.iceServers) { // Edge does not like // 1) stun: // 2) turn: that does not have all of turn:host:port?transport=udp // 3) turn: with ipv6 addresses var iceServers = JSON.parse(JSON.stringify(config.iceServers)); this.iceOptions.iceServers = iceServers.filter(function(server) { if (server && server.urls) { var urls = server.urls; if (typeof urls === 'string') { urls = [urls]; } urls = urls.filter(function(url) { return (url.indexOf('turn:') === 0 && url.indexOf('transport=udp') !== -1 && url.indexOf('turn:[') === -1) || (url.indexOf('stun:') === 0 && browserDetails.version >= 14393); })[0]; return !!urls; } return false; }); } this._config = config; // per-track iceGathers, iceTransports, dtlsTransports, rtpSenders, ... // everything that is needed to describe a SDP m-line. this.transceivers = []; // since the iceGatherer is currently created in createOffer but we // must not emit candidates until after setLocalDescription we buffer // them in this array. this._localIceCandidatesBuffer = []; }; window.RTCPeerConnection.prototype._emitBufferedCandidates = function() { var self = this; var sections = SDPUtils.splitSections(self.localDescription.sdp); // FIXME: need to apply ice candidates in a way which is async but // in-order this._localIceCandidatesBuffer.forEach(function(event) { var end = !event.candidate || Object.keys(event.candidate).length === 0; if (end) { for (var j = 1; j < sections.length; j++) { if (sections[j].indexOf('\r\na=end-of-candidates\r\n') === -1) { sections[j] += 'a=end-of-candidates\r\n'; } } } else if (event.candidate.candidate.indexOf('typ endOfCandidates') === -1) { sections[event.candidate.sdpMLineIndex + 1] += 'a=' + event.candidate.candidate + '\r\n'; } self.localDescription.sdp = sections.join(''); self.dispatchEvent(event); if (self.onicecandidate !== null) { self.onicecandidate(event); } if (!event.candidate && self.iceGatheringState !== 'complete') { var complete = self.transceivers.every(function(transceiver) { return transceiver.iceGatherer && transceiver.iceGatherer.state === 'completed'; }); if (complete) { self.iceGatheringState = 'complete'; } } }); this._localIceCandidatesBuffer = []; }; window.RTCPeerConnection.prototype.getConfiguration = function() { return this._config; }; window.RTCPeerConnection.prototype.addStream = function(stream) { // Clone is necessary for local demos mostly, attaching directly // to two different senders does not work (build 10547). var clonedStream = stream.clone(); stream.getTracks().forEach(function(track, idx) { var clonedTrack = clonedStream.getTracks()[idx]; track.addEventListener('enabled', function(event) { clonedTrack.enabled = event.enabled; }); }); this.localStreams.push(clonedStream); this._maybeFireNegotiationNeeded(); }; window.RTCPeerConnection.prototype.removeStream = function(stream) { var idx = this.localStreams.indexOf(stream); if (idx > -1) { this.localStreams.splice(idx, 1); this._maybeFireNegotiationNeeded(); } }; window.RTCPeerConnection.prototype.getSenders = function() { return this.transceivers.filter(function(transceiver) { return !!transceiver.rtpSender; }) .map(function(transceiver) { return transceiver.rtpSender; }); }; window.RTCPeerConnection.prototype.getReceivers = function() { return this.transceivers.filter(function(transceiver) { return !!transceiver.rtpReceiver; }) .map(function(transceiver) { return transceiver.rtpReceiver; }); }; // Determines the intersection of local and remote capabilities. window.RTCPeerConnection.prototype._getCommonCapabilities = function(localCapabilities, remoteCapabilities) { var commonCapabilities = { codecs: [], headerExtensions: [], fecMechanisms: [] }; localCapabilities.codecs.forEach(function(lCodec) { for (var i = 0; i < remoteCapabilities.codecs.length; i++) { var rCodec = remoteCapabilities.codecs[i]; if (lCodec.name.toLowerCase() === rCodec.name.toLowerCase() && lCodec.clockRate === rCodec.clockRate) { // number of channels is the highest common number of channels rCodec.numChannels = Math.min(lCodec.numChannels, rCodec.numChannels); // push rCodec so we reply with offerer payload type commonCapabilities.codecs.push(rCodec); // determine common feedback mechanisms rCodec.rtcpFeedback = rCodec.rtcpFeedback.filter(function(fb) { for (var j = 0; j < lCodec.rtcpFeedback.length; j++) { if (lCodec.rtcpFeedback[j].type === fb.type && lCodec.rtcpFeedback[j].parameter === fb.parameter) { return true; } } return false; }); // FIXME: also need to determine .parameters // see https://github.com/openpeer/ortc/issues/569 break; } } }); localCapabilities.headerExtensions .forEach(function(lHeaderExtension) { for (var i = 0; i < remoteCapabilities.headerExtensions.length; i++) { var rHeaderExtension = remoteCapabilities.headerExtensions[i]; if (lHeaderExtension.uri === rHeaderExtension.uri) { commonCapabilities.headerExtensions.push(rHeaderExtension); break; } } }); // FIXME: fecMechanisms return commonCapabilities; }; // Create ICE gatherer, ICE transport and DTLS transport. window.RTCPeerConnection.prototype._createIceAndDtlsTransports = function(mid, sdpMLineIndex) { var self = this; var iceGatherer = new RTCIceGatherer(self.iceOptions); var iceTransport = new RTCIceTransport(iceGatherer); iceGatherer.onlocalcandidate = function(evt) { var event = new Event('icecandidate'); event.candidate = {sdpMid: mid, sdpMLineIndex: sdpMLineIndex}; var cand = evt.candidate; var end = !cand || Object.keys(cand).length === 0; // Edge emits an empty object for RTCIceCandidateComplete‥ if (end) { // polyfill since RTCIceGatherer.state is not implemented in // Edge 10547 yet. if (iceGatherer.state === undefined) { iceGatherer.state = 'completed'; } // Emit a candidate with type endOfCandidates to make the samples // work. Edge requires addIceCandidate with this empty candidate // to start checking. The real solution is to signal // end-of-candidates to the other side when getting the null // candidate but some apps (like the samples) don't do that. event.candidate.candidate = 'candidate:1 1 udp 1 0.0.0.0 9 typ endOfCandidates'; } else { // RTCIceCandidate doesn't have a component, needs to be added cand.component = iceTransport.component === 'RTCP' ? 2 : 1; event.candidate.candidate = SDPUtils.writeCandidate(cand); } // update local description. var sections = SDPUtils.splitSections(self.localDescription.sdp); if (event.candidate.candidate.indexOf('typ endOfCandidates') === -1) { sections[event.candidate.sdpMLineIndex + 1] += 'a=' + event.candidate.candidate + '\r\n'; } else { sections[event.candidate.sdpMLineIndex + 1] += 'a=end-of-candidates\r\n'; } self.localDescription.sdp = sections.join(''); var complete = self.transceivers.every(function(transceiver) { return transceiver.iceGatherer && transceiver.iceGatherer.state === 'completed'; }); // Emit candidate if localDescription is set. // Also emits null candidate when all gatherers are complete. switch (self.iceGatheringState) { case 'new': self._localIceCandidatesBuffer.push(event); if (end && complete) { self._localIceCandidatesBuffer.push( new Event('icecandidate')); } break; case 'gathering': self._emitBufferedCandidates(); self.dispatchEvent(event); if (self.onicecandidate !== null) { self.onicecandidate(event); } if (complete) { self.dispatchEvent(new Event('icecandidate')); if (self.onicecandidate !== null) { self.onicecandidate(new Event('icecandidate')); } self.iceGatheringState = 'complete'; } break; case 'complete': // should not happen... currently! break; default: // no-op. break; } }; iceTransport.onicestatechange = function() { self._updateConnectionState(); }; var dtlsTransport = new RTCDtlsTransport(iceTransport); dtlsTransport.ondtlsstatechange = function() { self._updateConnectionState(); }; dtlsTransport.onerror = function() { // onerror does not set state to failed by itself. dtlsTransport.state = 'failed'; self._updateConnectionState(); }; return { iceGatherer: iceGatherer, iceTransport: iceTransport, dtlsTransport: dtlsTransport }; }; // Start the RTP Sender and Receiver for a transceiver. window.RTCPeerConnection.prototype._transceive = function(transceiver, send, recv) { var params = this._getCommonCapabilities(transceiver.localCapabilities, transceiver.remoteCapabilities); if (send && transceiver.rtpSender) { params.encodings = transceiver.sendEncodingParameters; params.rtcp = { cname: SDPUtils.localCName }; if (transceiver.recvEncodingParameters.length) { params.rtcp.ssrc = transceiver.recvEncodingParameters[0].ssrc; } transceiver.rtpSender.send(params); } if (recv && transceiver.rtpReceiver) { // remove RTX field in Edge 14942 if (transceiver.kind === 'video' && transceiver.recvEncodingParameters) { transceiver.recvEncodingParameters.forEach(function(p) { delete p.rtx; }); } params.encodings = transceiver.recvEncodingParameters; params.rtcp = { cname: transceiver.cname }; if (transceiver.sendEncodingParameters.length) { params.rtcp.ssrc = transceiver.sendEncodingParameters[0].ssrc; } transceiver.rtpReceiver.receive(params); } }; window.RTCPeerConnection.prototype.setLocalDescription = function(description) { var self = this; var sections; var sessionpart; if (description.type === 'offer') { // FIXME: What was the purpose of this empty if statement? // if (!this._pendingOffer) { // } else { if (this._pendingOffer) { // VERY limited support for SDP munging. Limited to: // * changing the order of codecs sections = SDPUtils.splitSections(description.sdp); sessionpart = sections.shift(); sections.forEach(function(mediaSection, sdpMLineIndex) { var caps = SDPUtils.parseRtpParameters(mediaSection); self._pendingOffer[sdpMLineIndex].localCapabilities = caps; }); this.transceivers = this._pendingOffer; delete this._pendingOffer; } } else if (description.type === 'answer') { sections = SDPUtils.splitSections(self.remoteDescription.sdp); sessionpart = sections.shift(); var isIceLite = SDPUtils.matchPrefix(sessionpart, 'a=ice-lite').length > 0; sections.forEach(function(mediaSection, sdpMLineIndex) { var transceiver = self.transceivers[sdpMLineIndex]; var iceGatherer = transceiver.iceGatherer; var iceTransport = transceiver.iceTransport; var dtlsTransport = transceiver.dtlsTransport; var localCapabilities = transceiver.localCapabilities; var remoteCapabilities = transceiver.remoteCapabilities; var rejected = mediaSection.split('\n', 1)[0] .split(' ', 2)[1] === '0'; if (!rejected && !transceiver.isDatachannel) { var remoteIceParameters = SDPUtils.getIceParameters( mediaSection, sessionpart); if (isIceLite) { var cands = SDPUtils.matchPrefix(mediaSection, 'a=candidate:') .map(function(cand) { return SDPUtils.parseCandidate(cand); }) .filter(function(cand) { return cand.component === '1'; }); // ice-lite only includes host candidates in the SDP so we can // use setRemoteCandidates (which implies an // RTCIceCandidateComplete) if (cands.length) { iceTransport.setRemoteCandidates(cands); } } var remoteDtlsParameters = SDPUtils.getDtlsParameters( mediaSection, sessionpart); if (isIceLite) { remoteDtlsParameters.role = 'server'; } if (!self.usingBundle || sdpMLineIndex === 0) { iceTransport.start(iceGatherer, remoteIceParameters, isIceLite ? 'controlling' : 'controlled'); dtlsTransport.start(remoteDtlsParameters); } // Calculate intersection of capabilities. var params = self._getCommonCapabilities(localCapabilities, remoteCapabilities); // Start the RTCRtpSender. The RTCRtpReceiver for this // transceiver has already been started in setRemoteDescription. self._transceive(transceiver, params.codecs.length > 0, false); } }); } this.localDescription = { type: description.type, sdp: description.sdp }; switch (description.type) { case 'offer': this._updateSignalingState('have-local-offer'); break; case 'answer': this._updateSignalingState('stable'); break; default: throw new TypeError('unsupported type "' + description.type + '"'); } // If a success callback was provided, emit ICE candidates after it // has been executed. Otherwise, emit callback after the Promise is // resolved. var hasCallback = arguments.length > 1 && typeof arguments[1] === 'function'; if (hasCallback) { var cb = arguments[1]; window.setTimeout(function() { cb(); if (self.iceGatheringState === 'new') { self.iceGatheringState = 'gathering'; } self._emitBufferedCandidates(); }, 0); } var p = Promise.resolve(); p.then(function() { if (!hasCallback) { if (self.iceGatheringState === 'new') { self.iceGatheringState = 'gathering'; } // Usually candidates will be emitted earlier. window.setTimeout(self._emitBufferedCandidates.bind(self), 500); } }); return p; }; window.RTCPeerConnection.prototype.setRemoteDescription = function(description) { var self = this; var stream = new MediaStream(); var receiverList = []; var sections = SDPUtils.splitSections(description.sdp); var sessionpart = sections.shift(); var isIceLite = SDPUtils.matchPrefix(sessionpart, 'a=ice-lite').length > 0; this.usingBundle = SDPUtils.matchPrefix(sessionpart, 'a=group:BUNDLE ').length > 0; sections.forEach(function(mediaSection, sdpMLineIndex) { var lines = SDPUtils.splitLines(mediaSection); var mline = lines[0].substr(2).split(' '); var kind = mline[0]; var rejected = mline[1] === '0'; var direction = SDPUtils.getDirection(mediaSection, sessionpart); var mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:'); if (mid.length) { mid = mid[0].substr(6); } else { mid = SDPUtils.generateIdentifier(); } // Reject datachannels which are not implemented yet. if (kind === 'application' && mline[2] === 'DTLS/SCTP') { self.transceivers[sdpMLineIndex] = { mid: mid, isDatachannel: true }; return; } var transceiver; var iceGatherer; var iceTransport; var dtlsTransport; var rtpSender; var rtpReceiver; var sendEncodingParameters; var recvEncodingParameters; var localCapabilities; var track; // FIXME: ensure the mediaSection has rtcp-mux set. var remoteCapabilities = SDPUtils.parseRtpParameters(mediaSection); var remoteIceParameters; var remoteDtlsParameters; if (!rejected) { remoteIceParameters = SDPUtils.getIceParameters(mediaSection, sessionpart); remoteDtlsParameters = SDPUtils.getDtlsParameters(mediaSection, sessionpart); remoteDtlsParameters.role = 'client'; } recvEncodingParameters = SDPUtils.parseRtpEncodingParameters(mediaSection); var cname; // Gets the first SSRC. Note that with RTX there might be multiple // SSRCs. var remoteSsrc = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:') .map(function(line) { return SDPUtils.parseSsrcMedia(line); }) .filter(function(obj) { return obj.attribute === 'cname'; })[0]; if (remoteSsrc) { cname = remoteSsrc.value; } var isComplete = SDPUtils.matchPrefix(mediaSection, 'a=end-of-candidates', sessionpart).length > 0; var cands = SDPUtils.matchPrefix(mediaSection, 'a=candidate:') .map(function(cand) { return SDPUtils.parseCandidate(cand); }) .filter(function(cand) { return cand.component === '1'; }); if (description.type === 'offer' && !rejected) { var transports = self.usingBundle && sdpMLineIndex > 0 ? { iceGatherer: self.transceivers[0].iceGatherer, iceTransport: self.transceivers[0].iceTransport, dtlsTransport: self.transceivers[0].dtlsTransport } : self._createIceAndDtlsTransports(mid, sdpMLineIndex); if (isComplete) { transports.iceTransport.setRemoteCandidates(cands); } localCapabilities = RTCRtpReceiver.getCapabilities(kind); // filter RTX until additional stuff needed for RTX is implemented // in adapter.js localCapabilities.codecs = localCapabilities.codecs.filter( function(codec) { return codec.name !== 'rtx'; }); sendEncodingParameters = [{ ssrc: (2 * sdpMLineIndex + 2) * 1001 }]; rtpReceiver = new RTCRtpReceiver(transports.dtlsTransport, kind); track = rtpReceiver.track; receiverList.push([track, rtpReceiver]); // FIXME: not correct when there are multiple streams but that is // not currently supported in this shim. stream.addTrack(track); // FIXME: look at direction. if (self.localStreams.length > 0 && self.localStreams[0].getTracks().length >= sdpMLineIndex) { var localTrack; if (kind === 'audio') { localTrack = self.localStreams[0].getAudioTracks()[0]; } else if (kind === 'video') { localTrack = self.localStreams[0].getVideoTracks()[0]; } if (localTrack) { rtpSender = new RTCRtpSender(localTrack, transports.dtlsTransport); } } self.transceivers[sdpMLineIndex] = { iceGatherer: transports.iceGatherer, iceTransport: transports.iceTransport, dtlsTransport: transports.dtlsTransport, localCapabilities: localCapabilities, remoteCapabilities: remoteCapabilities, rtpSender: rtpSender, rtpReceiver: rtpReceiver, kind: kind, mid: mid, cname: cname, sendEncodingParameters: sendEncodingParameters, recvEncodingParameters: recvEncodingParameters }; // Start the RTCRtpReceiver now. The RTPSender is started in // setLocalDescription. self._transceive(self.transceivers[sdpMLineIndex], false, direction === 'sendrecv' || direction === 'sendonly'); } else if (description.type === 'answer' && !rejected) { transceiver = self.transceivers[sdpMLineIndex]; iceGatherer = transceiver.iceGatherer; iceTransport = transceiver.iceTransport; dtlsTransport = transceiver.dtlsTransport; rtpSender = transceiver.rtpSender; rtpReceiver = transceiver.rtpReceiver; sendEncodingParameters = transceiver.sendEncodingParameters; localCapabilities = transceiver.localCapabilities; self.transceivers[sdpMLineIndex].recvEncodingParameters = recvEncodingParameters; self.transceivers[sdpMLineIndex].remoteCapabilities = remoteCapabilities; self.transceivers[sdpMLineIndex].cname = cname; if ((isIceLite || isComplete) && cands.length) { iceTransport.setRemoteCandidates(cands); } if (!self.usingBundle || sdpMLineIndex === 0) { iceTransport.start(iceGatherer, remoteIceParameters, 'controlling'); dtlsTransport.start(remoteDtlsParameters); } self._transceive(transceiver, direction === 'sendrecv' || direction === 'recvonly', direction === 'sendrecv' || direction === 'sendonly'); if (rtpReceiver && (direction === 'sendrecv' || direction === 'sendonly')) { track = rtpReceiver.track; receiverList.push([track, rtpReceiver]); stream.addTrack(track); } else { // FIXME: actually the receiver should be created later. delete transceiver.rtpReceiver; } } }); this.remoteDescription = { type: description.type, sdp: description.sdp }; switch (description.type) { case 'offer': this._updateSignalingState('have-remote-offer'); break; case 'answer': this._updateSignalingState('stable'); break; default: throw new TypeError('unsupported type "' + description.type + '"'); } if (stream.getTracks().length) { self.remoteStreams.push(stream); window.setTimeout(function() { var event = new Event('addstream'); event.stream = stream; self.dispatchEvent(event); if (self.onaddstream !== null) { window.setTimeout(function() { self.onaddstream(event); }, 0); } receiverList.forEach(function(item) { var track = item[0]; var receiver = item[1]; var trackEvent = new Event('track'); trackEvent.track = track; trackEvent.receiver = receiver; trackEvent.streams = [stream]; self.dispatchEvent(event); if (self.ontrack !== null) { window.setTimeout(function() { self.ontrack(trackEvent); }, 0); } }); }, 0); } if (arguments.length > 1 && typeof arguments[1] === 'function') { window.setTimeout(arguments[1], 0); } return Promise.resolve(); }; window.RTCPeerConnection.prototype.close = function() { this.transceivers.forEach(function(transceiver) { /* not yet if (transceiver.iceGatherer) { transceiver.iceGatherer.close(); } */ if (transceiver.iceTransport) { transceiver.iceTransport.stop(); } if (transceiver.dtlsTransport) { transceiver.dtlsTransport.stop(); } if (transceiver.rtpSender) { transceiver.rtpSender.stop(); } if (transceiver.rtpReceiver) { transceiver.rtpReceiver.stop(); } }); // FIXME: clean up tracks, local streams, remote streams, etc this._updateSignalingState('closed'); }; // Update the signaling state. window.RTCPeerConnection.prototype._updateSignalingState = function(newState) { this.signalingState = newState; var event = new Event('signalingstatechange'); this.dispatchEvent(event); if (this.onsignalingstatechange !== null) { this.onsignalingstatechange(event); } }; // Determine whether to fire the negotiationneeded event. window.RTCPeerConnection.prototype._maybeFireNegotiationNeeded = function() { // Fire away (for now). var event = new Event('negotiationneeded'); this.dispatchEvent(event); if (this.onnegotiationneeded !== null) { this.onnegotiationneeded(event); } }; // Update the connection state. window.RTCPeerConnection.prototype._updateConnectionState = function() { var self = this; var newState; var states = { 'new': 0, closed: 0, connecting: 0, checking: 0, connected: 0, completed: 0, failed: 0 }; this.transceivers.forEach(function(transceiver) { states[transceiver.iceTransport.state]++; states[transceiver.dtlsTransport.state]++; }); // ICETransport.completed and connected are the same for this purpose. states.connected += states.completed; newState = 'new'; if (states.failed > 0) { newState = 'failed'; } else if (states.connecting > 0 || states.checking > 0) { newState = 'connecting'; } else if (states.disconnected > 0) { newState = 'disconnected'; } else if (states.new > 0) { newState = 'new'; } else if (states.connected > 0 || states.completed > 0) { newState = 'connected'; } if (newState !== self.iceConnectionState) { self.iceConnectionState = newState; var event = new Event('iceconnectionstatechange'); this.dispatchEvent(event); if (this.oniceconnectionstatechange !== null) { this.oniceconnectionstatechange(event); } } }; window.RTCPeerConnection.prototype.createOffer = function() { var self = this; if (this._pendingOffer) { throw new Error('createOffer called while there is a pending offer.'); } var offerOptions; if (arguments.length === 1 && typeof arguments[0] !== 'function') { offerOptions = arguments[0]; } else if (arguments.length === 3) { offerOptions = arguments[2]; } var tracks = []; var numAudioTracks = 0; var numVideoTracks = 0; // Default to sendrecv. if (this.localStreams.length) { numAudioTracks = this.localStreams[0].getAudioTracks().length; numVideoTracks = this.localStreams[0].getVideoTracks().length; } // Determine number of audio and video tracks we need to send/recv. if (offerOptions) { // Reject Chrome legacy constraints. if (offerOptions.mandatory || offerOptions.optional) { throw new TypeError( 'Legacy mandatory/optional constraints not supported.'); } if (offerOptions.offerToReceiveAudio !== undefined) { numAudioTracks = offerOptions.offerToReceiveAudio; } if (offerOptions.offerToReceiveVideo !== undefined) { numVideoTracks = offerOptions.offerToReceiveVideo; } } if (this.localStreams.length) { // Push local streams. this.localStreams[0].getTracks().forEach(function(track) { tracks.push({ kind: track.kind, track: track, wantReceive: track.kind === 'audio' ? numAudioTracks > 0 : numVideoTracks > 0 }); if (track.kind === 'audio') { numAudioTracks--; } else if (track.kind === 'video') { numVideoTracks--; } }); } // Create M-lines for recvonly streams. while (numAudioTracks > 0 || numVideoTracks > 0) { if (numAudioTracks > 0) { tracks.push({ kind: 'audio', wantReceive: true }); numAudioTracks--; } if (numVideoTracks > 0) { tracks.push({ kind: 'video', wantReceive: true }); numVideoTracks--; } } var sdp = SDPUtils.writeSessionBoilerplate(); var transceivers = []; tracks.forEach(function(mline, sdpMLineIndex) { // For each track, create an ice gatherer, ice transport, // dtls transport, potentially rtpsender and rtpreceiver. var track = mline.track; var kind = mline.kind; var mid = SDPUtils.generateIdentifier(); var transports = self.usingBundle && sdpMLineIndex > 0 ? { iceGatherer: transceivers[0].iceGatherer, iceTransport: transceivers[0].iceTransport, dtlsTransport: transceivers[0].dtlsTransport } : self._createIceAndDtlsTransports(mid, sdpMLineIndex); var localCapabilities = RTCRtpSender.getCapabilities(kind); // filter RTX until additional stuff needed for RTX is implemented // in adapter.js localCapabilities.codecs = localCapabilities.codecs.filter( function(codec) { return codec.name !== 'rtx'; }); localCapabilities.codecs.forEach(function(codec) { // work around https://bugs.chromium.org/p/webrtc/issues/detail?id=6552 // by adding level-asymmetry-allowed=1 if (codec.name === 'H264' && codec.parameters['level-asymmetry-allowed'] === undefined) { codec.parameters['level-asymmetry-allowed'] = '1'; } }); var rtpSender; var rtpReceiver; // generate an ssrc now, to be used later in rtpSender.send var sendEncodingParameters = [{ ssrc: (2 * sdpMLineIndex + 1) * 1001 }]; if (track) { rtpSender = new RTCRtpSender(track, transports.dtlsTransport); } if (mline.wantReceive) { rtpReceiver = new RTCRtpReceiver(transports.dtlsTransport, kind); } transceivers[sdpMLineIndex] = { iceGatherer: transports.iceGatherer, iceTransport: transports.iceTransport, dtlsTransport: transports.dtlsTransport, localCapabilities: localCapabilities, remoteCapabilities: null, rtpSender: rtpSender, rtpReceiver: rtpReceiver, kind: kind, mid: mid, sendEncodingParameters: sendEncodingParameters, recvEncodingParameters: null }; }); if (this.usingBundle) { sdp += 'a=group:BUNDLE ' + transceivers.map(function(t) { return t.mid; }).join(' ') + '\r\n'; } tracks.forEach(function(mline, sdpMLineIndex) { var transceiver = transceivers[sdpMLineIndex]; sdp += SDPUtils.writeMediaSection(transceiver, transceiver.localCapabilities, 'offer', self.localStreams[0]); }); this._pendingOffer = transceivers; var desc = new RTCSessionDescription({ type: 'offer', sdp: sdp }); if (arguments.length && typeof arguments[0] === 'function') { window.setTimeout(arguments[0], 0, desc); } return Promise.resolve(desc); }; window.RTCPeerConnection.prototype.createAnswer = function() { var self = this; var sdp = SDPUtils.writeSessionBoilerplate(); if (this.usingBundle) { sdp += 'a=group:BUNDLE ' + this.transceivers.map(function(t) { return t.mid; }).join(' ') + '\r\n'; } this.transceivers.forEach(function(transceiver) { if (transceiver.isDatachannel) { sdp += 'm=application 0 DTLS/SCTP 5000\r\n' + 'c=IN IP4 0.0.0.0\r\n' + 'a=mid:' + transceiver.mid + '\r\n'; return; } // Calculate intersection of capabilities. var commonCapabilities = self._getCommonCapabilities( transceiver.localCapabilities, transceiver.remoteCapabilities); sdp += SDPUtils.writeMediaSection(transceiver, commonCapabilities, 'answer', self.localStreams[0]); }); var desc = new RTCSessionDescription({ type: 'answer', sdp: sdp }); if (arguments.length && typeof arguments[0] === 'function') { window.setTimeout(arguments[0], 0, desc); } return Promise.resolve(desc); }; window.RTCPeerConnection.prototype.addIceCandidate = function(candidate) { if (!candidate) { this.transceivers.forEach(function(transceiver) { transceiver.iceTransport.addRemoteCandidate({}); }); } else { var mLineIndex = candidate.sdpMLineIndex; if (candidate.sdpMid) { for (var i = 0; i < this.transceivers.length; i++) { if (this.transceivers[i].mid === candidate.sdpMid) { mLineIndex = i; break; } } } var transceiver = this.transceivers[mLineIndex]; if (transceiver) { var cand = Object.keys(candidate.candidate).length > 0 ? SDPUtils.parseCandidate(candidate.candidate) : {}; // Ignore Chrome's invalid candidates since Edge does not like them. if (cand.protocol === 'tcp' && (cand.port === 0 || cand.port === 9)) { return; } // Ignore RTCP candidates, we assume RTCP-MUX. if (cand.component !== '1') { return; } // A dirty hack to make samples work. if (cand.type === 'endOfCandidates') { cand = {}; } transceiver.iceTransport.addRemoteCandidate(cand); // update the remoteDescription. var sections = SDPUtils.splitSections(this.remoteDescription.sdp); sections[mLineIndex + 1] += (cand.type ? candidate.candidate.trim() : 'a=end-of-candidates') + '\r\n'; this.remoteDescription.sdp = sections.join(''); } } if (arguments.length > 1 && typeof arguments[1] === 'function') { window.setTimeout(arguments[1], 0); } return Promise.resolve(); }; window.RTCPeerConnection.prototype.getStats = function() { var promises = []; this.transceivers.forEach(function(transceiver) { ['rtpSender', 'rtpReceiver', 'iceGatherer', 'iceTransport', 'dtlsTransport'].forEach(function(method) { if (transceiver[method]) { promises.push(transceiver[method].getStats()); } }); }); var cb = arguments.length > 1 && typeof arguments[1] === 'function' && arguments[1]; return new Promise(function(resolve) { // shim getStats with maplike support var results = new Map(); Promise.all(promises).then(function(res) { res.forEach(function(result) { Object.keys(result).forEach(function(id) { results.set(id, result[id]); results[id] = result[id]; }); }); if (cb) { window.setTimeout(cb, 0, results); } resolve(results); }); }); }; } }; // Expose public methods. module.exports = { shimPeerConnection: edgeShim.shimPeerConnection, shimGetUserMedia: require('./getusermedia') }; },{"../utils":49,"./getusermedia":45,"sdp":40}],45:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; // Expose public methods. module.exports = function() { var shimError_ = function(e) { return { name: {PermissionDeniedError: 'NotAllowedError'}[e.name] || e.name, message: e.message, constraint: e.constraint, toString: function() { return this.name; } }; }; // getUserMedia error shim. var origGetUserMedia = navigator.mediaDevices.getUserMedia. bind(navigator.mediaDevices); navigator.mediaDevices.getUserMedia = function(c) { return origGetUserMedia(c).catch(function(e) { return Promise.reject(shimError_(e)); }); }; }; },{}],46:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var browserDetails = require('../utils').browserDetails; var firefoxShim = { shimOnTrack: function() { if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in window.RTCPeerConnection.prototype)) { Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', { get: function() { return this._ontrack; }, set: function(f) { if (this._ontrack) { this.removeEventListener('track', this._ontrack); this.removeEventListener('addstream', this._ontrackpoly); } this.addEventListener('track', this._ontrack = f); this.addEventListener('addstream', this._ontrackpoly = function(e) { e.stream.getTracks().forEach(function(track) { var event = new Event('track'); event.track = track; event.receiver = {track: track}; event.streams = [e.stream]; this.dispatchEvent(event); }.bind(this)); }.bind(this)); } }); } }, shimSourceObject: function() { // Firefox has supported mozSrcObject since FF22, unprefixed in 42. if (typeof window === 'object') { if (window.HTMLMediaElement && !('srcObject' in window.HTMLMediaElement.prototype)) { // Shim the srcObject property, once, when HTMLMediaElement is found. Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', { get: function() { return this.mozSrcObject; }, set: function(stream) { this.mozSrcObject = stream; } }); } } }, shimPeerConnection: function() { if (typeof window !== 'object' || !(window.RTCPeerConnection || window.mozRTCPeerConnection)) { return; // probably media.peerconnection.enabled=false in about:config } // The RTCPeerConnection object. if (!window.RTCPeerConnection) { window.RTCPeerConnection = function(pcConfig, pcConstraints) { if (browserDetails.version < 38) { // .urls is not supported in FF < 38. // create RTCIceServers with a single url. if (pcConfig && pcConfig.iceServers) { var newIceServers = []; for (var i = 0; i < pcConfig.iceServers.length; i++) { var server = pcConfig.iceServers[i]; if (server.hasOwnProperty('urls')) { for (var j = 0; j < server.urls.length; j++) { var newServer = { url: server.urls[j] }; if (server.urls[j].indexOf('turn') === 0) { newServer.username = server.username; newServer.credential = server.credential; } newIceServers.push(newServer); } } else { newIceServers.push(pcConfig.iceServers[i]); } } pcConfig.iceServers = newIceServers; } } return new mozRTCPeerConnection(pcConfig, pcConstraints); }; window.RTCPeerConnection.prototype = mozRTCPeerConnection.prototype; // wrap static methods. Currently just generateCertificate. if (mozRTCPeerConnection.generateCertificate) { Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', { get: function() { return mozRTCPeerConnection.generateCertificate; } }); } window.RTCSessionDescription = mozRTCSessionDescription; window.RTCIceCandidate = mozRTCIceCandidate; } // shim away need for obsolete RTCIceCandidate/RTCSessionDescription. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'] .forEach(function(method) { var nativeMethod = RTCPeerConnection.prototype[method]; RTCPeerConnection.prototype[method] = function() { arguments[0] = new ((method === 'addIceCandidate') ? RTCIceCandidate : RTCSessionDescription)(arguments[0]); return nativeMethod.apply(this, arguments); }; }); // support for addIceCandidate(null or undefined) var nativeAddIceCandidate = RTCPeerConnection.prototype.addIceCandidate; RTCPeerConnection.prototype.addIceCandidate = function() { if (!arguments[0]) { if (arguments[1]) { arguments[1].apply(null); } return Promise.resolve(); } return nativeAddIceCandidate.apply(this, arguments); }; if (browserDetails.version < 48) { // shim getStats with maplike support var makeMapStats = function(stats) { var map = new Map(); Object.keys(stats).forEach(function(key) { map.set(key, stats[key]); map[key] = stats[key]; }); return map; }; var nativeGetStats = RTCPeerConnection.prototype.getStats; RTCPeerConnection.prototype.getStats = function(selector, onSucc, onErr) { return nativeGetStats.apply(this, [selector || null]) .then(function(stats) { return makeMapStats(stats); }) .then(onSucc, onErr); }; } } }; // Expose public methods. module.exports = { shimOnTrack: firefoxShim.shimOnTrack, shimSourceObject: firefoxShim.shimSourceObject, shimPeerConnection: firefoxShim.shimPeerConnection, shimGetUserMedia: require('./getusermedia') }; },{"../utils":49,"./getusermedia":47}],47:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var logging = require('../utils').log; var browserDetails = require('../utils').browserDetails; // Expose public methods. module.exports = function() { var shimError_ = function(e) { return { name: { SecurityError: 'NotAllowedError', PermissionDeniedError: 'NotAllowedError' }[e.name] || e.name, message: { 'The operation is insecure.': 'The request is not allowed by the ' + 'user agent or the platform in the current context.' }[e.message] || e.message, constraint: e.constraint, toString: function() { return this.name + (this.message && ': ') + this.message; } }; }; // getUserMedia constraints shim. var getUserMedia_ = function(constraints, onSuccess, onError) { var constraintsToFF37_ = function(c) { if (typeof c !== 'object' || c.require) { return c; } var require = []; Object.keys(c).forEach(function(key) { if (key === 'require' || key === 'advanced' || key === 'mediaSource') { return; } var r = c[key] = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]}; if (r.min !== undefined || r.max !== undefined || r.exact !== undefined) { require.push(key); } if (r.exact !== undefined) { if (typeof r.exact === 'number') { r. min = r.max = r.exact; } else { c[key] = r.exact; } delete r.exact; } if (r.ideal !== undefined) { c.advanced = c.advanced || []; var oc = {}; if (typeof r.ideal === 'number') { oc[key] = {min: r.ideal, max: r.ideal}; } else { oc[key] = r.ideal; } c.advanced.push(oc); delete r.ideal; if (!Object.keys(r).length) { delete c[key]; } } }); if (require.length) { c.require = require; } return c; }; constraints = JSON.parse(JSON.stringify(constraints)); if (browserDetails.version < 38) { logging('spec: ' + JSON.stringify(constraints)); if (constraints.audio) { constraints.audio = constraintsToFF37_(constraints.audio); } if (constraints.video) { constraints.video = constraintsToFF37_(constraints.video); } logging('ff37: ' + JSON.stringify(constraints)); } return navigator.mozGetUserMedia(constraints, onSuccess, function(e) { onError(shimError_(e)); }); }; // Returns the result of getUserMedia as a Promise. var getUserMediaPromise_ = function(constraints) { return new Promise(function(resolve, reject) { getUserMedia_(constraints, resolve, reject); }); }; // Shim for mediaDevices on older versions. if (!navigator.mediaDevices) { navigator.mediaDevices = {getUserMedia: getUserMediaPromise_, addEventListener: function() { }, removeEventListener: function() { } }; } navigator.mediaDevices.enumerateDevices = navigator.mediaDevices.enumerateDevices || function() { return new Promise(function(resolve) { var infos = [ {kind: 'audioinput', deviceId: 'default', label: '', groupId: ''}, {kind: 'videoinput', deviceId: 'default', label: '', groupId: ''} ]; resolve(infos); }); }; if (browserDetails.version < 41) { // Work around http://bugzil.la/1169665 var orgEnumerateDevices = navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices); navigator.mediaDevices.enumerateDevices = function() { return orgEnumerateDevices().then(undefined, function(e) { if (e.name === 'NotFoundError') { return []; } throw e; }); }; } if (browserDetails.version < 49) { var origGetUserMedia = navigator.mediaDevices.getUserMedia. bind(navigator.mediaDevices); navigator.mediaDevices.getUserMedia = function(c) { return origGetUserMedia(c).then(function(stream) { // Work around https://bugzil.la/802326 if (c.audio && !stream.getAudioTracks().length || c.video && !stream.getVideoTracks().length) { stream.getTracks().forEach(function(track) { track.stop(); }); throw new DOMException('The object can not be found here.', 'NotFoundError'); } return stream; }, function(e) { return Promise.reject(shimError_(e)); }); }; } navigator.getUserMedia = function(constraints, onSuccess, onError) { if (browserDetails.version < 44) { return getUserMedia_(constraints, onSuccess, onError); } // Replace Firefox 44+'s deprecation warning with unprefixed version. console.warn('navigator.getUserMedia has been replaced by ' + 'navigator.mediaDevices.getUserMedia'); navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError); }; }; },{"../utils":49}],48:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ 'use strict'; var safariShim = { // TODO: DrAlex, should be here, double check against LayoutTests // shimOnTrack: function() { }, // TODO: once the back-end for the mac port is done, add. // TODO: check for webkitGTK+ // shimPeerConnection: function() { }, shimGetUserMedia: function() { navigator.getUserMedia = navigator.webkitGetUserMedia; } }; // Expose public methods. module.exports = { shimGetUserMedia: safariShim.shimGetUserMedia // TODO // shimOnTrack: safariShim.shimOnTrack, // shimPeerConnection: safariShim.shimPeerConnection }; },{}],49:[function(require,module,exports){ /* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ /* eslint-env node */ 'use strict'; var logDisabled_ = true; // Utility methods. var utils = { disableLog: function(bool) { if (typeof bool !== 'boolean') { return new Error('Argument type: ' + typeof bool + '. Please use a boolean.'); } logDisabled_ = bool; return (bool) ? 'adapter.js logging disabled' : 'adapter.js logging enabled'; }, log: function() { if (typeof window === 'object') { if (logDisabled_) { return; } if (typeof console !== 'undefined' && typeof console.log === 'function') { console.log.apply(console, arguments); } } }, /** * Extract browser version out of the provided user agent string. * * @param {!string} uastring userAgent string. * @param {!string} expr Regular expression used as match criteria. * @param {!number} pos position in the version string to be returned. * @return {!number} browser version. */ extractVersion: function(uastring, expr, pos) { var match = uastring.match(expr); return match && match.length >= pos && parseInt(match[pos], 10); }, /** * Browser detector. * * @return {object} result containing browser and version * properties. */ detectBrowser: function() { // Returned result object. var result = {}; result.browser = null; result.version = null; // Fail early if it's not a browser if (typeof window === 'undefined' || !window.navigator) { result.browser = 'Not a browser.'; return result; } // Firefox. if (navigator.mozGetUserMedia) { result.browser = 'firefox'; result.version = this.extractVersion(navigator.userAgent, /Firefox\/([0-9]+)\./, 1); // all webkit-based browsers } else if (navigator.webkitGetUserMedia) { // Chrome, Chromium, Webview, Opera, all use the chrome shim for now if (window.webkitRTCPeerConnection) { result.browser = 'chrome'; result.version = this.extractVersion(navigator.userAgent, /Chrom(e|ium)\/([0-9]+)\./, 2); // Safari or unknown webkit-based // for the time being Safari has support for MediaStreams but not webRTC } else { // Safari UA substrings of interest for reference: // - webkit version: AppleWebKit/602.1.25 (also used in Op,Cr) // - safari UI version: Version/9.0.3 (unique to Safari) // - safari UI webkit version: Safari/601.4.4 (also used in Op,Cr) // // if the webkit version and safari UI webkit versions are equals, // ... this is a stable version. // // only the internal webkit version is important today to know if // media streams are supported // if (navigator.userAgent.match(/Version\/(\d+).(\d+)/)) { result.browser = 'safari'; result.version = this.extractVersion(navigator.userAgent, /AppleWebKit\/([0-9]+)\./, 1); // unknown webkit-based browser } else { result.browser = 'Unsupported webkit-based browser ' + 'with GUM support but no WebRTC support.'; return result; } } // Edge. } else if (navigator.mediaDevices && navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)) { result.browser = 'edge'; result.version = this.extractVersion(navigator.userAgent, /Edge\/(\d+).(\d+)$/, 2); // Default fallthrough: not supported. } else { result.browser = 'Not a supported browser.'; return result; } return result; } }; // Export. module.exports = { log: utils.log, disableLog: utils.disableLog, browserDetails: utils.detectBrowser(), extractVersion: utils.extractVersion }; },{}],50:[function(require,module,exports){ module.exports={ "name": "jssip", "title": "JsSIP", "description": "the Javascript SIP library", "version": "3.0.2", "homepage": "http://jssip.net", "author": "José Luis Millán <[email protected]> (https://github.com/jmillan)", "contributors": [ "Iñaki Baz Castillo <[email protected]> (https://github.com/ibc)", "Saúl Ibarra Corretgé <[email protected]> (https://github.com/saghul)" ], "main": "lib/JsSIP.js", "keywords": [ "sip", "websocket", "webrtc", "node", "browser", "library" ], "license": "MIT", "repository": { "type": "git", "url": "https://github.com/versatica/JsSIP.git" }, "bugs": { "url": "https://github.com/versatica/JsSIP/issues" }, "dependencies": { "debug": "^2.3.3", "sdp-transform": "^1.6.2", "webrtc-adapter": "^2.0.8" }, "devDependencies": { "browserify": "^13.1.1", "gulp": "git+https://github.com/gulpjs/gulp.git#4.0", "gulp-expect-file": "0.0.7", "gulp-header": "1.8.8", "gulp-jshint": "^2.0.4", "gulp-nodeunit-runner": "^0.2.2", "gulp-rename": "^1.2.2", "gulp-uglify": "^2.0.0", "gulp-util": "^3.0.7", "jshint": "^2.9.4", "jshint-stylish": "^2.2.1", "pegjs": "0.7.0", "vinyl-buffer": "^1.0.0", "vinyl-source-stream": "^1.1.0" }, "scripts": { "test": "gulp test" } } },{}]},{},[7])(7) });
var five = require("../lib/johnny-five.js"); var board = new five.Board(); board.on("ready", function() { var temperature = new five.Temperature({ controller: "MPL115A2" }); temperature.on("data", function() { console.log("temperature"); console.log(" celsius : ", this.celsius); console.log(" fahrenheit : ", this.fahrenheit); console.log(" kelvin : ", this.kelvin); console.log("--------------------------------------"); }); }); // @markdown // - [MPL115A2 - I2C Barometric Pressure/Temperature Sensor](https://www.adafruit.com/product/992) // @markdown
ej.addCulture( "az-Latn-AZ", { name: "az-Latn-AZ", englishName: "Azerbaijani (Latin, Azerbaijan)", nativeName: "Azərbaycan dili (Azərbaycan)", language: "az-Latn", numberFormat: { ",": " ", ".": ",", percent: { pattern: ["-n%","n%"], ",": " ", ".": "," }, currency: { pattern: ["-n $","n $"], ",": " ", ".": ",", symbol: "manat" } }, calendars: { standard: { "/": ".", firstDay: 1, days: { names: ["bazar","Bazar ertəsi","çərşənbə axşamı","çərşənbə","Cümə axşamı","Cümə","şənbə"], namesAbbr: ["B","Be","Ça","Ç","Ca","C","Ş"], namesShort: ["B","Be","Ça","Ç","Ca","C","Ş"] }, months: { names: ["yanvar","fevral","mart","aprel","may","iyun","iyul","avgust","sentyabr","oktyabr","noyabr","dekabr",""], namesAbbr: ["Yan","Fev","Mar","Apr","May","İyun","İyul","Avg","Sen","Okt","Noy","Dek",""] }, AM: null, PM: null, patterns: { d: "dd.MM.yyyy", D: "dd MMMM yyyy'-cü il'", t: "HH:mm", T: "HH:mm:ss", f: "dd MMMM yyyy'-cü il' HH:mm", F: "dd MMMM yyyy'-cü il' HH:mm:ss", M: "d MMMM" } }, Hijri: { name: "Hijri", "/": ".", firstDay: 1, days: { names: ["Bazar","Bazar ertəsi","Çərşənbə axşamı","Çərşənbə","Cümə axşamı","Cümə","Şənbə"], namesAbbr: ["B","Be","Ça","Ç","Ca","C","Ş"], namesShort: ["B","Be","Ça","Ç","Ca","C","Ş"] }, months: { names: ["Məhərrəm","Səfər","Rəbiüləvvəl","Rəbiülaxır","Cəmadiyələvvəl","Cəmadiyəlaxır","Rəcəb","Şaban","Ramazan","Şəvval","Zilqədə","Zilhiccə",""], namesAbbr: ["Məhərrəm","Səfər","Rəbiüləvvəl","Rəbiülaxır","Cəmadiyələvvəl","Cəmadiyəlaxır","Rəcəb","Şaban","Ramazan","Şəvval","Zilqədə","Zilhiccə",""] }, AM: null, PM: null, twoDigitYearMax: 1451, patterns: { d: "dd.MM.yyyy", D: "d MMMM yyyy", t: "HH:mm", T: "HH:mm:ss", f: "d MMMM yyyy HH:mm", F: "d MMMM yyyy HH:mm:ss", M: "d MMMM" }, convert: { // Adapted to Script from System.Globalization.HijriCalendar ticks1970: 62135596800000, // number of days leading up to each month monthDays: [0, 30, 59, 89, 118, 148, 177, 207, 236, 266, 295, 325, 355], minDate: -42521673600000, maxDate: 253402300799999, // The number of days to add or subtract from the calendar to accommodate the variances // in the start and the end of Ramadan and to accommodate the date difference between // countries/regions. May be dynamically adjusted based on user preference, but should // remain in the range of -2 to 2, inclusive. hijriAdjustment: 0, toGregorian: function(hyear, hmonth, hday) { var daysSinceJan0101 = this.daysToYear(hyear) + this.monthDays[hmonth] + hday - 1 - this.hijriAdjustment; // 86400000 = ticks per day var gdate = new Date(daysSinceJan0101 * 86400000 - this.ticks1970); // adjust for timezone, because we are interested in the gregorian date for the same timezone // but ticks in javascript is always from GMT, unlike the server were ticks counts from the base // date in the current timezone. gdate.setMinutes(gdate.getMinutes() + gdate.getTimezoneOffset()); return gdate; }, fromGregorian: function(gdate) { if ((gdate < this.minDate) || (gdate > this.maxDate)) return null; var ticks = this.ticks1970 + (gdate-0) - gdate.getTimezoneOffset() * 60000, daysSinceJan0101 = Math.floor(ticks / 86400000) + 1 + this.hijriAdjustment; // very particular formula determined by someone smart, adapted from the server-side implementation. // it approximates the hijri year. var hday, hmonth, hyear = Math.floor(((daysSinceJan0101 - 227013) * 30) / 10631) + 1, absDays = this.daysToYear(hyear), daysInYear = this.isLeapYear(hyear) ? 355 : 354; // hyear is just approximate, it may need adjustment up or down by 1. if (daysSinceJan0101 < absDays) { hyear--; absDays -= daysInYear; } else if (daysSinceJan0101 === absDays) { hyear--; absDays = this.daysToYear(hyear); } else { if (daysSinceJan0101 > (absDays + daysInYear)) { absDays += daysInYear; hyear++; } } // determine month by looking at how many days into the hyear we are // monthDays contains the number of days up to each month. hmonth = 0; var daysIntoYear = daysSinceJan0101 - absDays; while (hmonth <= 11 && daysIntoYear > this.monthDays[hmonth]) { hmonth++; } hmonth--; hday = daysIntoYear - this.monthDays[hmonth]; return [hyear, hmonth, hday]; }, daysToYear: function(year) { // calculates how many days since Jan 1, 0001 var yearsToYear30 = Math.floor((year - 1) / 30) * 30, yearsInto30 = year - yearsToYear30 - 1, days = Math.floor((yearsToYear30 * 10631) / 30) + 227013; while (yearsInto30 > 0) { days += (this.isLeapYear(yearsInto30) ? 355 : 354); yearsInto30--; } return days; }, isLeapYear: function(year) { return ((((year * 11) + 14) % 30) < 11); } } } } });
// This file contains methods responsible for removing a node. import { hooks } from "./lib/removal-hooks"; export function remove() { this._assertUnremoved(); this.resync(); if (this._callRemovalHooks()) { this._markRemoved(); return; } this.shareCommentsWithSiblings(); this._remove(); this._markRemoved(); } export function _callRemovalHooks() { for (let fn of (hooks: Array<Function>)) { if (fn(this, this.parentPath)) return true; } } export function _remove() { if (Array.isArray(this.container)) { this.container.splice(this.key, 1); this.updateSiblingKeys(this.key, -1); } else { this._replaceWith(null); } } export function _markRemoved() { this.shouldSkip = true; this.removed = true; this.node = null; } export function _assertUnremoved() { if (this.removed) { throw this.buildCodeFrameError("NodePath has been removed so is read-only."); } }
/*! DataTables 1.10.7 * ©2008-2015 SpryMedia Ltd - datatables.net/license */ (function(Ea,Q,k){var P=function(h){function W(a){var b,c,e={};h.each(a,function(d){if((b=d.match(/^([^A-Z]+?)([A-Z])/))&&-1!=="a aa ai ao as b fn i m o s ".indexOf(b[1]+" "))c=d.replace(b[0],b[2].toLowerCase()),e[c]=d,"o"===b[1]&&W(a[d])});a._hungarianMap=e}function H(a,b,c){a._hungarianMap||W(a);var e;h.each(b,function(d){e=a._hungarianMap[d];if(e!==k&&(c||b[e]===k))"o"===e.charAt(0)?(b[e]||(b[e]={}),h.extend(!0,b[e],b[d]),H(a[e],b[e],c)):b[e]=b[d]})}function P(a){var b=m.defaults.oLanguage,c=a.sZeroRecords; !a.sEmptyTable&&(c&&"No data available in table"===b.sEmptyTable)&&E(a,a,"sZeroRecords","sEmptyTable");!a.sLoadingRecords&&(c&&"Loading..."===b.sLoadingRecords)&&E(a,a,"sZeroRecords","sLoadingRecords");a.sInfoThousands&&(a.sThousands=a.sInfoThousands);(a=a.sDecimal)&&db(a)}function eb(a){A(a,"ordering","bSort");A(a,"orderMulti","bSortMulti");A(a,"orderClasses","bSortClasses");A(a,"orderCellsTop","bSortCellsTop");A(a,"order","aaSorting");A(a,"orderFixed","aaSortingFixed");A(a,"paging","bPaginate"); A(a,"pagingType","sPaginationType");A(a,"pageLength","iDisplayLength");A(a,"searching","bFilter");if(a=a.aoSearchCols)for(var b=0,c=a.length;b<c;b++)a[b]&&H(m.models.oSearch,a[b])}function fb(a){A(a,"orderable","bSortable");A(a,"orderData","aDataSort");A(a,"orderSequence","asSorting");A(a,"orderDataType","sortDataType");var b=a.aDataSort;b&&!h.isArray(b)&&(a.aDataSort=[b])}function gb(a){var a=a.oBrowser,b=h("<div/>").css({position:"absolute",top:0,left:0,height:1,width:1,overflow:"hidden"}).append(h("<div/>").css({position:"absolute", top:1,left:1,width:100,overflow:"scroll"}).append(h('<div class="test"/>').css({width:"100%",height:10}))).appendTo("body"),c=b.find(".test");a.bScrollOversize=100===c[0].offsetWidth;a.bScrollbarLeft=1!==Math.round(c.offset().left);b.remove()}function hb(a,b,c,e,d,f){var g,j=!1;c!==k&&(g=c,j=!0);for(;e!==d;)a.hasOwnProperty(e)&&(g=j?b(g,a[e],e,a):a[e],j=!0,e+=f);return g}function Fa(a,b){var c=m.defaults.column,e=a.aoColumns.length,c=h.extend({},m.models.oColumn,c,{nTh:b?b:Q.createElement("th"),sTitle:c.sTitle? c.sTitle:b?b.innerHTML:"",aDataSort:c.aDataSort?c.aDataSort:[e],mData:c.mData?c.mData:e,idx:e});a.aoColumns.push(c);c=a.aoPreSearchCols;c[e]=h.extend({},m.models.oSearch,c[e]);ka(a,e,h(b).data())}function ka(a,b,c){var b=a.aoColumns[b],e=a.oClasses,d=h(b.nTh);if(!b.sWidthOrig){b.sWidthOrig=d.attr("width")||null;var f=(d.attr("style")||"").match(/width:\s*(\d+[pxem%]+)/);f&&(b.sWidthOrig=f[1])}c!==k&&null!==c&&(fb(c),H(m.defaults.column,c),c.mDataProp!==k&&!c.mData&&(c.mData=c.mDataProp),c.sType&& (b._sManualType=c.sType),c.className&&!c.sClass&&(c.sClass=c.className),h.extend(b,c),E(b,c,"sWidth","sWidthOrig"),c.iDataSort!==k&&(b.aDataSort=[c.iDataSort]),E(b,c,"aDataSort"));var g=b.mData,j=R(g),i=b.mRender?R(b.mRender):null,c=function(a){return"string"===typeof a&&-1!==a.indexOf("@")};b._bAttrSrc=h.isPlainObject(g)&&(c(g.sort)||c(g.type)||c(g.filter));b.fnGetData=function(a,b,c){var e=j(a,b,k,c);return i&&b?i(e,b,a,c):e};b.fnSetData=function(a,b,c){return S(g)(a,b,c)};"number"!==typeof g&& (a._rowReadObject=!0);a.oFeatures.bSort||(b.bSortable=!1,d.addClass(e.sSortableNone));a=-1!==h.inArray("asc",b.asSorting);c=-1!==h.inArray("desc",b.asSorting);!b.bSortable||!a&&!c?(b.sSortingClass=e.sSortableNone,b.sSortingClassJUI=""):a&&!c?(b.sSortingClass=e.sSortableAsc,b.sSortingClassJUI=e.sSortJUIAscAllowed):!a&&c?(b.sSortingClass=e.sSortableDesc,b.sSortingClassJUI=e.sSortJUIDescAllowed):(b.sSortingClass=e.sSortable,b.sSortingClassJUI=e.sSortJUI)}function X(a){if(!1!==a.oFeatures.bAutoWidth){var b= a.aoColumns;Ga(a);for(var c=0,e=b.length;c<e;c++)b[c].nTh.style.width=b[c].sWidth}b=a.oScroll;(""!==b.sY||""!==b.sX)&&Y(a);w(a,null,"column-sizing",[a])}function la(a,b){var c=Z(a,"bVisible");return"number"===typeof c[b]?c[b]:null}function $(a,b){var c=Z(a,"bVisible"),c=h.inArray(b,c);return-1!==c?c:null}function aa(a){return Z(a,"bVisible").length}function Z(a,b){var c=[];h.map(a.aoColumns,function(a,d){a[b]&&c.push(d)});return c}function Ha(a){var b=a.aoColumns,c=a.aoData,e=m.ext.type.detect,d, f,g,j,i,h,l,q,n;d=0;for(f=b.length;d<f;d++)if(l=b[d],n=[],!l.sType&&l._sManualType)l.sType=l._sManualType;else if(!l.sType){g=0;for(j=e.length;g<j;g++){i=0;for(h=c.length;i<h;i++){n[i]===k&&(n[i]=x(a,i,d,"type"));q=e[g](n[i],a);if(!q&&g!==e.length-1)break;if("html"===q)break}if(q){l.sType=q;break}}l.sType||(l.sType="string")}}function ib(a,b,c,e){var d,f,g,j,i,o,l=a.aoColumns;if(b)for(d=b.length-1;0<=d;d--){o=b[d];var q=o.targets!==k?o.targets:o.aTargets;h.isArray(q)||(q=[q]);f=0;for(g=q.length;f< g;f++)if("number"===typeof q[f]&&0<=q[f]){for(;l.length<=q[f];)Fa(a);e(q[f],o)}else if("number"===typeof q[f]&&0>q[f])e(l.length+q[f],o);else if("string"===typeof q[f]){j=0;for(i=l.length;j<i;j++)("_all"==q[f]||h(l[j].nTh).hasClass(q[f]))&&e(j,o)}}if(c){d=0;for(a=c.length;d<a;d++)e(d,c[d])}}function K(a,b,c,e){var d=a.aoData.length,f=h.extend(!0,{},m.models.oRow,{src:c?"dom":"data"});f._aData=b;a.aoData.push(f);for(var b=a.aoColumns,f=0,g=b.length;f<g;f++)c&&Ia(a,d,f,x(a,d,f)),b[f].sType=null;a.aiDisplayMaster.push(d); (c||!a.oFeatures.bDeferRender)&&Ja(a,d,c,e);return d}function ma(a,b){var c;b instanceof h||(b=h(b));return b.map(function(b,d){c=na(a,d);return K(a,c.data,d,c.cells)})}function x(a,b,c,e){var d=a.iDraw,f=a.aoColumns[c],g=a.aoData[b]._aData,j=f.sDefaultContent,c=f.fnGetData(g,e,{settings:a,row:b,col:c});if(c===k)return a.iDrawError!=d&&null===j&&(I(a,0,"Requested unknown parameter "+("function"==typeof f.mData?"{function}":"'"+f.mData+"'")+" for row "+b,4),a.iDrawError=d),j;if((c===g||null===c)&& null!==j)c=j;else if("function"===typeof c)return c.call(g);return null===c&&"display"==e?"":c}function Ia(a,b,c,e){a.aoColumns[c].fnSetData(a.aoData[b]._aData,e,{settings:a,row:b,col:c})}function Ka(a){return h.map(a.match(/(\\.|[^\.])+/g),function(a){return a.replace(/\\./g,".")})}function R(a){if(h.isPlainObject(a)){var b={};h.each(a,function(a,c){c&&(b[a]=R(c))});return function(a,c,f,g){var j=b[c]||b._;return j!==k?j(a,c,f,g):a}}if(null===a)return function(a){return a};if("function"===typeof a)return function(b, c,f,g){return a(b,c,f,g)};if("string"===typeof a&&(-1!==a.indexOf(".")||-1!==a.indexOf("[")||-1!==a.indexOf("("))){var c=function(a,b,f){var g,j;if(""!==f){j=Ka(f);for(var i=0,h=j.length;i<h;i++){f=j[i].match(ba);g=j[i].match(T);if(f){j[i]=j[i].replace(ba,"");""!==j[i]&&(a=a[j[i]]);g=[];j.splice(0,i+1);j=j.join(".");i=0;for(h=a.length;i<h;i++)g.push(c(a[i],b,j));a=f[0].substring(1,f[0].length-1);a=""===a?g:g.join(a);break}else if(g){j[i]=j[i].replace(T,"");a=a[j[i]]();continue}if(null===a||a[j[i]]=== k)return k;a=a[j[i]]}}return a};return function(b,d){return c(b,d,a)}}return function(b){return b[a]}}function S(a){if(h.isPlainObject(a))return S(a._);if(null===a)return function(){};if("function"===typeof a)return function(b,e,d){a(b,"set",e,d)};if("string"===typeof a&&(-1!==a.indexOf(".")||-1!==a.indexOf("[")||-1!==a.indexOf("("))){var b=function(a,e,d){var d=Ka(d),f;f=d[d.length-1];for(var g,j,i=0,h=d.length-1;i<h;i++){g=d[i].match(ba);j=d[i].match(T);if(g){d[i]=d[i].replace(ba,"");a[d[i]]=[]; f=d.slice();f.splice(0,i+1);g=f.join(".");j=0;for(h=e.length;j<h;j++)f={},b(f,e[j],g),a[d[i]].push(f);return}j&&(d[i]=d[i].replace(T,""),a=a[d[i]](e));if(null===a[d[i]]||a[d[i]]===k)a[d[i]]={};a=a[d[i]]}if(f.match(T))a[f.replace(T,"")](e);else a[f.replace(ba,"")]=e};return function(c,e){return b(c,e,a)}}return function(b,e){b[a]=e}}function La(a){return D(a.aoData,"_aData")}function oa(a){a.aoData.length=0;a.aiDisplayMaster.length=0;a.aiDisplay.length=0}function pa(a,b,c){for(var e=-1,d=0,f=a.length;d< f;d++)a[d]==b?e=d:a[d]>b&&a[d]--; -1!=e&&c===k&&a.splice(e,1)}function ca(a,b,c,e){var d=a.aoData[b],f,g=function(c,f){for(;c.childNodes.length;)c.removeChild(c.firstChild);c.innerHTML=x(a,b,f,"display")};if("dom"===c||(!c||"auto"===c)&&"dom"===d.src)d._aData=na(a,d,e,e===k?k:d._aData).data;else{var j=d.anCells;if(j)if(e!==k)g(j[e],e);else{c=0;for(f=j.length;c<f;c++)g(j[c],c)}}d._aSortData=null;d._aFilterData=null;g=a.aoColumns;if(e!==k)g[e].sType=null;else{c=0;for(f=g.length;c<f;c++)g[c].sType=null; Ma(d)}}function na(a,b,c,e){var d=[],f=b.firstChild,g,j=0,i,o=a.aoColumns,l=a._rowReadObject,e=e||l?{}:[],q=function(a,b){if("string"===typeof a){var c=a.indexOf("@");-1!==c&&(c=a.substring(c+1),S(a)(e,b.getAttribute(c)))}},a=function(a){if(c===k||c===j)g=o[j],i=h.trim(a.innerHTML),g&&g._bAttrSrc?(S(g.mData._)(e,i),q(g.mData.sort,a),q(g.mData.type,a),q(g.mData.filter,a)):l?(g._setter||(g._setter=S(g.mData)),g._setter(e,i)):e[j]=i;j++};if(f)for(;f;){b=f.nodeName.toUpperCase();if("TD"==b||"TH"==b)a(f), d.push(f);f=f.nextSibling}else{d=b.anCells;f=0;for(b=d.length;f<b;f++)a(d[f])}return{data:e,cells:d}}function Ja(a,b,c,e){var d=a.aoData[b],f=d._aData,g=[],j,i,h,l,q;if(null===d.nTr){j=c||Q.createElement("tr");d.nTr=j;d.anCells=g;j._DT_RowIndex=b;Ma(d);l=0;for(q=a.aoColumns.length;l<q;l++){h=a.aoColumns[l];i=c?e[l]:Q.createElement(h.sCellType);g.push(i);if(!c||h.mRender||h.mData!==l)i.innerHTML=x(a,b,l,"display");h.sClass&&(i.className+=" "+h.sClass);h.bVisible&&!c?j.appendChild(i):!h.bVisible&&c&& i.parentNode.removeChild(i);h.fnCreatedCell&&h.fnCreatedCell.call(a.oInstance,i,x(a,b,l),f,b,l)}w(a,"aoRowCreatedCallback",null,[j,f,b])}d.nTr.setAttribute("role","row")}function Ma(a){var b=a.nTr,c=a._aData;if(b){c.DT_RowId&&(b.id=c.DT_RowId);if(c.DT_RowClass){var e=c.DT_RowClass.split(" ");a.__rowc=a.__rowc?Na(a.__rowc.concat(e)):e;h(b).removeClass(a.__rowc.join(" ")).addClass(c.DT_RowClass)}c.DT_RowAttr&&h(b).attr(c.DT_RowAttr);c.DT_RowData&&h(b).data(c.DT_RowData)}}function jb(a){var b,c,e,d, f,g=a.nTHead,j=a.nTFoot,i=0===h("th, td",g).length,o=a.oClasses,l=a.aoColumns;i&&(d=h("<tr/>").appendTo(g));b=0;for(c=l.length;b<c;b++)f=l[b],e=h(f.nTh).addClass(f.sClass),i&&e.appendTo(d),a.oFeatures.bSort&&(e.addClass(f.sSortingClass),!1!==f.bSortable&&(e.attr("tabindex",a.iTabIndex).attr("aria-controls",a.sTableId),Oa(a,f.nTh,b))),f.sTitle!=e.html()&&e.html(f.sTitle),Pa(a,"header")(a,e,f,o);i&&da(a.aoHeader,g);h(g).find(">tr").attr("role","row");h(g).find(">tr>th, >tr>td").addClass(o.sHeaderTH); h(j).find(">tr>th, >tr>td").addClass(o.sFooterTH);if(null!==j){a=a.aoFooter[0];b=0;for(c=a.length;b<c;b++)f=l[b],f.nTf=a[b].cell,f.sClass&&h(f.nTf).addClass(f.sClass)}}function ea(a,b,c){var e,d,f,g=[],j=[],i=a.aoColumns.length,o;if(b){c===k&&(c=!1);e=0;for(d=b.length;e<d;e++){g[e]=b[e].slice();g[e].nTr=b[e].nTr;for(f=i-1;0<=f;f--)!a.aoColumns[f].bVisible&&!c&&g[e].splice(f,1);j.push([])}e=0;for(d=g.length;e<d;e++){if(a=g[e].nTr)for(;f=a.firstChild;)a.removeChild(f);f=0;for(b=g[e].length;f<b;f++)if(o= i=1,j[e][f]===k){a.appendChild(g[e][f].cell);for(j[e][f]=1;g[e+i]!==k&&g[e][f].cell==g[e+i][f].cell;)j[e+i][f]=1,i++;for(;g[e][f+o]!==k&&g[e][f].cell==g[e][f+o].cell;){for(c=0;c<i;c++)j[e+c][f+o]=1;o++}h(g[e][f].cell).attr("rowspan",i).attr("colspan",o)}}}}function M(a){var b=w(a,"aoPreDrawCallback","preDraw",[a]);if(-1!==h.inArray(!1,b))C(a,!1);else{var b=[],c=0,e=a.asStripeClasses,d=e.length,f=a.oLanguage,g=a.iInitDisplayStart,j="ssp"==B(a),i=a.aiDisplay;a.bDrawing=!0;g!==k&&-1!==g&&(a._iDisplayStart= j?g:g>=a.fnRecordsDisplay()?0:g,a.iInitDisplayStart=-1);var g=a._iDisplayStart,o=a.fnDisplayEnd();if(a.bDeferLoading)a.bDeferLoading=!1,a.iDraw++,C(a,!1);else if(j){if(!a.bDestroying&&!kb(a))return}else a.iDraw++;if(0!==i.length){f=j?a.aoData.length:o;for(j=j?0:g;j<f;j++){var l=i[j],q=a.aoData[l];null===q.nTr&&Ja(a,l);l=q.nTr;if(0!==d){var n=e[c%d];q._sRowStripe!=n&&(h(l).removeClass(q._sRowStripe).addClass(n),q._sRowStripe=n)}w(a,"aoRowCallback",null,[l,q._aData,c,j]);b.push(l);c++}}else c=f.sZeroRecords, 1==a.iDraw&&"ajax"==B(a)?c=f.sLoadingRecords:f.sEmptyTable&&0===a.fnRecordsTotal()&&(c=f.sEmptyTable),b[0]=h("<tr/>",{"class":d?e[0]:""}).append(h("<td />",{valign:"top",colSpan:aa(a),"class":a.oClasses.sRowEmpty}).html(c))[0];w(a,"aoHeaderCallback","header",[h(a.nTHead).children("tr")[0],La(a),g,o,i]);w(a,"aoFooterCallback","footer",[h(a.nTFoot).children("tr")[0],La(a),g,o,i]);e=h(a.nTBody);e.children().detach();e.append(h(b));w(a,"aoDrawCallback","draw",[a]);a.bSorted=!1;a.bFiltered=!1;a.bDrawing= !1}}function N(a,b){var c=a.oFeatures,e=c.bFilter;c.bSort&&lb(a);e?fa(a,a.oPreviousSearch):a.aiDisplay=a.aiDisplayMaster.slice();!0!==b&&(a._iDisplayStart=0);a._drawHold=b;M(a);a._drawHold=!1}function mb(a){var b=a.oClasses,c=h(a.nTable),c=h("<div/>").insertBefore(c),e=a.oFeatures,d=h("<div/>",{id:a.sTableId+"_wrapper","class":b.sWrapper+(a.nTFoot?"":" "+b.sNoFooter)});a.nHolding=c[0];a.nTableWrapper=d[0];a.nTableReinsertBefore=a.nTable.nextSibling;for(var f=a.sDom.split(""),g,j,i,o,l,q,n=0;n<f.length;n++){g= null;j=f[n];if("<"==j){i=h("<div/>")[0];o=f[n+1];if("'"==o||'"'==o){l="";for(q=2;f[n+q]!=o;)l+=f[n+q],q++;"H"==l?l=b.sJUIHeader:"F"==l&&(l=b.sJUIFooter);-1!=l.indexOf(".")?(o=l.split("."),i.id=o[0].substr(1,o[0].length-1),i.className=o[1]):"#"==l.charAt(0)?i.id=l.substr(1,l.length-1):i.className=l;n+=q}d.append(i);d=h(i)}else if(">"==j)d=d.parent();else if("l"==j&&e.bPaginate&&e.bLengthChange)g=nb(a);else if("f"==j&&e.bFilter)g=ob(a);else if("r"==j&&e.bProcessing)g=pb(a);else if("t"==j)g=qb(a);else if("i"== j&&e.bInfo)g=rb(a);else if("p"==j&&e.bPaginate)g=sb(a);else if(0!==m.ext.feature.length){i=m.ext.feature;q=0;for(o=i.length;q<o;q++)if(j==i[q].cFeature){g=i[q].fnInit(a);break}}g&&(i=a.aanFeatures,i[j]||(i[j]=[]),i[j].push(g),d.append(g))}c.replaceWith(d)}function da(a,b){var c=h(b).children("tr"),e,d,f,g,j,i,o,l,q,n;a.splice(0,a.length);f=0;for(i=c.length;f<i;f++)a.push([]);f=0;for(i=c.length;f<i;f++){e=c[f];for(d=e.firstChild;d;){if("TD"==d.nodeName.toUpperCase()||"TH"==d.nodeName.toUpperCase()){l= 1*d.getAttribute("colspan");q=1*d.getAttribute("rowspan");l=!l||0===l||1===l?1:l;q=!q||0===q||1===q?1:q;g=0;for(j=a[f];j[g];)g++;o=g;n=1===l?!0:!1;for(j=0;j<l;j++)for(g=0;g<q;g++)a[f+g][o+j]={cell:d,unique:n},a[f+g].nTr=e}d=d.nextSibling}}}function qa(a,b,c){var e=[];c||(c=a.aoHeader,b&&(c=[],da(c,b)));for(var b=0,d=c.length;b<d;b++)for(var f=0,g=c[b].length;f<g;f++)if(c[b][f].unique&&(!e[f]||!a.bSortCellsTop))e[f]=c[b][f].cell;return e}function ra(a,b,c){w(a,"aoServerParams","serverParams",[b]); if(b&&h.isArray(b)){var e={},d=/(.*?)\[\]$/;h.each(b,function(a,b){var c=b.name.match(d);c?(c=c[0],e[c]||(e[c]=[]),e[c].push(b.value)):e[b.name]=b.value});b=e}var f,g=a.ajax,j=a.oInstance,i=function(b){w(a,null,"xhr",[a,b,a.jqXHR]);c(b)};if(h.isPlainObject(g)&&g.data){f=g.data;var o=h.isFunction(f)?f(b,a):f,b=h.isFunction(f)&&o?o:h.extend(!0,b,o);delete g.data}o={data:b,success:function(b){var c=b.error||b.sError;c&&I(a,0,c);a.json=b;i(b)},dataType:"json",cache:!1,type:a.sServerMethod,error:function(b, c){var f=w(a,null,"xhr",[a,null,a.jqXHR]);-1===h.inArray(!0,f)&&("parsererror"==c?I(a,0,"Invalid JSON response",1):4===b.readyState&&I(a,0,"Ajax error",7));C(a,!1)}};a.oAjaxData=b;w(a,null,"preXhr",[a,b]);a.fnServerData?a.fnServerData.call(j,a.sAjaxSource,h.map(b,function(a,b){return{name:b,value:a}}),i,a):a.sAjaxSource||"string"===typeof g?a.jqXHR=h.ajax(h.extend(o,{url:g||a.sAjaxSource})):h.isFunction(g)?a.jqXHR=g.call(j,b,i,a):(a.jqXHR=h.ajax(h.extend(o,g)),g.data=f)}function kb(a){return a.bAjaxDataGet? (a.iDraw++,C(a,!0),ra(a,tb(a),function(b){ub(a,b)}),!1):!0}function tb(a){var b=a.aoColumns,c=b.length,e=a.oFeatures,d=a.oPreviousSearch,f=a.aoPreSearchCols,g,j=[],i,o,l,q=U(a);g=a._iDisplayStart;i=!1!==e.bPaginate?a._iDisplayLength:-1;var n=function(a,b){j.push({name:a,value:b})};n("sEcho",a.iDraw);n("iColumns",c);n("sColumns",D(b,"sName").join(","));n("iDisplayStart",g);n("iDisplayLength",i);var k={draw:a.iDraw,columns:[],order:[],start:g,length:i,search:{value:d.sSearch,regex:d.bRegex}};for(g= 0;g<c;g++)o=b[g],l=f[g],i="function"==typeof o.mData?"function":o.mData,k.columns.push({data:i,name:o.sName,searchable:o.bSearchable,orderable:o.bSortable,search:{value:l.sSearch,regex:l.bRegex}}),n("mDataProp_"+g,i),e.bFilter&&(n("sSearch_"+g,l.sSearch),n("bRegex_"+g,l.bRegex),n("bSearchable_"+g,o.bSearchable)),e.bSort&&n("bSortable_"+g,o.bSortable);e.bFilter&&(n("sSearch",d.sSearch),n("bRegex",d.bRegex));e.bSort&&(h.each(q,function(a,b){k.order.push({column:b.col,dir:b.dir});n("iSortCol_"+a,b.col); n("sSortDir_"+a,b.dir)}),n("iSortingCols",q.length));b=m.ext.legacy.ajax;return null===b?a.sAjaxSource?j:k:b?j:k}function ub(a,b){var c=sa(a,b),e=b.sEcho!==k?b.sEcho:b.draw,d=b.iTotalRecords!==k?b.iTotalRecords:b.recordsTotal,f=b.iTotalDisplayRecords!==k?b.iTotalDisplayRecords:b.recordsFiltered;if(e){if(1*e<a.iDraw)return;a.iDraw=1*e}oa(a);a._iRecordsTotal=parseInt(d,10);a._iRecordsDisplay=parseInt(f,10);e=0;for(d=c.length;e<d;e++)K(a,c[e]);a.aiDisplay=a.aiDisplayMaster.slice();a.bAjaxDataGet=!1; M(a);a._bInitComplete||ta(a,b);a.bAjaxDataGet=!0;C(a,!1)}function sa(a,b){var c=h.isPlainObject(a.ajax)&&a.ajax.dataSrc!==k?a.ajax.dataSrc:a.sAjaxDataProp;return"data"===c?b.aaData||b[c]:""!==c?R(c)(b):b}function ob(a){var b=a.oClasses,c=a.sTableId,e=a.oLanguage,d=a.oPreviousSearch,f=a.aanFeatures,g='<input type="search" class="'+b.sFilterInput+'"/>',j=e.sSearch,j=j.match(/_INPUT_/)?j.replace("_INPUT_",g):j+g,b=h("<div/>",{id:!f.f?c+"_filter":null,"class":b.sFilter}).append(h("<label/>").append(j)), f=function(){var b=!this.value?"":this.value;b!=d.sSearch&&(fa(a,{sSearch:b,bRegex:d.bRegex,bSmart:d.bSmart,bCaseInsensitive:d.bCaseInsensitive}),a._iDisplayStart=0,M(a))},g=null!==a.searchDelay?a.searchDelay:"ssp"===B(a)?400:0,i=h("input",b).val(d.sSearch).attr("placeholder",e.sSearchPlaceholder).bind("keyup.DT search.DT input.DT paste.DT cut.DT",g?ua(f,g):f).bind("keypress.DT",function(a){if(13==a.keyCode)return!1}).attr("aria-controls",c);h(a.nTable).on("search.dt.DT",function(b,c){if(a===c)try{i[0]!== Q.activeElement&&i.val(d.sSearch)}catch(f){}});return b[0]}function fa(a,b,c){var e=a.oPreviousSearch,d=a.aoPreSearchCols,f=function(a){e.sSearch=a.sSearch;e.bRegex=a.bRegex;e.bSmart=a.bSmart;e.bCaseInsensitive=a.bCaseInsensitive};Ha(a);if("ssp"!=B(a)){vb(a,b.sSearch,c,b.bEscapeRegex!==k?!b.bEscapeRegex:b.bRegex,b.bSmart,b.bCaseInsensitive);f(b);for(b=0;b<d.length;b++)wb(a,d[b].sSearch,b,d[b].bEscapeRegex!==k?!d[b].bEscapeRegex:d[b].bRegex,d[b].bSmart,d[b].bCaseInsensitive);xb(a)}else f(b);a.bFiltered= !0;w(a,null,"search",[a])}function xb(a){for(var b=m.ext.search,c=a.aiDisplay,e,d,f=0,g=b.length;f<g;f++){for(var j=[],i=0,h=c.length;i<h;i++)d=c[i],e=a.aoData[d],b[f](a,e._aFilterData,d,e._aData,i)&&j.push(d);c.length=0;c.push.apply(c,j)}}function wb(a,b,c,e,d,f){if(""!==b)for(var g=a.aiDisplay,e=Qa(b,e,d,f),d=g.length-1;0<=d;d--)b=a.aoData[g[d]]._aFilterData[c],e.test(b)||g.splice(d,1)}function vb(a,b,c,e,d,f){var e=Qa(b,e,d,f),d=a.oPreviousSearch.sSearch,f=a.aiDisplayMaster,g;0!==m.ext.search.length&& (c=!0);g=yb(a);if(0>=b.length)a.aiDisplay=f.slice();else{if(g||c||d.length>b.length||0!==b.indexOf(d)||a.bSorted)a.aiDisplay=f.slice();b=a.aiDisplay;for(c=b.length-1;0<=c;c--)e.test(a.aoData[b[c]]._sFilterRow)||b.splice(c,1)}}function Qa(a,b,c,e){a=b?a:va(a);c&&(a="^(?=.*?"+h.map(a.match(/"[^"]+"|[^ ]+/g)||[""],function(a){if('"'===a.charAt(0))var b=a.match(/^"(.*)"$/),a=b?b[1]:a;return a.replace('"',"")}).join(")(?=.*?")+").*$");return RegExp(a,e?"i":"")}function va(a){return a.replace(Yb,"\\$1")} function yb(a){var b=a.aoColumns,c,e,d,f,g,j,i,h,l=m.ext.type.search;c=!1;e=0;for(f=a.aoData.length;e<f;e++)if(h=a.aoData[e],!h._aFilterData){j=[];d=0;for(g=b.length;d<g;d++)c=b[d],c.bSearchable?(i=x(a,e,d,"filter"),l[c.sType]&&(i=l[c.sType](i)),null===i&&(i=""),"string"!==typeof i&&i.toString&&(i=i.toString())):i="",i.indexOf&&-1!==i.indexOf("&")&&(wa.innerHTML=i,i=Zb?wa.textContent:wa.innerText),i.replace&&(i=i.replace(/[\r\n]/g,"")),j.push(i);h._aFilterData=j;h._sFilterRow=j.join(" ");c=!0}return c} function zb(a){return{search:a.sSearch,smart:a.bSmart,regex:a.bRegex,caseInsensitive:a.bCaseInsensitive}}function Ab(a){return{sSearch:a.search,bSmart:a.smart,bRegex:a.regex,bCaseInsensitive:a.caseInsensitive}}function rb(a){var b=a.sTableId,c=a.aanFeatures.i,e=h("<div/>",{"class":a.oClasses.sInfo,id:!c?b+"_info":null});c||(a.aoDrawCallback.push({fn:Bb,sName:"information"}),e.attr("role","status").attr("aria-live","polite"),h(a.nTable).attr("aria-describedby",b+"_info"));return e[0]}function Bb(a){var b= a.aanFeatures.i;if(0!==b.length){var c=a.oLanguage,e=a._iDisplayStart+1,d=a.fnDisplayEnd(),f=a.fnRecordsTotal(),g=a.fnRecordsDisplay(),j=g?c.sInfo:c.sInfoEmpty;g!==f&&(j+=" "+c.sInfoFiltered);j+=c.sInfoPostFix;j=Cb(a,j);c=c.fnInfoCallback;null!==c&&(j=c.call(a.oInstance,a,e,d,f,g,j));h(b).html(j)}}function Cb(a,b){var c=a.fnFormatNumber,e=a._iDisplayStart+1,d=a._iDisplayLength,f=a.fnRecordsDisplay(),g=-1===d;return b.replace(/_START_/g,c.call(a,e)).replace(/_END_/g,c.call(a,a.fnDisplayEnd())).replace(/_MAX_/g, c.call(a,a.fnRecordsTotal())).replace(/_TOTAL_/g,c.call(a,f)).replace(/_PAGE_/g,c.call(a,g?1:Math.ceil(e/d))).replace(/_PAGES_/g,c.call(a,g?1:Math.ceil(f/d)))}function ga(a){var b,c,e=a.iInitDisplayStart,d=a.aoColumns,f;c=a.oFeatures;if(a.bInitialised){mb(a);jb(a);ea(a,a.aoHeader);ea(a,a.aoFooter);C(a,!0);c.bAutoWidth&&Ga(a);b=0;for(c=d.length;b<c;b++)f=d[b],f.sWidth&&(f.nTh.style.width=s(f.sWidth));N(a);d=B(a);"ssp"!=d&&("ajax"==d?ra(a,[],function(c){var f=sa(a,c);for(b=0;b<f.length;b++)K(a,f[b]); a.iInitDisplayStart=e;N(a);C(a,!1);ta(a,c)},a):(C(a,!1),ta(a)))}else setTimeout(function(){ga(a)},200)}function ta(a,b){a._bInitComplete=!0;b&&X(a);w(a,"aoInitComplete","init",[a,b])}function Ra(a,b){var c=parseInt(b,10);a._iDisplayLength=c;Sa(a);w(a,null,"length",[a,c])}function nb(a){for(var b=a.oClasses,c=a.sTableId,e=a.aLengthMenu,d=h.isArray(e[0]),f=d?e[0]:e,e=d?e[1]:e,d=h("<select/>",{name:c+"_length","aria-controls":c,"class":b.sLengthSelect}),g=0,j=f.length;g<j;g++)d[0][g]=new Option(e[g], f[g]);var i=h("<div><label/></div>").addClass(b.sLength);a.aanFeatures.l||(i[0].id=c+"_length");i.children().append(a.oLanguage.sLengthMenu.replace("_MENU_",d[0].outerHTML));h("select",i).val(a._iDisplayLength).bind("change.DT",function(){Ra(a,h(this).val());M(a)});h(a.nTable).bind("length.dt.DT",function(b,c,f){a===c&&h("select",i).val(f)});return i[0]}function sb(a){var b=a.sPaginationType,c=m.ext.pager[b],e="function"===typeof c,d=function(a){M(a)},b=h("<div/>").addClass(a.oClasses.sPaging+b)[0], f=a.aanFeatures;e||c.fnInit(a,b,d);f.p||(b.id=a.sTableId+"_paginate",a.aoDrawCallback.push({fn:function(a){if(e){var b=a._iDisplayStart,i=a._iDisplayLength,h=a.fnRecordsDisplay(),l=-1===i,b=l?0:Math.ceil(b/i),i=l?1:Math.ceil(h/i),h=c(b,i),q,l=0;for(q=f.p.length;l<q;l++)Pa(a,"pageButton")(a,f.p[l],l,h,b,i)}else c.fnUpdate(a,d)},sName:"pagination"}));return b}function Ta(a,b,c){var e=a._iDisplayStart,d=a._iDisplayLength,f=a.fnRecordsDisplay();0===f||-1===d?e=0:"number"===typeof b?(e=b*d,e>f&&(e=0)): "first"==b?e=0:"previous"==b?(e=0<=d?e-d:0,0>e&&(e=0)):"next"==b?e+d<f&&(e+=d):"last"==b?e=Math.floor((f-1)/d)*d:I(a,0,"Unknown paging action: "+b,5);b=a._iDisplayStart!==e;a._iDisplayStart=e;b&&(w(a,null,"page",[a]),c&&M(a));return b}function pb(a){return h("<div/>",{id:!a.aanFeatures.r?a.sTableId+"_processing":null,"class":a.oClasses.sProcessing}).html(a.oLanguage.sProcessing).insertBefore(a.nTable)[0]}function C(a,b){a.oFeatures.bProcessing&&h(a.aanFeatures.r).css("display",b?"block":"none");w(a, null,"processing",[a,b])}function qb(a){var b=h(a.nTable);b.attr("role","grid");var c=a.oScroll;if(""===c.sX&&""===c.sY)return a.nTable;var e=c.sX,d=c.sY,f=a.oClasses,g=b.children("caption"),j=g.length?g[0]._captionSide:null,i=h(b[0].cloneNode(!1)),o=h(b[0].cloneNode(!1)),l=b.children("tfoot");c.sX&&"100%"===b.attr("width")&&b.removeAttr("width");l.length||(l=null);c=h("<div/>",{"class":f.sScrollWrapper}).append(h("<div/>",{"class":f.sScrollHead}).css({overflow:"hidden",position:"relative",border:0, width:e?!e?null:s(e):"100%"}).append(h("<div/>",{"class":f.sScrollHeadInner}).css({"box-sizing":"content-box",width:c.sXInner||"100%"}).append(i.removeAttr("id").css("margin-left",0).append("top"===j?g:null).append(b.children("thead"))))).append(h("<div/>",{"class":f.sScrollBody}).css({overflow:"auto",height:!d?null:s(d),width:!e?null:s(e)}).append(b));l&&c.append(h("<div/>",{"class":f.sScrollFoot}).css({overflow:"hidden",border:0,width:e?!e?null:s(e):"100%"}).append(h("<div/>",{"class":f.sScrollFootInner}).append(o.removeAttr("id").css("margin-left", 0).append("bottom"===j?g:null).append(b.children("tfoot")))));var b=c.children(),q=b[0],f=b[1],n=l?b[2]:null;if(e)h(f).on("scroll.DT",function(){var a=this.scrollLeft;q.scrollLeft=a;l&&(n.scrollLeft=a)});a.nScrollHead=q;a.nScrollBody=f;a.nScrollFoot=n;a.aoDrawCallback.push({fn:Y,sName:"scrolling"});return c[0]}function Y(a){var b=a.oScroll,c=b.sX,e=b.sXInner,d=b.sY,f=b.iBarWidth,g=h(a.nScrollHead),j=g[0].style,i=g.children("div"),o=i[0].style,l=i.children("table"),i=a.nScrollBody,q=h(i),n=i.style, k=h(a.nScrollFoot).children("div"),p=k.children("table"),m=h(a.nTHead),r=h(a.nTable),t=r[0],O=t.style,L=a.nTFoot?h(a.nTFoot):null,ha=a.oBrowser,w=ha.bScrollOversize,v,u,y,x,z,A=[],B=[],C=[],D,E=function(a){a=a.style;a.paddingTop="0";a.paddingBottom="0";a.borderTopWidth="0";a.borderBottomWidth="0";a.height=0};r.children("thead, tfoot").remove();z=m.clone().prependTo(r);v=m.find("tr");y=z.find("tr");z.find("th, td").removeAttr("tabindex");L&&(x=L.clone().prependTo(r),u=L.find("tr"),x=x.find("tr")); c||(n.width="100%",g[0].style.width="100%");h.each(qa(a,z),function(b,c){D=la(a,b);c.style.width=a.aoColumns[D].sWidth});L&&G(function(a){a.style.width=""},x);b.bCollapse&&""!==d&&(n.height=q[0].offsetHeight+m[0].offsetHeight+"px");g=r.outerWidth();if(""===c){if(O.width="100%",w&&(r.find("tbody").height()>i.offsetHeight||"scroll"==q.css("overflow-y")))O.width=s(r.outerWidth()-f)}else""!==e?O.width=s(e):g==q.width()&&q.height()<r.height()?(O.width=s(g-f),r.outerWidth()>g-f&&(O.width=s(g))):O.width= s(g);g=r.outerWidth();G(E,y);G(function(a){C.push(a.innerHTML);A.push(s(h(a).css("width")))},y);G(function(a,b){a.style.width=A[b]},v);h(y).height(0);L&&(G(E,x),G(function(a){B.push(s(h(a).css("width")))},x),G(function(a,b){a.style.width=B[b]},u),h(x).height(0));G(function(a,b){a.innerHTML='<div class="dataTables_sizing" style="height:0;overflow:hidden;">'+C[b]+"</div>";a.style.width=A[b]},y);L&&G(function(a,b){a.innerHTML="";a.style.width=B[b]},x);if(r.outerWidth()<g){u=i.scrollHeight>i.offsetHeight|| "scroll"==q.css("overflow-y")?g+f:g;if(w&&(i.scrollHeight>i.offsetHeight||"scroll"==q.css("overflow-y")))O.width=s(u-f);(""===c||""!==e)&&I(a,1,"Possible column misalignment",6)}else u="100%";n.width=s(u);j.width=s(u);L&&(a.nScrollFoot.style.width=s(u));!d&&w&&(n.height=s(t.offsetHeight+f));d&&b.bCollapse&&(n.height=s(d),b=c&&t.offsetWidth>i.offsetWidth?f:0,t.offsetHeight<i.offsetHeight&&(n.height=s(t.offsetHeight+b)));b=r.outerWidth();l[0].style.width=s(b);o.width=s(b);l=r.height()>i.clientHeight|| "scroll"==q.css("overflow-y");ha="padding"+(ha.bScrollbarLeft?"Left":"Right");o[ha]=l?f+"px":"0px";L&&(p[0].style.width=s(b),k[0].style.width=s(b),k[0].style[ha]=l?f+"px":"0px");q.scroll();if((a.bSorted||a.bFiltered)&&!a._drawHold)i.scrollTop=0}function G(a,b,c){for(var e=0,d=0,f=b.length,g,j;d<f;){g=b[d].firstChild;for(j=c?c[d].firstChild:null;g;)1===g.nodeType&&(c?a(g,j,e):a(g,e),e++),g=g.nextSibling,j=c?j.nextSibling:null;d++}}function Ga(a){var b=a.nTable,c=a.aoColumns,e=a.oScroll,d=e.sY,f=e.sX, g=e.sXInner,j=c.length,e=Z(a,"bVisible"),i=h("th",a.nTHead),o=b.getAttribute("width"),l=b.parentNode,k=!1,n,m;(n=b.style.width)&&-1!==n.indexOf("%")&&(o=n);for(n=0;n<e.length;n++)m=c[e[n]],null!==m.sWidth&&(m.sWidth=Db(m.sWidthOrig,l),k=!0);if(!k&&!f&&!d&&j==aa(a)&&j==i.length)for(n=0;n<j;n++)c[n].sWidth=s(i.eq(n).width());else{j=h(b).clone().css("visibility","hidden").removeAttr("id");j.find("tbody tr").remove();var p=h("<tr/>").appendTo(j.find("tbody"));j.find("tfoot th, tfoot td").css("width", "");i=qa(a,j.find("thead")[0]);for(n=0;n<e.length;n++)m=c[e[n]],i[n].style.width=null!==m.sWidthOrig&&""!==m.sWidthOrig?s(m.sWidthOrig):"";if(a.aoData.length)for(n=0;n<e.length;n++)k=e[n],m=c[k],h(Eb(a,k)).clone(!1).append(m.sContentPadding).appendTo(p);j.appendTo(l);f&&g?j.width(g):f?(j.css("width","auto"),j.width()<l.offsetWidth&&j.width(l.offsetWidth)):d?j.width(l.offsetWidth):o&&j.width(o);Fb(a,j[0]);if(f){for(n=g=0;n<e.length;n++)m=c[e[n]],d=h(i[n]).outerWidth(),g+=null===m.sWidthOrig?d:parseInt(m.sWidth, 10)+d-h(i[n]).width();j.width(s(g));b.style.width=s(g)}for(n=0;n<e.length;n++)if(m=c[e[n]],d=h(i[n]).width())m.sWidth=s(d);b.style.width=s(j.css("width"));j.remove()}o&&(b.style.width=s(o));if((o||f)&&!a._reszEvt)b=function(){h(Ea).bind("resize.DT-"+a.sInstance,ua(function(){X(a)}))},a.oBrowser.bScrollOversize?setTimeout(b,1E3):b(),a._reszEvt=!0}function ua(a,b){var c=b!==k?b:200,e,d;return function(){var b=this,g=+new Date,j=arguments;e&&g<e+c?(clearTimeout(d),d=setTimeout(function(){e=k;a.apply(b, j)},c)):(e=g,a.apply(b,j))}}function Db(a,b){if(!a)return 0;var c=h("<div/>").css("width",s(a)).appendTo(b||Q.body),e=c[0].offsetWidth;c.remove();return e}function Fb(a,b){var c=a.oScroll;if(c.sX||c.sY)c=!c.sX?c.iBarWidth:0,b.style.width=s(h(b).outerWidth()-c)}function Eb(a,b){var c=Gb(a,b);if(0>c)return null;var e=a.aoData[c];return!e.nTr?h("<td/>").html(x(a,c,b,"display"))[0]:e.anCells[b]}function Gb(a,b){for(var c,e=-1,d=-1,f=0,g=a.aoData.length;f<g;f++)c=x(a,f,b,"display")+"",c=c.replace($b,""), c.length>e&&(e=c.length,d=f);return d}function s(a){return null===a?"0px":"number"==typeof a?0>a?"0px":a+"px":a.match(/\d$/)?a+"px":a}function Hb(){var a=m.__scrollbarWidth;if(a===k){var b=h("<p/>").css({position:"absolute",top:0,left:0,width:"100%",height:150,padding:0,overflow:"scroll",visibility:"hidden"}).appendTo("body"),a=b[0].offsetWidth-b[0].clientWidth;m.__scrollbarWidth=a;b.remove()}return a}function U(a){var b,c,e=[],d=a.aoColumns,f,g,j,i;b=a.aaSortingFixed;c=h.isPlainObject(b);var o=[]; f=function(a){a.length&&!h.isArray(a[0])?o.push(a):o.push.apply(o,a)};h.isArray(b)&&f(b);c&&b.pre&&f(b.pre);f(a.aaSorting);c&&b.post&&f(b.post);for(a=0;a<o.length;a++){i=o[a][0];f=d[i].aDataSort;b=0;for(c=f.length;b<c;b++)g=f[b],j=d[g].sType||"string",o[a]._idx===k&&(o[a]._idx=h.inArray(o[a][1],d[g].asSorting)),e.push({src:i,col:g,dir:o[a][1],index:o[a]._idx,type:j,formatter:m.ext.type.order[j+"-pre"]})}return e}function lb(a){var b,c,e=[],d=m.ext.type.order,f=a.aoData,g=0,j,i=a.aiDisplayMaster,h; Ha(a);h=U(a);b=0;for(c=h.length;b<c;b++)j=h[b],j.formatter&&g++,Ib(a,j.col);if("ssp"!=B(a)&&0!==h.length){b=0;for(c=i.length;b<c;b++)e[i[b]]=b;g===h.length?i.sort(function(a,b){var c,d,g,j,i=h.length,k=f[a]._aSortData,m=f[b]._aSortData;for(g=0;g<i;g++)if(j=h[g],c=k[j.col],d=m[j.col],c=c<d?-1:c>d?1:0,0!==c)return"asc"===j.dir?c:-c;c=e[a];d=e[b];return c<d?-1:c>d?1:0}):i.sort(function(a,b){var c,g,j,i,k=h.length,m=f[a]._aSortData,r=f[b]._aSortData;for(j=0;j<k;j++)if(i=h[j],c=m[i.col],g=r[i.col],i=d[i.type+ "-"+i.dir]||d["string-"+i.dir],c=i(c,g),0!==c)return c;c=e[a];g=e[b];return c<g?-1:c>g?1:0})}a.bSorted=!0}function Jb(a){for(var b,c,e=a.aoColumns,d=U(a),a=a.oLanguage.oAria,f=0,g=e.length;f<g;f++){c=e[f];var j=c.asSorting;b=c.sTitle.replace(/<.*?>/g,"");var i=c.nTh;i.removeAttribute("aria-sort");c.bSortable&&(0<d.length&&d[0].col==f?(i.setAttribute("aria-sort","asc"==d[0].dir?"ascending":"descending"),c=j[d[0].index+1]||j[0]):c=j[0],b+="asc"===c?a.sSortAscending:a.sSortDescending);i.setAttribute("aria-label", b)}}function Ua(a,b,c,e){var d=a.aaSorting,f=a.aoColumns[b].asSorting,g=function(a,b){var c=a._idx;c===k&&(c=h.inArray(a[1],f));return c+1<f.length?c+1:b?null:0};"number"===typeof d[0]&&(d=a.aaSorting=[d]);c&&a.oFeatures.bSortMulti?(c=h.inArray(b,D(d,"0")),-1!==c?(b=g(d[c],!0),null===b&&1===d.length&&(b=0),null===b?d.splice(c,1):(d[c][1]=f[b],d[c]._idx=b)):(d.push([b,f[0],0]),d[d.length-1]._idx=0)):d.length&&d[0][0]==b?(b=g(d[0]),d.length=1,d[0][1]=f[b],d[0]._idx=b):(d.length=0,d.push([b,f[0]]),d[0]._idx= 0);N(a);"function"==typeof e&&e(a)}function Oa(a,b,c,e){var d=a.aoColumns[c];Va(b,{},function(b){!1!==d.bSortable&&(a.oFeatures.bProcessing?(C(a,!0),setTimeout(function(){Ua(a,c,b.shiftKey,e);"ssp"!==B(a)&&C(a,!1)},0)):Ua(a,c,b.shiftKey,e))})}function xa(a){var b=a.aLastSort,c=a.oClasses.sSortColumn,e=U(a),d=a.oFeatures,f,g;if(d.bSort&&d.bSortClasses){d=0;for(f=b.length;d<f;d++)g=b[d].src,h(D(a.aoData,"anCells",g)).removeClass(c+(2>d?d+1:3));d=0;for(f=e.length;d<f;d++)g=e[d].src,h(D(a.aoData,"anCells", g)).addClass(c+(2>d?d+1:3))}a.aLastSort=e}function Ib(a,b){var c=a.aoColumns[b],e=m.ext.order[c.sSortDataType],d;e&&(d=e.call(a.oInstance,a,b,$(a,b)));for(var f,g=m.ext.type.order[c.sType+"-pre"],j=0,i=a.aoData.length;j<i;j++)if(c=a.aoData[j],c._aSortData||(c._aSortData=[]),!c._aSortData[b]||e)f=e?d[j]:x(a,j,b,"sort"),c._aSortData[b]=g?g(f):f}function ya(a){if(a.oFeatures.bStateSave&&!a.bDestroying){var b={time:+new Date,start:a._iDisplayStart,length:a._iDisplayLength,order:h.extend(!0,[],a.aaSorting), search:zb(a.oPreviousSearch),columns:h.map(a.aoColumns,function(b,e){return{visible:b.bVisible,search:zb(a.aoPreSearchCols[e])}})};w(a,"aoStateSaveParams","stateSaveParams",[a,b]);a.oSavedState=b;a.fnStateSaveCallback.call(a.oInstance,a,b)}}function Kb(a){var b,c,e=a.aoColumns;if(a.oFeatures.bStateSave){var d=a.fnStateLoadCallback.call(a.oInstance,a);if(d&&d.time&&(b=w(a,"aoStateLoadParams","stateLoadParams",[a,d]),-1===h.inArray(!1,b)&&(b=a.iStateDuration,!(0<b&&d.time<+new Date-1E3*b)&&e.length=== d.columns.length))){a.oLoadedState=h.extend(!0,{},d);d.start!==k&&(a._iDisplayStart=d.start,a.iInitDisplayStart=d.start);d.length!==k&&(a._iDisplayLength=d.length);d.order!==k&&(a.aaSorting=[],h.each(d.order,function(b,c){a.aaSorting.push(c[0]>=e.length?[0,c[1]]:c)}));d.search!==k&&h.extend(a.oPreviousSearch,Ab(d.search));b=0;for(c=d.columns.length;b<c;b++){var f=d.columns[b];f.visible!==k&&(e[b].bVisible=f.visible);f.search!==k&&h.extend(a.aoPreSearchCols[b],Ab(f.search))}w(a,"aoStateLoaded","stateLoaded", [a,d])}}}function za(a){var b=m.settings,a=h.inArray(a,D(b,"nTable"));return-1!==a?b[a]:null}function I(a,b,c,e){c="DataTables warning: "+(null!==a?"table id="+a.sTableId+" - ":"")+c;e&&(c+=". For more information about this error, please see http://datatables.net/tn/"+e);if(b)Ea.console&&console.log&&console.log(c);else if(b=m.ext,b=b.sErrMode||b.errMode,w(a,null,"error",[a,e,c]),"alert"==b)alert(c);else{if("throw"==b)throw Error(c);"function"==typeof b&&b(a,e,c)}}function E(a,b,c,e){h.isArray(c)? h.each(c,function(c,f){h.isArray(f)?E(a,b,f[0],f[1]):E(a,b,f)}):(e===k&&(e=c),b[c]!==k&&(a[e]=b[c]))}function Lb(a,b,c){var e,d;for(d in b)b.hasOwnProperty(d)&&(e=b[d],h.isPlainObject(e)?(h.isPlainObject(a[d])||(a[d]={}),h.extend(!0,a[d],e)):a[d]=c&&"data"!==d&&"aaData"!==d&&h.isArray(e)?e.slice():e);return a}function Va(a,b,c){h(a).bind("click.DT",b,function(b){a.blur();c(b)}).bind("keypress.DT",b,function(a){13===a.which&&(a.preventDefault(),c(a))}).bind("selectstart.DT",function(){return!1})}function z(a, b,c,e){c&&a[b].push({fn:c,sName:e})}function w(a,b,c,e){var d=[];b&&(d=h.map(a[b].slice().reverse(),function(b){return b.fn.apply(a.oInstance,e)}));null!==c&&(b=h.Event(c+".dt"),h(a.nTable).trigger(b,e),d.push(b.result));return d}function Sa(a){var b=a._iDisplayStart,c=a.fnDisplayEnd(),e=a._iDisplayLength;b>=c&&(b=c-e);b-=b%e;if(-1===e||0>b)b=0;a._iDisplayStart=b}function Pa(a,b){var c=a.renderer,e=m.ext.renderer[b];return h.isPlainObject(c)&&c[b]?e[c[b]]||e._:"string"===typeof c?e[c]||e._:e._}function B(a){return a.oFeatures.bServerSide? "ssp":a.ajax||a.sAjaxSource?"ajax":"dom"}function Wa(a,b){var c=[],c=Mb.numbers_length,e=Math.floor(c/2);b<=c?c=V(0,b):a<=e?(c=V(0,c-2),c.push("ellipsis"),c.push(b-1)):(a>=b-1-e?c=V(b-(c-2),b):(c=V(a-e+2,a+e-1),c.push("ellipsis"),c.push(b-1)),c.splice(0,0,"ellipsis"),c.splice(0,0,0));c.DT_el="span";return c}function db(a){h.each({num:function(b){return Aa(b,a)},"num-fmt":function(b){return Aa(b,a,Xa)},"html-num":function(b){return Aa(b,a,Ba)},"html-num-fmt":function(b){return Aa(b,a,Ba,Xa)}},function(b, c){u.type.order[b+a+"-pre"]=c;b.match(/^html\-/)&&(u.type.search[b+a]=u.type.search.html)})}function Nb(a){return function(){var b=[za(this[m.ext.iApiIndex])].concat(Array.prototype.slice.call(arguments));return m.ext.internal[a].apply(this,b)}}var m,u,t,r,v,Ya={},Ob=/[\r\n]/g,Ba=/<.*?>/g,ac=/^[\w\+\-]/,bc=/[\w\+\-]$/,Yb=RegExp("(\\/|\\.|\\*|\\+|\\?|\\||\\(|\\)|\\[|\\]|\\{|\\}|\\\\|\\$|\\^|\\-)","g"),Xa=/[',$\u00a3\u20ac\u00a5%\u2009\u202F\u20BD\u20a9\u20BArfk]/gi,J=function(a){return!a||!0===a|| "-"===a?!0:!1},Pb=function(a){var b=parseInt(a,10);return!isNaN(b)&&isFinite(a)?b:null},Qb=function(a,b){Ya[b]||(Ya[b]=RegExp(va(b),"g"));return"string"===typeof a&&"."!==b?a.replace(/\./g,"").replace(Ya[b],"."):a},Za=function(a,b,c){var e="string"===typeof a;if(J(a))return!0;b&&e&&(a=Qb(a,b));c&&e&&(a=a.replace(Xa,""));return!isNaN(parseFloat(a))&&isFinite(a)},Rb=function(a,b,c){return J(a)?!0:!(J(a)||"string"===typeof a)?null:Za(a.replace(Ba,""),b,c)?!0:null},D=function(a,b,c){var e=[],d=0,f=a.length; if(c!==k)for(;d<f;d++)a[d]&&a[d][b]&&e.push(a[d][b][c]);else for(;d<f;d++)a[d]&&e.push(a[d][b]);return e},ia=function(a,b,c,e){var d=[],f=0,g=b.length;if(e!==k)for(;f<g;f++)a[b[f]][c]&&d.push(a[b[f]][c][e]);else for(;f<g;f++)d.push(a[b[f]][c]);return d},V=function(a,b){var c=[],e;b===k?(b=0,e=a):(e=b,b=a);for(var d=b;d<e;d++)c.push(d);return c},Sb=function(a){for(var b=[],c=0,e=a.length;c<e;c++)a[c]&&b.push(a[c]);return b},Na=function(a){var b=[],c,e,d=a.length,f,g=0;e=0;a:for(;e<d;e++){c=a[e];for(f= 0;f<g;f++)if(b[f]===c)continue a;b.push(c);g++}return b},A=function(a,b,c){a[b]!==k&&(a[c]=a[b])},ba=/\[.*?\]$/,T=/\(\)$/,wa=h("<div>")[0],Zb=wa.textContent!==k,$b=/<.*?>/g;m=function(a){this.$=function(a,b){return this.api(!0).$(a,b)};this._=function(a,b){return this.api(!0).rows(a,b).data()};this.api=function(a){return a?new t(za(this[u.iApiIndex])):new t(this)};this.fnAddData=function(a,b){var c=this.api(!0),e=h.isArray(a)&&(h.isArray(a[0])||h.isPlainObject(a[0]))?c.rows.add(a):c.row.add(a);(b=== k||b)&&c.draw();return e.flatten().toArray()};this.fnAdjustColumnSizing=function(a){var b=this.api(!0).columns.adjust(),c=b.settings()[0],e=c.oScroll;a===k||a?b.draw(!1):(""!==e.sX||""!==e.sY)&&Y(c)};this.fnClearTable=function(a){var b=this.api(!0).clear();(a===k||a)&&b.draw()};this.fnClose=function(a){this.api(!0).row(a).child.hide()};this.fnDeleteRow=function(a,b,c){var e=this.api(!0),a=e.rows(a),d=a.settings()[0],h=d.aoData[a[0][0]];a.remove();b&&b.call(this,d,h);(c===k||c)&&e.draw();return h}; this.fnDestroy=function(a){this.api(!0).destroy(a)};this.fnDraw=function(a){this.api(!0).draw(a)};this.fnFilter=function(a,b,c,e,d,h){d=this.api(!0);null===b||b===k?d.search(a,c,e,h):d.column(b).search(a,c,e,h);d.draw()};this.fnGetData=function(a,b){var c=this.api(!0);if(a!==k){var e=a.nodeName?a.nodeName.toLowerCase():"";return b!==k||"td"==e||"th"==e?c.cell(a,b).data():c.row(a).data()||null}return c.data().toArray()};this.fnGetNodes=function(a){var b=this.api(!0);return a!==k?b.row(a).node():b.rows().nodes().flatten().toArray()}; this.fnGetPosition=function(a){var b=this.api(!0),c=a.nodeName.toUpperCase();return"TR"==c?b.row(a).index():"TD"==c||"TH"==c?(a=b.cell(a).index(),[a.row,a.columnVisible,a.column]):null};this.fnIsOpen=function(a){return this.api(!0).row(a).child.isShown()};this.fnOpen=function(a,b,c){return this.api(!0).row(a).child(b,c).show().child()[0]};this.fnPageChange=function(a,b){var c=this.api(!0).page(a);(b===k||b)&&c.draw(!1)};this.fnSetColumnVis=function(a,b,c){a=this.api(!0).column(a).visible(b);(c=== k||c)&&a.columns.adjust().draw()};this.fnSettings=function(){return za(this[u.iApiIndex])};this.fnSort=function(a){this.api(!0).order(a).draw()};this.fnSortListener=function(a,b,c){this.api(!0).order.listener(a,b,c)};this.fnUpdate=function(a,b,c,e,d){var h=this.api(!0);c===k||null===c?h.row(b).data(a):h.cell(b,c).data(a);(d===k||d)&&h.columns.adjust();(e===k||e)&&h.draw();return 0};this.fnVersionCheck=u.fnVersionCheck;var b=this,c=a===k,e=this.length;c&&(a={});this.oApi=this.internal=u.internal;for(var d in m.ext.internal)d&& (this[d]=Nb(d));this.each(function(){var d={},d=1<e?Lb(d,a,!0):a,g=0,j,i=this.getAttribute("id"),o=!1,l=m.defaults,q=h(this);if("table"!=this.nodeName.toLowerCase())I(null,0,"Non-table node initialisation ("+this.nodeName+")",2);else{eb(l);fb(l.column);H(l,l,!0);H(l.column,l.column,!0);H(l,h.extend(d,q.data()));var n=m.settings,g=0;for(j=n.length;g<j;g++){var r=n[g];if(r.nTable==this||r.nTHead.parentNode==this||r.nTFoot&&r.nTFoot.parentNode==this){g=d.bRetrieve!==k?d.bRetrieve:l.bRetrieve;if(c||g)return r.oInstance; if(d.bDestroy!==k?d.bDestroy:l.bDestroy){r.oInstance.fnDestroy();break}else{I(r,0,"Cannot reinitialise DataTable",3);return}}if(r.sTableId==this.id){n.splice(g,1);break}}if(null===i||""===i)this.id=i="DataTables_Table_"+m.ext._unique++;var p=h.extend(!0,{},m.models.oSettings,{sDestroyWidth:q[0].style.width,sInstance:i,sTableId:i});p.nTable=this;p.oApi=b.internal;p.oInit=d;n.push(p);p.oInstance=1===b.length?b:q.dataTable();eb(d);d.oLanguage&&P(d.oLanguage);d.aLengthMenu&&!d.iDisplayLength&&(d.iDisplayLength= h.isArray(d.aLengthMenu[0])?d.aLengthMenu[0][0]:d.aLengthMenu[0]);d=Lb(h.extend(!0,{},l),d);E(p.oFeatures,d,"bPaginate bLengthChange bFilter bSort bSortMulti bInfo bProcessing bAutoWidth bSortClasses bServerSide bDeferRender".split(" "));E(p,d,["asStripeClasses","ajax","fnServerData","fnFormatNumber","sServerMethod","aaSorting","aaSortingFixed","aLengthMenu","sPaginationType","sAjaxSource","sAjaxDataProp","iStateDuration","sDom","bSortCellsTop","iTabIndex","fnStateLoadCallback","fnStateSaveCallback", "renderer","searchDelay",["iCookieDuration","iStateDuration"],["oSearch","oPreviousSearch"],["aoSearchCols","aoPreSearchCols"],["iDisplayLength","_iDisplayLength"],["bJQueryUI","bJUI"]]);E(p.oScroll,d,[["sScrollX","sX"],["sScrollXInner","sXInner"],["sScrollY","sY"],["bScrollCollapse","bCollapse"]]);E(p.oLanguage,d,"fnInfoCallback");z(p,"aoDrawCallback",d.fnDrawCallback,"user");z(p,"aoServerParams",d.fnServerParams,"user");z(p,"aoStateSaveParams",d.fnStateSaveParams,"user");z(p,"aoStateLoadParams", d.fnStateLoadParams,"user");z(p,"aoStateLoaded",d.fnStateLoaded,"user");z(p,"aoRowCallback",d.fnRowCallback,"user");z(p,"aoRowCreatedCallback",d.fnCreatedRow,"user");z(p,"aoHeaderCallback",d.fnHeaderCallback,"user");z(p,"aoFooterCallback",d.fnFooterCallback,"user");z(p,"aoInitComplete",d.fnInitComplete,"user");z(p,"aoPreDrawCallback",d.fnPreDrawCallback,"user");i=p.oClasses;d.bJQueryUI?(h.extend(i,m.ext.oJUIClasses,d.oClasses),d.sDom===l.sDom&&"lfrtip"===l.sDom&&(p.sDom='<"H"lfr>t<"F"ip>'),p.renderer)? h.isPlainObject(p.renderer)&&!p.renderer.header&&(p.renderer.header="jqueryui"):p.renderer="jqueryui":h.extend(i,m.ext.classes,d.oClasses);q.addClass(i.sTable);if(""!==p.oScroll.sX||""!==p.oScroll.sY)p.oScroll.iBarWidth=Hb();!0===p.oScroll.sX&&(p.oScroll.sX="100%");p.iInitDisplayStart===k&&(p.iInitDisplayStart=d.iDisplayStart,p._iDisplayStart=d.iDisplayStart);null!==d.iDeferLoading&&(p.bDeferLoading=!0,g=h.isArray(d.iDeferLoading),p._iRecordsDisplay=g?d.iDeferLoading[0]:d.iDeferLoading,p._iRecordsTotal= g?d.iDeferLoading[1]:d.iDeferLoading);var t=p.oLanguage;h.extend(!0,t,d.oLanguage);""!==t.sUrl&&(h.ajax({dataType:"json",url:t.sUrl,success:function(a){P(a);H(l.oLanguage,a);h.extend(true,t,a);ga(p)},error:function(){ga(p)}}),o=!0);null===d.asStripeClasses&&(p.asStripeClasses=[i.sStripeOdd,i.sStripeEven]);var g=p.asStripeClasses,s=q.children("tbody").find("tr").eq(0);-1!==h.inArray(!0,h.map(g,function(a){return s.hasClass(a)}))&&(h("tbody tr",this).removeClass(g.join(" ")),p.asDestroyStripes=g.slice()); n=[];g=this.getElementsByTagName("thead");0!==g.length&&(da(p.aoHeader,g[0]),n=qa(p));if(null===d.aoColumns){r=[];g=0;for(j=n.length;g<j;g++)r.push(null)}else r=d.aoColumns;g=0;for(j=r.length;g<j;g++)Fa(p,n?n[g]:null);ib(p,d.aoColumnDefs,r,function(a,b){ka(p,a,b)});if(s.length){var u=function(a,b){return a.getAttribute("data-"+b)!==null?b:null};h.each(na(p,s[0]).cells,function(a,b){var c=p.aoColumns[a];if(c.mData===a){var d=u(b,"sort")||u(b,"order"),e=u(b,"filter")||u(b,"search");if(d!==null||e!== null){c.mData={_:a+".display",sort:d!==null?a+".@data-"+d:k,type:d!==null?a+".@data-"+d:k,filter:e!==null?a+".@data-"+e:k};ka(p,a)}}})}var v=p.oFeatures;d.bStateSave&&(v.bStateSave=!0,Kb(p,d),z(p,"aoDrawCallback",ya,"state_save"));if(d.aaSorting===k){n=p.aaSorting;g=0;for(j=n.length;g<j;g++)n[g][1]=p.aoColumns[g].asSorting[0]}xa(p);v.bSort&&z(p,"aoDrawCallback",function(){if(p.bSorted){var a=U(p),b={};h.each(a,function(a,c){b[c.src]=c.dir});w(p,null,"order",[p,a,b]);Jb(p)}});z(p,"aoDrawCallback", function(){(p.bSorted||B(p)==="ssp"||v.bDeferRender)&&xa(p)},"sc");gb(p);g=q.children("caption").each(function(){this._captionSide=q.css("caption-side")});j=q.children("thead");0===j.length&&(j=h("<thead/>").appendTo(this));p.nTHead=j[0];j=q.children("tbody");0===j.length&&(j=h("<tbody/>").appendTo(this));p.nTBody=j[0];j=q.children("tfoot");if(0===j.length&&0<g.length&&(""!==p.oScroll.sX||""!==p.oScroll.sY))j=h("<tfoot/>").appendTo(this);0===j.length||0===j.children().length?q.addClass(i.sNoFooter): 0<j.length&&(p.nTFoot=j[0],da(p.aoFooter,p.nTFoot));if(d.aaData)for(g=0;g<d.aaData.length;g++)K(p,d.aaData[g]);else(p.bDeferLoading||"dom"==B(p))&&ma(p,h(p.nTBody).children("tr"));p.aiDisplay=p.aiDisplayMaster.slice();p.bInitialised=!0;!1===o&&ga(p)}});b=null;return this};var Tb=[],y=Array.prototype,cc=function(a){var b,c,e=m.settings,d=h.map(e,function(a){return a.nTable});if(a){if(a.nTable&&a.oApi)return[a];if(a.nodeName&&"table"===a.nodeName.toLowerCase())return b=h.inArray(a,d),-1!==b?[e[b]]: null;if(a&&"function"===typeof a.settings)return a.settings().toArray();"string"===typeof a?c=h(a):a instanceof h&&(c=a)}else return[];if(c)return c.map(function(){b=h.inArray(this,d);return-1!==b?e[b]:null}).toArray()};t=function(a,b){if(!(this instanceof t))return new t(a,b);var c=[],e=function(a){(a=cc(a))&&c.push.apply(c,a)};if(h.isArray(a))for(var d=0,f=a.length;d<f;d++)e(a[d]);else e(a);this.context=Na(c);b&&this.push.apply(this,b.toArray?b.toArray():b);this.selector={rows:null,cols:null,opts:null}; t.extend(this,this,Tb)};m.Api=t;t.prototype={any:function(){return 0!==this.flatten().length},concat:y.concat,context:[],each:function(a){for(var b=0,c=this.length;b<c;b++)a.call(this,this[b],b,this);return this},eq:function(a){var b=this.context;return b.length>a?new t(b[a],this[a]):null},filter:function(a){var b=[];if(y.filter)b=y.filter.call(this,a,this);else for(var c=0,e=this.length;c<e;c++)a.call(this,this[c],c,this)&&b.push(this[c]);return new t(this.context,b)},flatten:function(){var a=[]; return new t(this.context,a.concat.apply(a,this.toArray()))},join:y.join,indexOf:y.indexOf||function(a,b){for(var c=b||0,e=this.length;c<e;c++)if(this[c]===a)return c;return-1},iterator:function(a,b,c,e){var d=[],f,g,h,i,o,l=this.context,q,n,m=this.selector;"string"===typeof a&&(e=c,c=b,b=a,a=!1);g=0;for(h=l.length;g<h;g++){var p=new t(l[g]);if("table"===b)f=c.call(p,l[g],g),f!==k&&d.push(f);else if("columns"===b||"rows"===b)f=c.call(p,l[g],this[g],g),f!==k&&d.push(f);else if("column"===b||"column-rows"=== b||"row"===b||"cell"===b){n=this[g];"column-rows"===b&&(q=Ca(l[g],m.opts));i=0;for(o=n.length;i<o;i++)f=n[i],f="cell"===b?c.call(p,l[g],f.row,f.column,g,i):c.call(p,l[g],f,g,i,q),f!==k&&d.push(f)}}return d.length||e?(a=new t(l,a?d.concat.apply([],d):d),b=a.selector,b.rows=m.rows,b.cols=m.cols,b.opts=m.opts,a):this},lastIndexOf:y.lastIndexOf||function(a,b){return this.indexOf.apply(this.toArray.reverse(),arguments)},length:0,map:function(a){var b=[];if(y.map)b=y.map.call(this,a,this);else for(var c= 0,e=this.length;c<e;c++)b.push(a.call(this,this[c],c));return new t(this.context,b)},pluck:function(a){return this.map(function(b){return b[a]})},pop:y.pop,push:y.push,reduce:y.reduce||function(a,b){return hb(this,a,b,0,this.length,1)},reduceRight:y.reduceRight||function(a,b){return hb(this,a,b,this.length-1,-1,-1)},reverse:y.reverse,selector:null,shift:y.shift,sort:y.sort,splice:y.splice,toArray:function(){return y.slice.call(this)},to$:function(){return h(this)},toJQuery:function(){return h(this)}, unique:function(){return new t(this.context,Na(this))},unshift:y.unshift};t.extend=function(a,b,c){if(c.length&&b&&(b instanceof t||b.__dt_wrapper)){var e,d,f,g=function(a,b,c){return function(){var d=b.apply(a,arguments);t.extend(d,d,c.methodExt);return d}};e=0;for(d=c.length;e<d;e++)f=c[e],b[f.name]="function"===typeof f.val?g(a,f.val,f):h.isPlainObject(f.val)?{}:f.val,b[f.name].__dt_wrapper=!0,t.extend(a,b[f.name],f.propExt)}};t.register=r=function(a,b){if(h.isArray(a))for(var c=0,e=a.length;c< e;c++)t.register(a[c],b);else for(var d=a.split("."),f=Tb,g,j,c=0,e=d.length;c<e;c++){g=(j=-1!==d[c].indexOf("()"))?d[c].replace("()",""):d[c];var i;a:{i=0;for(var o=f.length;i<o;i++)if(f[i].name===g){i=f[i];break a}i=null}i||(i={name:g,val:{},methodExt:[],propExt:[]},f.push(i));c===e-1?i.val=b:f=j?i.methodExt:i.propExt}};t.registerPlural=v=function(a,b,c){t.register(a,c);t.register(b,function(){var a=c.apply(this,arguments);return a===this?this:a instanceof t?a.length?h.isArray(a[0])?new t(a.context, a[0]):a[0]:k:a})};r("tables()",function(a){var b;if(a){b=t;var c=this.context;if("number"===typeof a)a=[c[a]];else var e=h.map(c,function(a){return a.nTable}),a=h(e).filter(a).map(function(){var a=h.inArray(this,e);return c[a]}).toArray();b=new b(a)}else b=this;return b});r("table()",function(a){var a=this.tables(a),b=a.context;return b.length?new t(b[0]):a});v("tables().nodes()","table().node()",function(){return this.iterator("table",function(a){return a.nTable},1)});v("tables().body()","table().body()", function(){return this.iterator("table",function(a){return a.nTBody},1)});v("tables().header()","table().header()",function(){return this.iterator("table",function(a){return a.nTHead},1)});v("tables().footer()","table().footer()",function(){return this.iterator("table",function(a){return a.nTFoot},1)});v("tables().containers()","table().container()",function(){return this.iterator("table",function(a){return a.nTableWrapper},1)});r("draw()",function(a){return this.iterator("table",function(b){N(b, !1===a)})});r("page()",function(a){return a===k?this.page.info().page:this.iterator("table",function(b){Ta(b,a)})});r("page.info()",function(){if(0===this.context.length)return k;var a=this.context[0],b=a._iDisplayStart,c=a._iDisplayLength,e=a.fnRecordsDisplay(),d=-1===c;return{page:d?0:Math.floor(b/c),pages:d?1:Math.ceil(e/c),start:b,end:a.fnDisplayEnd(),length:c,recordsTotal:a.fnRecordsTotal(),recordsDisplay:e}});r("page.len()",function(a){return a===k?0!==this.context.length?this.context[0]._iDisplayLength: k:this.iterator("table",function(b){Ra(b,a)})});var Ub=function(a,b,c){if(c){var e=new t(a);e.one("draw",function(){c(e.ajax.json())})}"ssp"==B(a)?N(a,b):(C(a,!0),ra(a,[],function(c){oa(a);for(var c=sa(a,c),e=0,g=c.length;e<g;e++)K(a,c[e]);N(a,b);C(a,!1)}))};r("ajax.json()",function(){var a=this.context;if(0<a.length)return a[0].json});r("ajax.params()",function(){var a=this.context;if(0<a.length)return a[0].oAjaxData});r("ajax.reload()",function(a,b){return this.iterator("table",function(c){Ub(c, !1===b,a)})});r("ajax.url()",function(a){var b=this.context;if(a===k){if(0===b.length)return k;b=b[0];return b.ajax?h.isPlainObject(b.ajax)?b.ajax.url:b.ajax:b.sAjaxSource}return this.iterator("table",function(b){h.isPlainObject(b.ajax)?b.ajax.url=a:b.ajax=a})});r("ajax.url().load()",function(a,b){return this.iterator("table",function(c){Ub(c,!1===b,a)})});var $a=function(a,b,c,e,d){var f=[],g,j,i,o,l,q;i=typeof b;if(!b||"string"===i||"function"===i||b.length===k)b=[b];i=0;for(o=b.length;i<o;i++){j= b[i]&&b[i].split?b[i].split(","):[b[i]];l=0;for(q=j.length;l<q;l++)(g=c("string"===typeof j[l]?h.trim(j[l]):j[l]))&&g.length&&f.push.apply(f,g)}a=u.selector[a];if(a.length){i=0;for(o=a.length;i<o;i++)f=a[i](e,d,f)}return f},ab=function(a){a||(a={});a.filter&&a.search===k&&(a.search=a.filter);return h.extend({search:"none",order:"current",page:"all"},a)},bb=function(a){for(var b=0,c=a.length;b<c;b++)if(0<a[b].length)return a[0]=a[b],a[0].length=1,a.length=1,a.context=[a.context[b]],a;a.length=0;return a}, Ca=function(a,b){var c,e,d,f=[],g=a.aiDisplay;c=a.aiDisplayMaster;var j=b.search;e=b.order;d=b.page;if("ssp"==B(a))return"removed"===j?[]:V(0,c.length);if("current"==d){c=a._iDisplayStart;for(e=a.fnDisplayEnd();c<e;c++)f.push(g[c])}else if("current"==e||"applied"==e)f="none"==j?c.slice():"applied"==j?g.slice():h.map(c,function(a){return-1===h.inArray(a,g)?a:null});else if("index"==e||"original"==e){c=0;for(e=a.aoData.length;c<e;c++)"none"==j?f.push(c):(d=h.inArray(c,g),(-1===d&&"removed"==j||0<=d&& "applied"==j)&&f.push(c))}return f};r("rows()",function(a,b){a===k?a="":h.isPlainObject(a)&&(b=a,a="");var b=ab(b),c=this.iterator("table",function(c){var d=b;return $a("row",a,function(a){var b=Pb(a);if(b!==null&&!d)return[b];var j=Ca(c,d);if(b!==null&&h.inArray(b,j)!==-1)return[b];if(!a)return j;if(typeof a==="function")return h.map(j,function(b){var d=c.aoData[b];return a(b,d._aData,d.nTr)?b:null});b=Sb(ia(c.aoData,j,"nTr"));return a.nodeName&&h.inArray(a,b)!==-1?[a._DT_RowIndex]:h(b).filter(a).map(function(){return this._DT_RowIndex}).toArray()}, c,d)},1);c.selector.rows=a;c.selector.opts=b;return c});r("rows().nodes()",function(){return this.iterator("row",function(a,b){return a.aoData[b].nTr||k},1)});r("rows().data()",function(){return this.iterator(!0,"rows",function(a,b){return ia(a.aoData,b,"_aData")},1)});v("rows().cache()","row().cache()",function(a){return this.iterator("row",function(b,c){var e=b.aoData[c];return"search"===a?e._aFilterData:e._aSortData},1)});v("rows().invalidate()","row().invalidate()",function(a){return this.iterator("row", function(b,c){ca(b,c,a)})});v("rows().indexes()","row().index()",function(){return this.iterator("row",function(a,b){return b},1)});v("rows().remove()","row().remove()",function(){var a=this;return this.iterator("row",function(b,c,e){var d=b.aoData;d.splice(c,1);for(var f=0,g=d.length;f<g;f++)null!==d[f].nTr&&(d[f].nTr._DT_RowIndex=f);h.inArray(c,b.aiDisplay);pa(b.aiDisplayMaster,c);pa(b.aiDisplay,c);pa(a[e],c,!1);Sa(b)})});r("rows.add()",function(a){var b=this.iterator("table",function(b){var c, f,g,h=[];f=0;for(g=a.length;f<g;f++)c=a[f],c.nodeName&&"TR"===c.nodeName.toUpperCase()?h.push(ma(b,c)[0]):h.push(K(b,c));return h},1),c=this.rows(-1);c.pop();c.push.apply(c,b.toArray());return c});r("row()",function(a,b){return bb(this.rows(a,b))});r("row().data()",function(a){var b=this.context;if(a===k)return b.length&&this.length?b[0].aoData[this[0]]._aData:k;b[0].aoData[this[0]]._aData=a;ca(b[0],this[0],"data");return this});r("row().node()",function(){var a=this.context;return a.length&&this.length? a[0].aoData[this[0]].nTr||null:null});r("row.add()",function(a){a instanceof h&&a.length&&(a=a[0]);var b=this.iterator("table",function(b){return a.nodeName&&"TR"===a.nodeName.toUpperCase()?ma(b,a)[0]:K(b,a)});return this.row(b[0])});var cb=function(a,b){var c=a.context;c.length&&(c=c[0].aoData[b!==k?b:a[0]],c._details&&(c._details.remove(),c._detailsShow=k,c._details=k))},Vb=function(a,b){var c=a.context;if(c.length&&a.length){var e=c[0].aoData[a[0]];if(e._details){(e._detailsShow=b)?e._details.insertAfter(e.nTr): e._details.detach();var d=c[0],f=new t(d),g=d.aoData;f.off("draw.dt.DT_details column-visibility.dt.DT_details destroy.dt.DT_details");0<D(g,"_details").length&&(f.on("draw.dt.DT_details",function(a,b){d===b&&f.rows({page:"current"}).eq(0).each(function(a){a=g[a];a._detailsShow&&a._details.insertAfter(a.nTr)})}),f.on("column-visibility.dt.DT_details",function(a,b){if(d===b)for(var c,e=aa(b),f=0,h=g.length;f<h;f++)c=g[f],c._details&&c._details.children("td[colspan]").attr("colspan",e)}),f.on("destroy.dt.DT_details", function(a,b){if(d===b)for(var c=0,e=g.length;c<e;c++)g[c]._details&&cb(f,c)}))}}};r("row().child()",function(a,b){var c=this.context;if(a===k)return c.length&&this.length?c[0].aoData[this[0]]._details:k;if(!0===a)this.child.show();else if(!1===a)cb(this);else if(c.length&&this.length){var e=c[0],c=c[0].aoData[this[0]],d=[],f=function(a,b){if(h.isArray(a)||a instanceof h)for(var c=0,k=a.length;c<k;c++)f(a[c],b);else a.nodeName&&"tr"===a.nodeName.toLowerCase()?d.push(a):(c=h("<tr><td/></tr>").addClass(b), h("td",c).addClass(b).html(a)[0].colSpan=aa(e),d.push(c[0]))};f(a,b);c._details&&c._details.remove();c._details=h(d);c._detailsShow&&c._details.insertAfter(c.nTr)}return this});r(["row().child.show()","row().child().show()"],function(){Vb(this,!0);return this});r(["row().child.hide()","row().child().hide()"],function(){Vb(this,!1);return this});r(["row().child.remove()","row().child().remove()"],function(){cb(this);return this});r("row().child.isShown()",function(){var a=this.context;return a.length&& this.length?a[0].aoData[this[0]]._detailsShow||!1:!1});var dc=/^(.+):(name|visIdx|visible)$/,Wb=function(a,b,c,e,d){for(var c=[],e=0,f=d.length;e<f;e++)c.push(x(a,d[e],b));return c};r("columns()",function(a,b){a===k?a="":h.isPlainObject(a)&&(b=a,a="");var b=ab(b),c=this.iterator("table",function(c){var d=a,f=b,g=c.aoColumns,j=D(g,"sName"),i=D(g,"nTh");return $a("column",d,function(a){var b=Pb(a);if(a==="")return V(g.length);if(b!==null)return[b>=0?b:g.length+b];if(typeof a==="function"){var d=Ca(c, f);return h.map(g,function(b,f){return a(f,Wb(c,f,0,0,d),i[f])?f:null})}var k=typeof a==="string"?a.match(dc):"";if(k)switch(k[2]){case "visIdx":case "visible":b=parseInt(k[1],10);if(b<0){var m=h.map(g,function(a,b){return a.bVisible?b:null});return[m[m.length+b]]}return[la(c,b)];case "name":return h.map(j,function(a,b){return a===k[1]?b:null})}else return h(i).filter(a).map(function(){return h.inArray(this,i)}).toArray()},c,f)},1);c.selector.cols=a;c.selector.opts=b;return c});v("columns().header()", "column().header()",function(){return this.iterator("column",function(a,b){return a.aoColumns[b].nTh},1)});v("columns().footer()","column().footer()",function(){return this.iterator("column",function(a,b){return a.aoColumns[b].nTf},1)});v("columns().data()","column().data()",function(){return this.iterator("column-rows",Wb,1)});v("columns().dataSrc()","column().dataSrc()",function(){return this.iterator("column",function(a,b){return a.aoColumns[b].mData},1)});v("columns().cache()","column().cache()", function(a){return this.iterator("column-rows",function(b,c,e,d,f){return ia(b.aoData,f,"search"===a?"_aFilterData":"_aSortData",c)},1)});v("columns().nodes()","column().nodes()",function(){return this.iterator("column-rows",function(a,b,c,e,d){return ia(a.aoData,d,"anCells",b)},1)});v("columns().visible()","column().visible()",function(a,b){return this.iterator("column",function(c,e){if(a===k)return c.aoColumns[e].bVisible;var d=c.aoColumns,f=d[e],g=c.aoData,j,i,m;if(a!==k&&f.bVisible!==a){if(a){var l= h.inArray(!0,D(d,"bVisible"),e+1);j=0;for(i=g.length;j<i;j++)m=g[j].nTr,d=g[j].anCells,m&&m.insertBefore(d[e],d[l]||null)}else h(D(c.aoData,"anCells",e)).detach();f.bVisible=a;ea(c,c.aoHeader);ea(c,c.aoFooter);if(b===k||b)X(c),(c.oScroll.sX||c.oScroll.sY)&&Y(c);w(c,null,"column-visibility",[c,e,a]);ya(c)}})});v("columns().indexes()","column().index()",function(a){return this.iterator("column",function(b,c){return"visible"===a?$(b,c):c},1)});r("columns.adjust()",function(){return this.iterator("table", function(a){X(a)},1)});r("column.index()",function(a,b){if(0!==this.context.length){var c=this.context[0];if("fromVisible"===a||"toData"===a)return la(c,b);if("fromData"===a||"toVisible"===a)return $(c,b)}});r("column()",function(a,b){return bb(this.columns(a,b))});r("cells()",function(a,b,c){h.isPlainObject(a)&&(a.row===k?(c=a,a=null):(c=b,b=null));h.isPlainObject(b)&&(c=b,b=null);if(null===b||b===k)return this.iterator("table",function(b){var d=a,e=ab(c),f=b.aoData,g=Ca(b,e),i=Sb(ia(f,g,"anCells")), j=h([].concat.apply([],i)),l,m=b.aoColumns.length,o,r,t,s,u,v;return $a("cell",d,function(a){var c=typeof a==="function";if(a===null||a===k||c){o=[];r=0;for(t=g.length;r<t;r++){l=g[r];for(s=0;s<m;s++){u={row:l,column:s};if(c){v=b.aoData[l];a(u,x(b,l,s),v.anCells?v.anCells[s]:null)&&o.push(u)}else o.push(u)}}return o}return h.isPlainObject(a)?[a]:j.filter(a).map(function(a,b){l=b.parentNode._DT_RowIndex;return{row:l,column:h.inArray(b,f[l].anCells)}}).toArray()},b,e)});var e=this.columns(b,c),d=this.rows(a, c),f,g,j,i,m,l=this.iterator("table",function(a,b){f=[];g=0;for(j=d[b].length;g<j;g++){i=0;for(m=e[b].length;i<m;i++)f.push({row:d[b][g],column:e[b][i]})}return f},1);h.extend(l.selector,{cols:b,rows:a,opts:c});return l});v("cells().nodes()","cell().node()",function(){return this.iterator("cell",function(a,b,c){return(a=a.aoData[b].anCells)?a[c]:k},1)});r("cells().data()",function(){return this.iterator("cell",function(a,b,c){return x(a,b,c)},1)});v("cells().cache()","cell().cache()",function(a){a= "search"===a?"_aFilterData":"_aSortData";return this.iterator("cell",function(b,c,e){return b.aoData[c][a][e]},1)});v("cells().render()","cell().render()",function(a){return this.iterator("cell",function(b,c,e){return x(b,c,e,a)},1)});v("cells().indexes()","cell().index()",function(){return this.iterator("cell",function(a,b,c){return{row:b,column:c,columnVisible:$(a,c)}},1)});v("cells().invalidate()","cell().invalidate()",function(a){return this.iterator("cell",function(b,c,e){ca(b,c,a,e)})});r("cell()", function(a,b,c){return bb(this.cells(a,b,c))});r("cell().data()",function(a){var b=this.context,c=this[0];if(a===k)return b.length&&c.length?x(b[0],c[0].row,c[0].column):k;Ia(b[0],c[0].row,c[0].column,a);ca(b[0],c[0].row,"data",c[0].column);return this});r("order()",function(a,b){var c=this.context;if(a===k)return 0!==c.length?c[0].aaSorting:k;"number"===typeof a?a=[[a,b]]:h.isArray(a[0])||(a=Array.prototype.slice.call(arguments));return this.iterator("table",function(b){b.aaSorting=a.slice()})}); r("order.listener()",function(a,b,c){return this.iterator("table",function(e){Oa(e,a,b,c)})});r(["columns().order()","column().order()"],function(a){var b=this;return this.iterator("table",function(c,e){var d=[];h.each(b[e],function(b,c){d.push([c,a])});c.aaSorting=d})});r("search()",function(a,b,c,e){var d=this.context;return a===k?0!==d.length?d[0].oPreviousSearch.sSearch:k:this.iterator("table",function(d){d.oFeatures.bFilter&&fa(d,h.extend({},d.oPreviousSearch,{sSearch:a+"",bRegex:null===b?!1: b,bSmart:null===c?!0:c,bCaseInsensitive:null===e?!0:e}),1)})});v("columns().search()","column().search()",function(a,b,c,e){return this.iterator("column",function(d,f){var g=d.aoPreSearchCols;if(a===k)return g[f].sSearch;d.oFeatures.bFilter&&(h.extend(g[f],{sSearch:a+"",bRegex:null===b?!1:b,bSmart:null===c?!0:c,bCaseInsensitive:null===e?!0:e}),fa(d,d.oPreviousSearch,1))})});r("state()",function(){return this.context.length?this.context[0].oSavedState:null});r("state.clear()",function(){return this.iterator("table", function(a){a.fnStateSaveCallback.call(a.oInstance,a,{})})});r("state.loaded()",function(){return this.context.length?this.context[0].oLoadedState:null});r("state.save()",function(){return this.iterator("table",function(a){ya(a)})});m.versionCheck=m.fnVersionCheck=function(a){for(var b=m.version.split("."),a=a.split("."),c,e,d=0,f=a.length;d<f;d++)if(c=parseInt(b[d],10)||0,e=parseInt(a[d],10)||0,c!==e)return c>e;return!0};m.isDataTable=m.fnIsDataTable=function(a){var b=h(a).get(0),c=!1;h.each(m.settings, function(a,d){var f=d.nScrollHead?h("table",d.nScrollHead)[0]:null,g=d.nScrollFoot?h("table",d.nScrollFoot)[0]:null;if(d.nTable===b||f===b||g===b)c=!0});return c};m.tables=m.fnTables=function(a){return h.map(m.settings,function(b){if(!a||a&&h(b.nTable).is(":visible"))return b.nTable})};m.util={throttle:ua,escapeRegex:va};m.camelToHungarian=H;r("$()",function(a,b){var c=this.rows(b).nodes(),c=h(c);return h([].concat(c.filter(a).toArray(),c.find(a).toArray()))});h.each(["on","one","off"],function(a, b){r(b+"()",function(){var a=Array.prototype.slice.call(arguments);a[0].match(/\.dt\b/)||(a[0]+=".dt");var e=h(this.tables().nodes());e[b].apply(e,a);return this})});r("clear()",function(){return this.iterator("table",function(a){oa(a)})});r("settings()",function(){return new t(this.context,this.context)});r("init()",function(){var a=this.context;return a.length?a[0].oInit:null});r("data()",function(){return this.iterator("table",function(a){return D(a.aoData,"_aData")}).flatten()});r("destroy()", function(a){a=a||!1;return this.iterator("table",function(b){var c=b.nTableWrapper.parentNode,e=b.oClasses,d=b.nTable,f=b.nTBody,g=b.nTHead,j=b.nTFoot,i=h(d),f=h(f),k=h(b.nTableWrapper),l=h.map(b.aoData,function(a){return a.nTr}),q;b.bDestroying=!0;w(b,"aoDestroyCallback","destroy",[b]);a||(new t(b)).columns().visible(!0);k.unbind(".DT").find(":not(tbody *)").unbind(".DT");h(Ea).unbind(".DT-"+b.sInstance);d!=g.parentNode&&(i.children("thead").detach(),i.append(g));j&&d!=j.parentNode&&(i.children("tfoot").detach(), i.append(j));i.detach();k.detach();b.aaSorting=[];b.aaSortingFixed=[];xa(b);h(l).removeClass(b.asStripeClasses.join(" "));h("th, td",g).removeClass(e.sSortable+" "+e.sSortableAsc+" "+e.sSortableDesc+" "+e.sSortableNone);b.bJUI&&(h("th span."+e.sSortIcon+", td span."+e.sSortIcon,g).detach(),h("th, td",g).each(function(){var a=h("div."+e.sSortJUIWrapper,this);h(this).append(a.contents());a.detach()}));!a&&c&&c.insertBefore(d,b.nTableReinsertBefore);f.children().detach();f.append(l);i.css("width",b.sDestroyWidth).removeClass(e.sTable); (q=b.asDestroyStripes.length)&&f.children().each(function(a){h(this).addClass(b.asDestroyStripes[a%q])});c=h.inArray(b,m.settings);-1!==c&&m.settings.splice(c,1)})});h.each(["column","row","cell"],function(a,b){r(b+"s().every()",function(a){return this.iterator(b,function(e,d,f){a.call((new t(e))[b](d,f))})})});r("i18n()",function(a,b,c){var e=this.context[0],a=R(a)(e.oLanguage);a===k&&(a=b);c!==k&&h.isPlainObject(a)&&(a=a[c]!==k?a[c]:a._);return a.replace("%d",c)});m.version="1.10.7";m.settings= [];m.models={};m.models.oSearch={bCaseInsensitive:!0,sSearch:"",bRegex:!1,bSmart:!0};m.models.oRow={nTr:null,anCells:null,_aData:[],_aSortData:null,_aFilterData:null,_sFilterRow:null,_sRowStripe:"",src:null};m.models.oColumn={idx:null,aDataSort:null,asSorting:null,bSearchable:null,bSortable:null,bVisible:null,_sManualType:null,_bAttrSrc:!1,fnCreatedCell:null,fnGetData:null,fnSetData:null,mData:null,mRender:null,nTh:null,nTf:null,sClass:null,sContentPadding:null,sDefaultContent:null,sName:null,sSortDataType:"std", sSortingClass:null,sSortingClassJUI:null,sTitle:null,sType:null,sWidth:null,sWidthOrig:null};m.defaults={aaData:null,aaSorting:[[0,"asc"]],aaSortingFixed:[],ajax:null,aLengthMenu:[10,25,50,100],aoColumns:null,aoColumnDefs:null,aoSearchCols:[],asStripeClasses:null,bAutoWidth:!0,bDeferRender:!1,bDestroy:!1,bFilter:!0,bInfo:!0,bJQueryUI:!1,bLengthChange:!0,bPaginate:!0,bProcessing:!1,bRetrieve:!1,bScrollCollapse:!1,bServerSide:!1,bSort:!0,bSortMulti:!0,bSortCellsTop:!1,bSortClasses:!0,bStateSave:!1, fnCreatedRow:null,fnDrawCallback:null,fnFooterCallback:null,fnFormatNumber:function(a){return a.toString().replace(/\B(?=(\d{3})+(?!\d))/g,this.oLanguage.sThousands)},fnHeaderCallback:null,fnInfoCallback:null,fnInitComplete:null,fnPreDrawCallback:null,fnRowCallback:null,fnServerData:null,fnServerParams:null,fnStateLoadCallback:function(a){try{return JSON.parse((-1===a.iStateDuration?sessionStorage:localStorage).getItem("DataTables_"+a.sInstance+"_"+location.pathname))}catch(b){}},fnStateLoadParams:null, fnStateLoaded:null,fnStateSaveCallback:function(a,b){try{(-1===a.iStateDuration?sessionStorage:localStorage).setItem("DataTables_"+a.sInstance+"_"+location.pathname,JSON.stringify(b))}catch(c){}},fnStateSaveParams:null,iStateDuration:7200,iDeferLoading:null,iDisplayLength:10,iDisplayStart:0,iTabIndex:0,oClasses:{},oLanguage:{oAria:{sSortAscending:": activate to sort column ascending",sSortDescending:": activate to sort column descending"},oPaginate:{sFirst:"First",sLast:"Last",sNext:"Next",sPrevious:"Previous"}, sEmptyTable:"No data available in table",sInfo:"Showing _START_ to _END_ of _TOTAL_ entries",sInfoEmpty:"Showing 0 to 0 of 0 entries",sInfoFiltered:"(filtered from _MAX_ total entries)",sInfoPostFix:"",sDecimal:"",sThousands:",",sLengthMenu:"Show _MENU_ entries",sLoadingRecords:"Loading...",sProcessing:"Processing...",sSearch:"Search:",sSearchPlaceholder:"",sUrl:"",sZeroRecords:"No matching records found"},oSearch:h.extend({},m.models.oSearch),sAjaxDataProp:"data",sAjaxSource:null,sDom:"lfrtip",searchDelay:null, sPaginationType:"simple_numbers",sScrollX:"",sScrollXInner:"",sScrollY:"",sServerMethod:"GET",renderer:null};W(m.defaults);m.defaults.column={aDataSort:null,iDataSort:-1,asSorting:["asc","desc"],bSearchable:!0,bSortable:!0,bVisible:!0,fnCreatedCell:null,mData:null,mRender:null,sCellType:"td",sClass:"",sContentPadding:"",sDefaultContent:null,sName:"",sSortDataType:"std",sTitle:null,sType:null,sWidth:null};W(m.defaults.column);m.models.oSettings={oFeatures:{bAutoWidth:null,bDeferRender:null,bFilter:null, bInfo:null,bLengthChange:null,bPaginate:null,bProcessing:null,bServerSide:null,bSort:null,bSortMulti:null,bSortClasses:null,bStateSave:null},oScroll:{bCollapse:null,iBarWidth:0,sX:null,sXInner:null,sY:null},oLanguage:{fnInfoCallback:null},oBrowser:{bScrollOversize:!1,bScrollbarLeft:!1},ajax:null,aanFeatures:[],aoData:[],aiDisplay:[],aiDisplayMaster:[],aoColumns:[],aoHeader:[],aoFooter:[],oPreviousSearch:{},aoPreSearchCols:[],aaSorting:null,aaSortingFixed:[],asStripeClasses:null,asDestroyStripes:[], sDestroyWidth:0,aoRowCallback:[],aoHeaderCallback:[],aoFooterCallback:[],aoDrawCallback:[],aoRowCreatedCallback:[],aoPreDrawCallback:[],aoInitComplete:[],aoStateSaveParams:[],aoStateLoadParams:[],aoStateLoaded:[],sTableId:"",nTable:null,nTHead:null,nTFoot:null,nTBody:null,nTableWrapper:null,bDeferLoading:!1,bInitialised:!1,aoOpenRows:[],sDom:null,searchDelay:null,sPaginationType:"two_button",iStateDuration:0,aoStateSave:[],aoStateLoad:[],oSavedState:null,oLoadedState:null,sAjaxSource:null,sAjaxDataProp:null, bAjaxDataGet:!0,jqXHR:null,json:k,oAjaxData:k,fnServerData:null,aoServerParams:[],sServerMethod:null,fnFormatNumber:null,aLengthMenu:null,iDraw:0,bDrawing:!1,iDrawError:-1,_iDisplayLength:10,_iDisplayStart:0,_iRecordsTotal:0,_iRecordsDisplay:0,bJUI:null,oClasses:{},bFiltered:!1,bSorted:!1,bSortCellsTop:null,oInit:null,aoDestroyCallback:[],fnRecordsTotal:function(){return"ssp"==B(this)?1*this._iRecordsTotal:this.aiDisplayMaster.length},fnRecordsDisplay:function(){return"ssp"==B(this)?1*this._iRecordsDisplay: this.aiDisplay.length},fnDisplayEnd:function(){var a=this._iDisplayLength,b=this._iDisplayStart,c=b+a,e=this.aiDisplay.length,d=this.oFeatures,f=d.bPaginate;return d.bServerSide?!1===f||-1===a?b+e:Math.min(b+a,this._iRecordsDisplay):!f||c>e||-1===a?e:c},oInstance:null,sInstance:null,iTabIndex:0,nScrollHead:null,nScrollFoot:null,aLastSort:[],oPlugins:{}};m.ext=u={buttons:{},classes:{},errMode:"alert",feature:[],search:[],selector:{cell:[],column:[],row:[]},internal:{},legacy:{ajax:null},pager:{},renderer:{pageButton:{}, header:{}},order:{},type:{detect:[],search:{},order:{}},_unique:0,fnVersionCheck:m.fnVersionCheck,iApiIndex:0,oJUIClasses:{},sVersion:m.version};h.extend(u,{afnFiltering:u.search,aTypes:u.type.detect,ofnSearch:u.type.search,oSort:u.type.order,afnSortData:u.order,aoFeatures:u.feature,oApi:u.internal,oStdClasses:u.classes,oPagination:u.pager});h.extend(m.ext.classes,{sTable:"dataTable",sNoFooter:"no-footer",sPageButton:"paginate_button",sPageButtonActive:"current",sPageButtonDisabled:"disabled",sStripeOdd:"odd", sStripeEven:"even",sRowEmpty:"dataTables_empty",sWrapper:"dataTables_wrapper",sFilter:"dataTables_filter",sInfo:"dataTables_info",sPaging:"dataTables_paginate paging_",sLength:"dataTables_length",sProcessing:"dataTables_processing",sSortAsc:"sorting_asc",sSortDesc:"sorting_desc",sSortable:"sorting",sSortableAsc:"sorting_asc_disabled",sSortableDesc:"sorting_desc_disabled",sSortableNone:"sorting_disabled",sSortColumn:"sorting_",sFilterInput:"",sLengthSelect:"",sScrollWrapper:"dataTables_scroll",sScrollHead:"dataTables_scrollHead", sScrollHeadInner:"dataTables_scrollHeadInner",sScrollBody:"dataTables_scrollBody",sScrollFoot:"dataTables_scrollFoot",sScrollFootInner:"dataTables_scrollFootInner",sHeaderTH:"",sFooterTH:"",sSortJUIAsc:"",sSortJUIDesc:"",sSortJUI:"",sSortJUIAscAllowed:"",sSortJUIDescAllowed:"",sSortJUIWrapper:"",sSortIcon:"",sJUIHeader:"",sJUIFooter:""});var Da="",Da="",F=Da+"ui-state-default",ja=Da+"css_right ui-icon ui-icon-",Xb=Da+"fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix";h.extend(m.ext.oJUIClasses, m.ext.classes,{sPageButton:"fg-button ui-button "+F,sPageButtonActive:"ui-state-disabled",sPageButtonDisabled:"ui-state-disabled",sPaging:"dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi ui-buttonset-multi paging_",sSortAsc:F+" sorting_asc",sSortDesc:F+" sorting_desc",sSortable:F+" sorting",sSortableAsc:F+" sorting_asc_disabled",sSortableDesc:F+" sorting_desc_disabled",sSortableNone:F+" sorting_disabled",sSortJUIAsc:ja+"triangle-1-n",sSortJUIDesc:ja+"triangle-1-s",sSortJUI:ja+"carat-2-n-s", sSortJUIAscAllowed:ja+"carat-1-n",sSortJUIDescAllowed:ja+"carat-1-s",sSortJUIWrapper:"DataTables_sort_wrapper",sSortIcon:"DataTables_sort_icon",sScrollHead:"dataTables_scrollHead "+F,sScrollFoot:"dataTables_scrollFoot "+F,sHeaderTH:F,sFooterTH:F,sJUIHeader:Xb+" ui-corner-tl ui-corner-tr",sJUIFooter:Xb+" ui-corner-bl ui-corner-br"});var Mb=m.ext.pager;h.extend(Mb,{simple:function(){return["previous","next"]},full:function(){return["first","previous","next","last"]},simple_numbers:function(a,b){return["previous", Wa(a,b),"next"]},full_numbers:function(a,b){return["first","previous",Wa(a,b),"next","last"]},_numbers:Wa,numbers_length:7});h.extend(!0,m.ext.renderer,{pageButton:{_:function(a,b,c,e,d,f){var g=a.oClasses,j=a.oLanguage.oPaginate,i,k,l=0,m=function(b,e){var n,r,t,s,u=function(b){Ta(a,b.data.action,true)};n=0;for(r=e.length;n<r;n++){s=e[n];if(h.isArray(s)){t=h("<"+(s.DT_el||"div")+"/>").appendTo(b);m(t,s)}else{k=i="";switch(s){case "ellipsis":b.append('<span class="ellipsis">&#x2026;</span>');break; case "first":i=j.sFirst;k=s+(d>0?"":" "+g.sPageButtonDisabled);break;case "previous":i=j.sPrevious;k=s+(d>0?"":" "+g.sPageButtonDisabled);break;case "next":i=j.sNext;k=s+(d<f-1?"":" "+g.sPageButtonDisabled);break;case "last":i=j.sLast;k=s+(d<f-1?"":" "+g.sPageButtonDisabled);break;default:i=s+1;k=d===s?g.sPageButtonActive:""}if(i){t=h("<a>",{"class":g.sPageButton+" "+k,"aria-controls":a.sTableId,"data-dt-idx":l,tabindex:a.iTabIndex,id:c===0&&typeof s==="string"?a.sTableId+"_"+s:null}).html(i).appendTo(b); Va(t,{action:s},u);l++}}}},n;try{n=h(Q.activeElement).data("dt-idx")}catch(r){}m(h(b).empty(),e);n&&h(b).find("[data-dt-idx="+n+"]").focus()}}});h.extend(m.ext.type.detect,[function(a,b){var c=b.oLanguage.sDecimal;return Za(a,c)?"num"+c:null},function(a){if(a&&!(a instanceof Date)&&(!ac.test(a)||!bc.test(a)))return null;var b=Date.parse(a);return null!==b&&!isNaN(b)||J(a)?"date":null},function(a,b){var c=b.oLanguage.sDecimal;return Za(a,c,!0)?"num-fmt"+c:null},function(a,b){var c=b.oLanguage.sDecimal; return Rb(a,c)?"html-num"+c:null},function(a,b){var c=b.oLanguage.sDecimal;return Rb(a,c,!0)?"html-num-fmt"+c:null},function(a){return J(a)||"string"===typeof a&&-1!==a.indexOf("<")?"html":null}]);h.extend(m.ext.type.search,{html:function(a){return J(a)?a:"string"===typeof a?a.replace(Ob," ").replace(Ba,""):""},string:function(a){return J(a)?a:"string"===typeof a?a.replace(Ob," "):a}});var Aa=function(a,b,c,e){if(0!==a&&(!a||"-"===a))return-Infinity;b&&(a=Qb(a,b));a.replace&&(c&&(a=a.replace(c,"")), e&&(a=a.replace(e,"")));return 1*a};h.extend(u.type.order,{"date-pre":function(a){return Date.parse(a)||0},"html-pre":function(a){return J(a)?"":a.replace?a.replace(/<.*?>/g,"").toLowerCase():a+""},"string-pre":function(a){return J(a)?"":"string"===typeof a?a.toLowerCase():!a.toString?"":a.toString()},"string-asc":function(a,b){return a<b?-1:a>b?1:0},"string-desc":function(a,b){return a<b?1:a>b?-1:0}});db("");h.extend(!0,m.ext.renderer,{header:{_:function(a,b,c,e){h(a.nTable).on("order.dt.DT",function(d, f,g,h){if(a===f){d=c.idx;b.removeClass(c.sSortingClass+" "+e.sSortAsc+" "+e.sSortDesc).addClass(h[d]=="asc"?e.sSortAsc:h[d]=="desc"?e.sSortDesc:c.sSortingClass)}})},jqueryui:function(a,b,c,e){h("<div/>").addClass(e.sSortJUIWrapper).append(b.contents()).append(h("<span/>").addClass(e.sSortIcon+" "+c.sSortingClassJUI)).appendTo(b);h(a.nTable).on("order.dt.DT",function(d,f,g,h){if(a===f){d=c.idx;b.removeClass(e.sSortAsc+" "+e.sSortDesc).addClass(h[d]=="asc"?e.sSortAsc:h[d]=="desc"?e.sSortDesc:c.sSortingClass); b.find("span."+e.sSortIcon).removeClass(e.sSortJUIAsc+" "+e.sSortJUIDesc+" "+e.sSortJUI+" "+e.sSortJUIAscAllowed+" "+e.sSortJUIDescAllowed).addClass(h[d]=="asc"?e.sSortJUIAsc:h[d]=="desc"?e.sSortJUIDesc:c.sSortingClassJUI)}})}}});m.render={number:function(a,b,c,e){return{display:function(d){if("number"!==typeof d&&"string"!==typeof d)return d;var f=0>d?"-":"",d=Math.abs(parseFloat(d)),g=parseInt(d,10),d=c?b+(d-g).toFixed(c).substring(2):"";return f+(e||"")+g.toString().replace(/\B(?=(\d{3})+(?!\d))/g, a)+d}}}};h.extend(m.ext.internal,{_fnExternApiFunc:Nb,_fnBuildAjax:ra,_fnAjaxUpdate:kb,_fnAjaxParameters:tb,_fnAjaxUpdateDraw:ub,_fnAjaxDataSrc:sa,_fnAddColumn:Fa,_fnColumnOptions:ka,_fnAdjustColumnSizing:X,_fnVisibleToColumnIndex:la,_fnColumnIndexToVisible:$,_fnVisbleColumns:aa,_fnGetColumns:Z,_fnColumnTypes:Ha,_fnApplyColumnDefs:ib,_fnHungarianMap:W,_fnCamelToHungarian:H,_fnLanguageCompat:P,_fnBrowserDetect:gb,_fnAddData:K,_fnAddTr:ma,_fnNodeToDataIndex:function(a,b){return b._DT_RowIndex!==k?b._DT_RowIndex: null},_fnNodeToColumnIndex:function(a,b,c){return h.inArray(c,a.aoData[b].anCells)},_fnGetCellData:x,_fnSetCellData:Ia,_fnSplitObjNotation:Ka,_fnGetObjectDataFn:R,_fnSetObjectDataFn:S,_fnGetDataMaster:La,_fnClearTable:oa,_fnDeleteIndex:pa,_fnInvalidate:ca,_fnGetRowElements:na,_fnCreateTr:Ja,_fnBuildHead:jb,_fnDrawHead:ea,_fnDraw:M,_fnReDraw:N,_fnAddOptionsHtml:mb,_fnDetectHeader:da,_fnGetUniqueThs:qa,_fnFeatureHtmlFilter:ob,_fnFilterComplete:fa,_fnFilterCustom:xb,_fnFilterColumn:wb,_fnFilter:vb,_fnFilterCreateSearch:Qa, _fnEscapeRegex:va,_fnFilterData:yb,_fnFeatureHtmlInfo:rb,_fnUpdateInfo:Bb,_fnInfoMacros:Cb,_fnInitialise:ga,_fnInitComplete:ta,_fnLengthChange:Ra,_fnFeatureHtmlLength:nb,_fnFeatureHtmlPaginate:sb,_fnPageChange:Ta,_fnFeatureHtmlProcessing:pb,_fnProcessingDisplay:C,_fnFeatureHtmlTable:qb,_fnScrollDraw:Y,_fnApplyToChildren:G,_fnCalculateColumnWidths:Ga,_fnThrottle:ua,_fnConvertToWidth:Db,_fnScrollingWidthAdjust:Fb,_fnGetWidestNode:Eb,_fnGetMaxLenString:Gb,_fnStringToCss:s,_fnScrollBarWidth:Hb,_fnSortFlatten:U, _fnSort:lb,_fnSortAria:Jb,_fnSortListener:Ua,_fnSortAttachListener:Oa,_fnSortingClasses:xa,_fnSortData:Ib,_fnSaveState:ya,_fnLoadState:Kb,_fnSettingsFromNode:za,_fnLog:I,_fnMap:E,_fnBindAction:Va,_fnCallbackReg:z,_fnCallbackFire:w,_fnLengthOverflow:Sa,_fnRenderer:Pa,_fnDataSource:B,_fnRowAttributes:Ma,_fnCalculateEnd:function(){}});h.fn.dataTable=m;h.fn.dataTableSettings=m.settings;h.fn.dataTableExt=m.ext;h.fn.DataTable=function(a){return h(this).dataTable(a).api()};h.each(m,function(a,b){h.fn.DataTable[a]= b});return h.fn.dataTable};"function"===typeof define&&define.amd?define("datatables",["jquery"],P):"object"===typeof exports?module.exports=P(require("jquery")):jQuery&&!jQuery.fn.dataTable&&P(jQuery)})(window,document);
var knex = require('knex'), config = require('../../config'), dbConfig = config.database, knexInstance; function configureDriver(client) { var pg; if (client === 'pg' || client === 'postgres' || client === 'postgresql') { try { pg = require('pg'); } catch (e) { pg = require('pg.js'); } // By default PostgreSQL returns data as strings along with an OID that identifies // its type. We're setting the parser to convert OID 20 (int8) into a javascript // integer. pg.types.setTypeParser(20, function (val) { return val === null ? null : parseInt(val, 10); }); } } if (!knexInstance && dbConfig && dbConfig.client) { configureDriver(dbConfig.client); knexInstance = knex(dbConfig); } module.exports = knexInstance;
/** @license MIT License (c) copyright B Cavalier & J Hann */ /** * wire/dojo/events plugin * wire plugin that can connect event handlers after an object is * initialized, and disconnect them when an object is destroyed. * This implementation uses dojo.connect and dojo.disconnect to do * the work of connecting and disconnecting event handlers. * * wire is part of the cujo.js family of libraries (http://cujojs.com/) * * Licensed under the MIT License at: * http://www.opensource.org/licenses/mit-license.php */ define(['when', '../lib/connection', 'dojo', 'dojo/_base/event'], function(when, connection, events) { return { wire$plugin: function eventsPlugin(/*, options*/) { var connectHandles = []; function handleConnection(source, eventName, handler) { connectHandles.push(events.connect(source, eventName, handler)); } function connect(source, connect, options, wire) { return connection.parse(source, connect, options, wire, handleConnection); } /* Function: connectFacet Setup connections for each specified in the connects param. Each key in connects is a reference, and the corresponding value is an object whose keys are event names, and whose values are methods of object to invoke. For example: connect: { "refToOtherThing": { "eventOrMethodOfOtherThing": "myOwnMethod" }, "dom!myButton": { "onclick": "_handleButtonClick" }, "dijit!myWidget": { "onChange": "_handleValueChange" } "myOwnEventOrMethod": { "refToOtherThing": "methodOfOtherThing" } } Parameters: factory - wiring factory object - object being wired, will be the target of connected events connects - specification of events to connect, see examples above. */ function connectFacet(wire, facet) { var promises, connects; promises = []; connects = facet.options; for(var ref in connects) { promises.push(connect(facet, ref, connects[ref], wire)); } return when.all(promises); } return { context: { destroy: function(resolver) { for (var i = connectHandles.length - 1; i >= 0; i--){ events.disconnect(connectHandles[i]); } resolver.resolve(); } }, facets: { connect: { connect: function(resolver, facet, wire) { resolver.resolve(connectFacet(wire, facet)); } } } }; } }; });
/*!*************************************************** * mark.js v8.7.0 * https://github.com/julmot/mark.js * Copyright (c) 2014–2017, Julian Motz * Released under the MIT license https://git.io/vwTVl *****************************************************/ "use strict"; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } (function (factory, window, document) { if (typeof define === "function" && define.amd) { define([], function () { return factory(window, document); }); } else if ((typeof module === "undefined" ? "undefined" : _typeof(module)) === "object" && module.exports) { module.exports = factory(window, document); } else { factory(window, document); } })(function (window, document) { var Mark = function () { function Mark(ctx) { _classCallCheck(this, Mark); this.ctx = ctx; this.ie = false; var ua = window.navigator.userAgent; if (ua.indexOf("MSIE") > -1 || ua.indexOf("Trident") > -1) { this.ie = true; } } _createClass(Mark, [{ key: "log", value: function log(msg) { var level = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "debug"; var log = this.opt.log; if (!this.opt.debug) { return; } if ((typeof log === "undefined" ? "undefined" : _typeof(log)) === "object" && typeof log[level] === "function") { log[level]("mark.js: " + msg); } } }, { key: "escapeStr", value: function escapeStr(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); } }, { key: "createRegExp", value: function createRegExp(str) { str = this.escapeStr(str); if (Object.keys(this.opt.synonyms).length) { str = this.createSynonymsRegExp(str); } if (this.opt.ignoreJoiners) { str = this.setupIgnoreJoinersRegExp(str); } if (this.opt.diacritics) { str = this.createDiacriticsRegExp(str); } str = this.createMergedBlanksRegExp(str); if (this.opt.ignoreJoiners) { str = this.createIgnoreJoinersRegExp(str); } str = this.createAccuracyRegExp(str); return str; } }, { key: "createSynonymsRegExp", value: function createSynonymsRegExp(str) { var syn = this.opt.synonyms, sens = this.opt.caseSensitive ? "" : "i"; for (var index in syn) { if (syn.hasOwnProperty(index)) { var value = syn[index], k1 = this.escapeStr(index), k2 = this.escapeStr(value); str = str.replace(new RegExp("(" + k1 + "|" + k2 + ")", "gm" + sens), "(" + k1 + "|" + k2 + ")"); } } return str; } }, { key: "setupIgnoreJoinersRegExp", value: function setupIgnoreJoinersRegExp(str) { return str.replace(/[^(|)\\]/g, function (val, indx, original) { var nextChar = original.charAt(indx + 1); if (/[(|)\\]/.test(nextChar) || nextChar === "") { return val; } else { return val + "\0"; } }); } }, { key: "createIgnoreJoinersRegExp", value: function createIgnoreJoinersRegExp(str) { return str.split("\0").join("[\\u00ad|\\u200b|\\u200c|\\u200d]?"); } }, { key: "createDiacriticsRegExp", value: function createDiacriticsRegExp(str) { var sens = this.opt.caseSensitive ? "" : "i", dct = this.opt.caseSensitive ? ["aàáâãäåāąă", "AÀÁÂÃÄÅĀĄĂ", "cçćč", "CÇĆČ", "dđď", "DĐĎ", "eèéêëěēę", "EÈÉÊËĚĒĘ", "iìíîïī", "IÌÍÎÏĪ", "lł", "LŁ", "nñňń", "NÑŇŃ", "oòóôõöøō", "OÒÓÔÕÖØŌ", "rř", "RŘ", "sšśș", "SŠŚȘ", "tťț", "TŤȚ", "uùúûüůū", "UÙÚÛÜŮŪ", "yÿý", "YŸÝ", "zžżź", "ZŽŻŹ"] : ["aÀÁÂÃÄÅàáâãäåĀāąĄăĂ", "cÇçćĆčČ", "dđĐďĎ", "eÈÉÊËèéêëěĚĒēęĘ", "iÌÍÎÏìíîïĪī", "lłŁ", "nÑñňŇńŃ", "oÒÓÔÕÖØòóôõöøŌō", "rřŘ", "sŠšśŚșȘ", "tťŤțȚ", "uÙÚÛÜùúûüůŮŪū", "yŸÿýÝ", "zŽžżŻźŹ"]; var handled = []; str.split("").forEach(function (ch) { dct.every(function (dct) { if (dct.indexOf(ch) !== -1) { if (handled.indexOf(dct) > -1) { return false; } str = str.replace(new RegExp("[" + dct + "]", "gm" + sens), "[" + dct + "]"); handled.push(dct); } return true; }); }); return str; } }, { key: "createMergedBlanksRegExp", value: function createMergedBlanksRegExp(str) { return str.replace(/[\s]+/gmi, "[\\s]+"); } }, { key: "createAccuracyRegExp", value: function createAccuracyRegExp(str) { var _this = this; var acc = this.opt.accuracy, val = typeof acc === "string" ? acc : acc.value, ls = typeof acc === "string" ? [] : acc.limiters, lsJoin = ""; ls.forEach(function (limiter) { lsJoin += "|" + _this.escapeStr(limiter); }); switch (val) { case "partially": default: return "()(" + str + ")"; case "complementary": return "()([^\\s" + lsJoin + "]*" + str + "[^\\s" + lsJoin + "]*)"; case "exactly": return "(^|\\s" + lsJoin + ")(" + str + ")(?=$|\\s" + lsJoin + ")"; } } }, { key: "getSeparatedKeywords", value: function getSeparatedKeywords(sv) { var _this2 = this; var stack = []; sv.forEach(function (kw) { if (!_this2.opt.separateWordSearch) { if (kw.trim() && stack.indexOf(kw) === -1) { stack.push(kw); } } else { kw.split(" ").forEach(function (kwSplitted) { if (kwSplitted.trim() && stack.indexOf(kwSplitted) === -1) { stack.push(kwSplitted); } }); } }); return { "keywords": stack.sort(function (a, b) { return b.length - a.length; }), "length": stack.length }; } }, { key: "getTextNodes", value: function getTextNodes(cb) { var _this3 = this; var val = "", nodes = []; this.iterator.forEachNode(NodeFilter.SHOW_TEXT, function (node) { nodes.push({ start: val.length, end: (val += node.textContent).length, node: node }); }, function (node) { if (_this3.matchesExclude(node.parentNode)) { return NodeFilter.FILTER_REJECT; } else { return NodeFilter.FILTER_ACCEPT; } }, function () { cb({ value: val, nodes: nodes }); }); } }, { key: "matchesExclude", value: function matchesExclude(el) { return DOMIterator.matches(el, this.opt.exclude.concat(["script", "style", "title", "head", "html"])); } }, { key: "wrapRangeInTextNode", value: function wrapRangeInTextNode(node, start, end) { var hEl = !this.opt.element ? "mark" : this.opt.element, startNode = node.splitText(start), ret = startNode.splitText(end - start); var repl = document.createElement(hEl); repl.setAttribute("data-markjs", "true"); if (this.opt.className) { repl.setAttribute("class", this.opt.className); } repl.textContent = startNode.textContent; startNode.parentNode.replaceChild(repl, startNode); return ret; } }, { key: "wrapRangeInMappedTextNode", value: function wrapRangeInMappedTextNode(dict, start, end, filterCb, eachCb) { var _this4 = this; dict.nodes.every(function (n, i) { var sibl = dict.nodes[i + 1]; if (typeof sibl === "undefined" || sibl.start > start) { var _ret = function () { if (!filterCb(n.node)) { return { v: false }; } var s = start - n.start, e = (end > n.end ? n.end : end) - n.start, startStr = dict.value.substr(0, n.start), endStr = dict.value.substr(e + n.start); n.node = _this4.wrapRangeInTextNode(n.node, s, e); dict.value = startStr + endStr; dict.nodes.forEach(function (k, j) { if (j >= i) { if (dict.nodes[j].start > 0 && j !== i) { dict.nodes[j].start -= e; } dict.nodes[j].end -= e; } }); end -= e; eachCb(n.node.previousSibling, n.start); if (end > n.end) { start = n.end; } else { return { v: false }; } }(); if ((typeof _ret === "undefined" ? "undefined" : _typeof(_ret)) === "object") return _ret.v; } return true; }); } }, { key: "wrapMatches", value: function wrapMatches(regex, ignoreGroups, filterCb, eachCb, endCb) { var _this5 = this; var matchIdx = ignoreGroups === 0 ? 0 : ignoreGroups + 1; this.getTextNodes(function (dict) { dict.nodes.forEach(function (node) { node = node.node; var match = void 0; while ((match = regex.exec(node.textContent)) !== null && match[matchIdx] !== "") { if (!filterCb(match[matchIdx], node)) { continue; } var pos = match.index; if (matchIdx !== 0) { for (var i = 1; i < matchIdx; i++) { pos += match[i].length; } } node = _this5.wrapRangeInTextNode(node, pos, pos + match[matchIdx].length); eachCb(node.previousSibling); regex.lastIndex = 0; } }); endCb(); }); } }, { key: "wrapMatchesAcrossElements", value: function wrapMatchesAcrossElements(regex, ignoreGroups, filterCb, eachCb, endCb) { var _this6 = this; var matchIdx = ignoreGroups === 0 ? 0 : ignoreGroups + 1; this.getTextNodes(function (dict) { var match = void 0; while ((match = regex.exec(dict.value)) !== null && match[matchIdx] !== "") { var start = match.index; if (matchIdx !== 0) { for (var i = 1; i < matchIdx; i++) { start += match[i].length; } } var end = start + match[matchIdx].length; _this6.wrapRangeInMappedTextNode(dict, start, end, function (node) { return filterCb(match[matchIdx], node); }, function (node, lastIndex) { regex.lastIndex = lastIndex; eachCb(node); }); } endCb(); }); } }, { key: "unwrapMatches", value: function unwrapMatches(node) { var parent = node.parentNode; var docFrag = document.createDocumentFragment(); while (node.firstChild) { docFrag.appendChild(node.removeChild(node.firstChild)); } parent.replaceChild(docFrag, node); if (!this.ie) { parent.normalize(); } else { this.normalizeTextNode(parent); } } }, { key: "normalizeTextNode", value: function normalizeTextNode(node) { if (!node) { return; } if (node.nodeType === 3) { while (node.nextSibling && node.nextSibling.nodeType === 3) { node.nodeValue += node.nextSibling.nodeValue; node.parentNode.removeChild(node.nextSibling); } } else { this.normalizeTextNode(node.firstChild); } this.normalizeTextNode(node.nextSibling); } }, { key: "markRegExp", value: function markRegExp(regexp, opt) { var _this7 = this; this.opt = opt; this.log("Searching with expression \"" + regexp + "\""); var totalMatches = 0, fn = "wrapMatches"; var eachCb = function eachCb(element) { totalMatches++; _this7.opt.each(element); }; if (this.opt.acrossElements) { fn = "wrapMatchesAcrossElements"; } this[fn](regexp, this.opt.ignoreGroups, function (match, node) { return _this7.opt.filter(node, match, totalMatches); }, eachCb, function () { if (totalMatches === 0) { _this7.opt.noMatch(regexp); } _this7.opt.done(totalMatches); }); } }, { key: "mark", value: function mark(sv, opt) { var _this8 = this; this.opt = opt; var totalMatches = 0, fn = "wrapMatches"; var _getSeparatedKeywords = this.getSeparatedKeywords(typeof sv === "string" ? [sv] : sv), kwArr = _getSeparatedKeywords.keywords, kwArrLen = _getSeparatedKeywords.length, sens = this.opt.caseSensitive ? "" : "i", handler = function handler(kw) { var regex = new RegExp(_this8.createRegExp(kw), "gm" + sens), matches = 0; _this8.log("Searching with expression \"" + regex + "\""); _this8[fn](regex, 1, function (term, node) { return _this8.opt.filter(node, kw, totalMatches, matches); }, function (element) { matches++; totalMatches++; _this8.opt.each(element); }, function () { if (matches === 0) { _this8.opt.noMatch(kw); } if (kwArr[kwArrLen - 1] === kw) { _this8.opt.done(totalMatches); } else { handler(kwArr[kwArr.indexOf(kw) + 1]); } }); }; if (this.opt.acrossElements) { fn = "wrapMatchesAcrossElements"; } if (kwArrLen === 0) { this.opt.done(totalMatches); } else { handler(kwArr[0]); } } }, { key: "unmark", value: function unmark(opt) { var _this9 = this; this.opt = opt; var sel = this.opt.element ? this.opt.element : "*"; sel += "[data-markjs]"; if (this.opt.className) { sel += "." + this.opt.className; } this.log("Removal selector \"" + sel + "\""); this.iterator.forEachNode(NodeFilter.SHOW_ELEMENT, function (node) { _this9.unwrapMatches(node); }, function (node) { var matchesSel = DOMIterator.matches(node, sel), matchesExclude = _this9.matchesExclude(node); if (!matchesSel || matchesExclude) { return NodeFilter.FILTER_REJECT; } else { return NodeFilter.FILTER_ACCEPT; } }, this.opt.done); } }, { key: "opt", set: function set(val) { this._opt = _extends({}, { "element": "", "className": "", "exclude": [], "iframes": false, "separateWordSearch": true, "diacritics": true, "synonyms": {}, "accuracy": "partially", "acrossElements": false, "caseSensitive": false, "ignoreJoiners": false, "ignoreGroups": 0, "each": function each() {}, "noMatch": function noMatch() {}, "filter": function filter() { return true; }, "done": function done() {}, "debug": false, "log": window.console }, val); }, get: function get() { return this._opt; } }, { key: "iterator", get: function get() { if (!this._iterator) { this._iterator = new DOMIterator(this.ctx, this.opt.iframes, this.opt.exclude); } return this._iterator; } }]); return Mark; }(); var DOMIterator = function () { function DOMIterator(ctx) { var iframes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; var exclude = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; _classCallCheck(this, DOMIterator); this.ctx = ctx; this.iframes = iframes; this.exclude = exclude; } _createClass(DOMIterator, [{ key: "getContexts", value: function getContexts() { var ctx = void 0, filteredCtx = []; if (typeof this.ctx === "undefined" || !this.ctx) { ctx = []; } else if (NodeList.prototype.isPrototypeOf(this.ctx)) { ctx = Array.prototype.slice.call(this.ctx); } else if (Array.isArray(this.ctx)) { ctx = this.ctx; } else if (typeof this.ctx === "string") { ctx = Array.prototype.slice.call(document.querySelectorAll(this.ctx)); } else { ctx = [this.ctx]; } ctx.forEach(function (ctx) { var isDescendant = filteredCtx.filter(function (contexts) { return contexts.contains(ctx); }).length > 0; if (filteredCtx.indexOf(ctx) === -1 && !isDescendant) { filteredCtx.push(ctx); } }); return filteredCtx; } }, { key: "getIframeContents", value: function getIframeContents(ifr, successFn) { var errorFn = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {}; var doc = void 0; try { var ifrWin = ifr.contentWindow; doc = ifrWin.document; if (!ifrWin || !doc) { throw new Error("iframe inaccessible"); } } catch (e) { errorFn(); } if (doc) { successFn(doc); } } }, { key: "onIframeReady", value: function onIframeReady(ifr, successFn, errorFn) { var _this10 = this; try { (function () { var ifrWin = ifr.contentWindow, bl = "about:blank", compl = "complete", isBlank = function isBlank() { var src = ifr.getAttribute("src").trim(), href = ifrWin.location.href; return href === bl && src !== bl && src; }, observeOnload = function observeOnload() { var listener = function listener() { try { if (!isBlank()) { ifr.removeEventListener("load", listener); _this10.getIframeContents(ifr, successFn, errorFn); } } catch (e) { errorFn(); } }; ifr.addEventListener("load", listener); }; if (ifrWin.document.readyState === compl) { if (isBlank()) { observeOnload(); } else { _this10.getIframeContents(ifr, successFn, errorFn); } } else { observeOnload(); } })(); } catch (e) { errorFn(); } } }, { key: "waitForIframes", value: function waitForIframes(ctx, done) { var _this11 = this; var eachCalled = 0; this.forEachIframe(ctx, function () { return true; }, function (ifr) { eachCalled++; _this11.waitForIframes(ifr.querySelector("html"), function () { if (! --eachCalled) { done(); } }); }, function (handled) { if (!handled) { done(); } }); } }, { key: "forEachIframe", value: function forEachIframe(ctx, filter, each) { var _this12 = this; var end = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : function () {}; var ifr = ctx.querySelectorAll("iframe"), open = ifr.length, handled = 0; ifr = Array.prototype.slice.call(ifr); var checkEnd = function checkEnd() { if (--open <= 0) { end(handled); } }; if (!open) { checkEnd(); } ifr.forEach(function (ifr) { if (DOMIterator.matches(ifr, _this12.exclude)) { checkEnd(); } else { _this12.onIframeReady(ifr, function (con) { if (filter(ifr)) { handled++; each(con); } checkEnd(); }, checkEnd); } }); } }, { key: "createIterator", value: function createIterator(ctx, whatToShow, filter) { return document.createNodeIterator(ctx, whatToShow, filter, false); } }, { key: "createInstanceOnIframe", value: function createInstanceOnIframe(contents) { return new DOMIterator(contents.querySelector("html"), this.iframes); } }, { key: "compareNodeIframe", value: function compareNodeIframe(node, prevNode, ifr) { var compCurr = node.compareDocumentPosition(ifr), prev = Node.DOCUMENT_POSITION_PRECEDING; if (compCurr & prev) { if (prevNode !== null) { var compPrev = prevNode.compareDocumentPosition(ifr), after = Node.DOCUMENT_POSITION_FOLLOWING; if (compPrev & after) { return true; } } else { return true; } } return false; } }, { key: "getIteratorNode", value: function getIteratorNode(itr) { var prevNode = itr.previousNode(); var node = void 0; if (prevNode === null) { node = itr.nextNode(); } else { node = itr.nextNode() && itr.nextNode(); } return { prevNode: prevNode, node: node }; } }, { key: "checkIframeFilter", value: function checkIframeFilter(node, prevNode, currIfr, ifr) { var key = false, handled = false; ifr.forEach(function (ifrDict, i) { if (ifrDict.val === currIfr) { key = i; handled = ifrDict.handled; } }); if (this.compareNodeIframe(node, prevNode, currIfr)) { if (key === false && !handled) { ifr.push({ val: currIfr, handled: true }); } else if (key !== false && !handled) { ifr[key].handled = true; } return true; } if (key === false) { ifr.push({ val: currIfr, handled: false }); } return false; } }, { key: "handleOpenIframes", value: function handleOpenIframes(ifr, whatToShow, eCb, fCb) { var _this13 = this; ifr.forEach(function (ifrDict) { if (!ifrDict.handled) { _this13.getIframeContents(ifrDict.val, function (con) { _this13.createInstanceOnIframe(con).forEachNode(whatToShow, eCb, fCb); }); } }); } }, { key: "iterateThroughNodes", value: function iterateThroughNodes(whatToShow, ctx, eachCb, filterCb, doneCb) { var _this14 = this; var itr = this.createIterator(ctx, whatToShow, filterCb); var ifr = [], elements = [], node = void 0, prevNode = void 0, retrieveNodes = function retrieveNodes() { var _getIteratorNode = _this14.getIteratorNode(itr); prevNode = _getIteratorNode.prevNode; node = _getIteratorNode.node; return node; }; while (retrieveNodes()) { if (this.iframes) { this.forEachIframe(ctx, function (currIfr) { return _this14.checkIframeFilter(node, prevNode, currIfr, ifr); }, function (con) { _this14.createInstanceOnIframe(con).forEachNode(whatToShow, eachCb, filterCb); }); } elements.push(node); } elements.forEach(function (node) { eachCb(node); }); if (this.iframes) { this.handleOpenIframes(ifr, whatToShow, eachCb, filterCb); } doneCb(); } }, { key: "forEachNode", value: function forEachNode(whatToShow, each, filter) { var _this15 = this; var done = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : function () {}; var contexts = this.getContexts(); var open = contexts.length; if (!open) { done(); } contexts.forEach(function (ctx) { var ready = function ready() { _this15.iterateThroughNodes(whatToShow, ctx, each, filter, function () { if (--open <= 0) { done(); } }); }; if (_this15.iframes) { _this15.waitForIframes(ctx, ready); } else { ready(); } }); } }], [{ key: "matches", value: function matches(element, selector) { var selectors = typeof selector === "string" ? [selector] : selector, fn = element.matches || element.matchesSelector || element.msMatchesSelector || element.mozMatchesSelector || element.oMatchesSelector || element.webkitMatchesSelector; if (fn) { var match = false; selectors.every(function (sel) { if (fn.call(element, sel)) { match = true; return false; } return true; }); return match; } else { return false; } } }]); return DOMIterator; }(); window.Mark = function (ctx) { var _this16 = this; var instance = new Mark(ctx); this.mark = function (sv, opt) { instance.mark(sv, opt); return _this16; }; this.markRegExp = function (sv, opt) { instance.markRegExp(sv, opt); return _this16; }; this.unmark = function (opt) { instance.unmark(opt); return _this16; }; return this; }; return window.Mark; }, window, document);
/** * @author Kyle-Larson https://github.com/Kyle-Larson * * Loader loads FBX file and generates Group representing FBX scene. * Requires FBX file to be >= 7.0 and in ASCII format. * * Supports: * Mesh Generation (Positional Data) * Normal Data (Per Vertex Drawing Instance) * UV Data (Per Vertex Drawing Instance) * Skinning * Animation * - Separated Animations based on stacks. * - Skeletal & Non-Skeletal Animations * * Needs Support: * Indexed Buffers * PreRotation support. */ ( function () { /** * Generates a loader for loading FBX files from URL and parsing into * a THREE.Group. * @param {THREE.LoadingManager} manager - Loading Manager for loader to use. */ THREE.FBXLoader = function ( manager ) { THREE.Loader.call( this ); this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; this.fileLoader = new THREE.FileLoader( this.manager ); this.textureLoader = new THREE.TextureLoader( this.manager ); }; Object.assign( THREE.FBXLoader.prototype, THREE.Loader.prototype ); THREE.FBXLoader.prototype.constructor = THREE.FBXLoader; Object.assign( THREE.FBXLoader.prototype, { /** * Loads an ASCII FBX file from URL and parses into a THREE.Group. * THREE.Group will have an animations property of AnimationClips * of the different animations exported with the FBX. * @param {string} url - URL of the FBX file. * @param {function(THREE.Group):void} onLoad - Callback for when FBX file is loaded and parsed. * @param {function(ProgressEvent):void} onProgress - Callback fired periodically when file is being retrieved from server. * @param {function(Event):void} onError - Callback fired when error occurs (Currently only with retrieving file, not with parsing errors). */ load: function ( url, onLoad, onProgress, onError ) { var self = this; var resourceDirectory = url.split( /[\\\/]/ ); resourceDirectory.pop(); resourceDirectory = resourceDirectory.join( '/' ); this.fileLoader.load( url, function ( text ) { if ( ! isFbxFormatASCII( text ) ) { console.error( 'FBXLoader: FBX Binary format not supported.' ); self.manager.itemError( url ); return; } if ( getFbxVersion( text ) < 7000 ) { console.error( 'FBXLoader: FBX version not supported for file at ' + url + ', FileVersion: ' + getFbxVersion( text ) ); self.manager.itemError( url ); return; } var scene = self.parse( text, resourceDirectory ); onLoad( scene ); }, onProgress, onError ); }, /** * Parses an ASCII FBX file and returns a THREE.Group. * THREE.Group will have an animations property of AnimationClips * of the different animations within the FBX file. * @param {string} FBXText - Contents of FBX file to parse. * @param {string} resourceDirectory - Directory to load external assets (e.g. textures ) from. * @returns {THREE.Group} */ parse: function ( FBXText, resourceDirectory ) { var loader = this; var FBXTree = new TextParser().parse( FBXText ); var connections = parseConnections( FBXTree ); var textures = parseTextures( FBXTree ); var materials = parseMaterials( FBXTree, textures, connections ); var deformerMap = parseDeformers( FBXTree, connections ); var geometryMap = parseGeometries( FBXTree, connections, deformerMap ); var sceneGraph = parseScene( FBXTree, connections, deformerMap, geometryMap, materials ); return sceneGraph; /** * @typedef {{value: number}} FBXValue */ /** * @typedef {{value: {x: string, y: string, z: string}}} FBXVector3 */ /** * @typedef {{properties: {a: string}}} FBXArrayNode */ /** * @typedef {{properties: {MappingInformationType: string, ReferenceInformationType: string }, subNodes: Object<string, FBXArrayNode>}} FBXMappedArrayNode */ /** * @typedef {{id: number, name: string, properties: {FileName: string}}} FBXTextureNode */ /** * @typedef {{id: number, attrName: string, properties: {ShadingModel: string, Diffuse: FBXVector3, Specular: FBXVector3, Shininess: FBXValue, Emissive: FBXVector3, EmissiveFactor: FBXValue, Opacity: FBXValue}}} FBXMaterialNode */ /** * @typedef {{subNodes: {Indexes: FBXArrayNode, Weights: FBXArrayNode, Transform: FBXArrayNode, TransformLink: FBXArrayNode}, properties: { Mode: string }}} FBXSubDeformerNode */ /** * @typedef {{id: number, attrName: string, attrType: string, subNodes: {Vertices: FBXArrayNode, PolygonVertexIndex: FBXArrayNode, LayerElementNormal: FBXMappedArrayNode[], LayerElementMaterial: FBXMappedArrayNode[], LayerElementUV: FBXMappedArrayNode[]}}} FBXGeometryNode */ /** * @typedef {{id: number, attrName: string, attrType: string, properties: {Lcl_Translation: FBXValue, Lcl_Rotation: FBXValue, Lcl_Scaling: FBXValue}}} FBXModelNode */ /** * Parses map of relationships between objects. * @param {{Connections: { properties: { connections: [number, number, string][]}}}} FBXTree * @returns {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} */ function parseConnections( FBXTree ) { /** * @type {Map<number, { parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} */ var connectionMap = new Map(); if ( 'Connections' in FBXTree ) { /** * @type {[number, number, string][]} */ var connectionArray = FBXTree.Connections.properties.connections; connectionArray.forEach( function ( connection ) { if ( ! connectionMap.has( connection[ 0 ] ) ) { connectionMap.set( connection[ 0 ], { parents: [], children: [] } ); } var parentRelationship = { ID: connection[ 1 ], relationship: connection[ 2 ] }; connectionMap.get( connection[ 0 ] ).parents.push( parentRelationship ); if ( ! connectionMap.has( connection[ 1 ] ) ) { connectionMap.set( connection[ 1 ], { parents: [], children: [] } ); } var childRelationship = { ID: connection[ 0 ], relationship: connection[ 2 ] }; connectionMap.get( connection[ 1 ] ).children.push( childRelationship ); } ); } return connectionMap; } /** * Parses map of textures referenced in FBXTree. * @param {{Objects: {subNodes: {Texture: Object.<string, FBXTextureNode>}}}} FBXTree * @returns {Map<number, THREE.Texture>} */ function parseTextures( FBXTree ) { /** * @type {Map<number, THREE.Texture>} */ var textureMap = new Map(); if ( 'Texture' in FBXTree.Objects.subNodes ) { var textureNodes = FBXTree.Objects.subNodes.Texture; for ( var nodeID in textureNodes ) { var texture = parseTexture( textureNodes[ nodeID ] ); textureMap.set( parseInt( nodeID ), texture ); } } return textureMap; /** * @param {textureNode} textureNode - Node to get texture information from. * @returns {THREE.Texture} */ function parseTexture( textureNode ) { var FBX_ID = textureNode.id; var name = textureNode.name; var filePath = textureNode.properties.FileName; var split = filePath.split( /[\\\/]/ ); if ( split.length > 0 ) { var fileName = split[ split.length - 1 ]; } else { var fileName = filePath; } /** * @type {THREE.Texture} */ var texture = loader.textureLoader.load( resourceDirectory + '/' + fileName ); texture.name = name; texture.FBX_ID = FBX_ID; return texture; } } /** * Parses map of Material information. * @param {{Objects: {subNodes: {Material: Object.<number, FBXMaterialNode>}}}} FBXTree * @param {Map<number, THREE.Texture>} textureMap * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections * @returns {Map<number, THREE.Material>} */ function parseMaterials( FBXTree, textureMap, connections ) { var materialMap = new Map(); if ( 'Material' in FBXTree.Objects.subNodes ) { var materialNodes = FBXTree.Objects.subNodes.Material; for ( var nodeID in materialNodes ) { var material = parseMaterial( materialNodes[ nodeID ], textureMap, connections ); materialMap.set( parseInt( nodeID ), material ); } } return materialMap; /** * Takes information from Material node and returns a generated THREE.Material * @param {FBXMaterialNode} materialNode * @param {Map<number, THREE.Texture>} textureMap * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections * @returns {THREE.Material} */ function parseMaterial( materialNode, textureMap, connections ) { var FBX_ID = materialNode.id; var name = materialNode.attrName; var type = materialNode.properties.ShadingModel; var children = connections.get( FBX_ID ).children; var parameters = parseParameters( materialNode.properties, textureMap, children ); var material; switch ( type ) { case 'phong': material = new THREE.MeshPhongMaterial(); break; case 'lambert': material = new THREE.MeshLambertMaterial(); break; default: console.warn( 'No implementation given for material type ' + type + ' in FBXLoader.js. Defaulting to basic material' ); material = new THREE.MeshBasicMaterial( { color: 0x3300ff } ); break; } material.setValues( parameters ); material.name = name; return material; /** * @typedef {{Diffuse: FBXVector3, Specular: FBXVector3, Shininess: FBXValue, Emissive: FBXVector3, EmissiveFactor: FBXValue, Opacity: FBXValue}} FBXMaterialProperties */ /** * @typedef {{color: THREE.Color=, specular: THREE.Color=, shininess: number=, emissive: THREE.Color=, emissiveIntensity: number=, opacity: number=, transparent: boolean=, map: THREE.Texture=}} THREEMaterialParameterPack */ /** * @param {FBXMaterialProperties} properties * @param {Map<number, THREE.Texture>} textureMap * @param {{ID: number, relationship: string}[]} childrenRelationships * @returns {THREEMaterialParameterPack} */ function parseParameters( properties, textureMap, childrenRelationships ) { var parameters = {}; if ( properties.Diffuse ) { parameters.color = parseColor( properties.Diffuse ); } if ( properties.Specular ) { parameters.specular = parseColor( properties.Specular ); } if ( properties.Shininess ) { parameters.shininess = properties.Shininess.value; } if ( properties.Emissive ) { parameters.emissive = parseColor( properties.Emissive ); } if ( properties.EmissiveFactor ) { parameters.emissiveIntensity = properties.EmissiveFactor.value; } if ( properties.Opacity ) { parameters.opacity = properties.Opacity.value; } if ( parameters.opacity < 1.0 ) { parameters.transparent = true; } childrenRelationships.forEach( function ( relationship ) { var type = relationship.relationship; switch ( type ) { case " \"AmbientColor": //TODO: Support AmbientColor textures break; case " \"DiffuseColor": parameters.map = textureMap.get( relationship.ID ); break; default: console.warn( 'Unknown texture application of type ' + type + ', skipping texture' ); break; } } ); return parameters; } } } /** * Generates map of Skeleton-like objects for use later when generating and binding skeletons. * @param {{Objects: {subNodes: {Deformer: Object.<number, FBXSubDeformerNode>}}}} FBXTree * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections * @returns {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}>} */ function parseDeformers( FBXTree, connections ) { var skeletonMap = new Map(); if ( 'Deformer' in FBXTree.Objects.subNodes ) { var DeformerNodes = FBXTree.Objects.subNodes.Deformer; for ( var nodeID in DeformerNodes ) { var deformerNode = DeformerNodes[ nodeID ]; if ( deformerNode.attrType === 'Skin' ) { var conns = connections.get( parseInt( nodeID ) ); var skeleton = parseSkeleton( conns, DeformerNodes ); skeleton.FBX_ID = parseInt( nodeID ); skeletonMap.set( parseInt( nodeID ), skeleton ); } } } return skeletonMap; /** * Generates a "Skeleton Representation" of FBX nodes based on an FBX Skin Deformer's connections and an object containing SubDeformer nodes. * @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} connections * @param {Object.<number, FBXSubDeformerNode>} DeformerNodes * @returns {{map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}} */ function parseSkeleton( connections, DeformerNodes ) { var subDeformers = new Map(); var subDeformerArray = []; connections.children.forEach( function ( child ) { var subDeformerNode = DeformerNodes[ child.ID ]; var subDeformer = { FBX_ID: child.ID, indices: parseIntArray( subDeformerNode.subNodes.Indexes.properties.a ), weights: parseFloatArray( subDeformerNode.subNodes.Weights.properties.a ), transform: parseMatrixArray( subDeformerNode.subNodes.Transform.properties.a ), transformLink: parseMatrixArray( subDeformerNode.subNodes.TransformLink.properties.a ), linkMode: subDeformerNode.properties.Mode }; subDeformers.set( child.ID, subDeformer ); subDeformerArray.push( subDeformer ); } ); return { map: subDeformers, array: subDeformerArray, bones: [] }; } } /** * Generates Buffer geometries from geometry information in FBXTree, and generates map of THREE.BufferGeometries * @param {{Objects: {subNodes: {Geometry: Object.<number, FBXGeometryNode}}}} FBXTree * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections * @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}>} deformerMap * @returns {Map<number, THREE.BufferGeometry>} */ function parseGeometries( FBXTree, connections, deformerMap ) { var geometryMap = new Map(); if ( 'Geometry' in FBXTree.Objects.subNodes ) { var geometryNodes = FBXTree.Objects.subNodes.Geometry; for ( var nodeID in geometryNodes ) { var relationships = connections.get( parseInt( nodeID ) ); var geo = parseGeometry( geometryNodes[ nodeID ], relationships, deformerMap ); geometryMap.set( parseInt( nodeID ), geo ); } } return geometryMap; /** * Generates BufferGeometry from FBXGeometryNode. * @param {FBXGeometryNode} geometryNode * @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} relationships * @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[]}>} deformerMap * @returns {THREE.BufferGeometry} */ function parseGeometry( geometryNode, relationships, deformerMap ) { switch ( geometryNode.attrType ) { case 'Mesh': return parseMeshGeometry( geometryNode, relationships, deformerMap ); break; case 'NurbsCurve': return parseNurbsGeometry( geometryNode, relationships, deformerMap ); break; } /** * Specialty function for parsing Mesh based Geometry Nodes. * @param {FBXGeometryNode} geometryNode * @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} relationships - Object representing relationships between specific geometry node and other nodes. * @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[]}>} deformerMap - Map object of deformers and subDeformers by ID. * @returns {THREE.BufferGeometry} */ function parseMeshGeometry( geometryNode, relationships, deformerMap ) { var FBX_ID = geometryNode.id; var name = geometryNode.attrName; for ( var i = 0; i < relationships.children.length; ++ i ) { if ( deformerMap.has( relationships.children[ i ].ID ) ) { var deformer = deformerMap.get( relationships.children[ i ].ID ); break; } } var geometry = genGeometry( geometryNode, deformer ); return geometry; /** * @param {{map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[]}} deformer - Skeleton representation for geometry instance. * @returns {THREE.BufferGeometry} */ function genGeometry( geometryNode, deformer ) { var geometry = new Geometry(); //First, each index is going to be its own vertex. var vertexBuffer = parseFloatArray( geometryNode.subNodes.Vertices.properties.a ); var indexBuffer = parseIntArray( geometryNode.subNodes.PolygonVertexIndex.properties.a ); if ( 'LayerElementNormal' in geometryNode.subNodes ) { var normalInfo = getNormals( geometryNode ); } if ( 'LayerElementUV' in geometryNode.subNodes ) { var uvInfo = getUVs( geometryNode ); } if ( 'LayerElementMaterial' in geometryNode.subNodes ) { var materialInfo = getMaterials( geometryNode ); } var faceVertexBuffer = []; var polygonIndex = 0; for ( var polygonVertexIndex = 0; polygonVertexIndex < indexBuffer.length; ++ polygonVertexIndex ) { var endOfFace; var vertexIndex = indexBuffer[ polygonVertexIndex ]; if ( indexBuffer[ polygonVertexIndex ] < 0 ) { vertexIndex = vertexIndex ^ - 1; indexBuffer[ polygonVertexIndex ] = vertexIndex; endOfFace = true; } var vertex = new Vertex(); var weightIndices = []; var weights = []; vertex.position.fromArray( vertexBuffer, vertexIndex * 3 ); // If we have a deformer for this geometry, get the skinIndex and skinWeights for this object. // They are stored as vertex indices on each deformer, and we need them as deformer indices // for each vertex. if ( deformer ) { for ( var j = 0; j < deformer.array.length; ++ j ) { var index = deformer.array[ j ].indices.findIndex( function ( index ) { return index === indexBuffer[ polygonVertexIndex ]; } ); if ( index !== - 1 ) { weights.push( deformer.array[ j ].weights[ index ] ); weightIndices.push( j ); } } if ( weights.length > 4 ) { console.warn( 'FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.' ); var WIndex = [ 0, 0, 0, 0 ]; var Weight = [ 0, 0, 0, 0 ]; for ( var polygonVertexIndex = 0; polygonVertexIndex < weights.length; ++ polygonVertexIndex ) { var currentWeight = weights[ polygonVertexIndex ]; var currentIndex = weightIndices[ polygonVertexIndex ]; for ( var j = 0; j < Weight.length; ++ j ) { if ( currentWeight > Weight[ j ] ) { var tmp = Weight[ j ]; Weight[ j ] = currentWeight; currentWeight = tmp; tmp = WIndex[ j ]; WIndex[ j ] = currentIndex; currentIndex = tmp; } } } weightIndices = WIndex; weights = Weight; } for ( var i = weights.length; i < 4; i ++ ) { weights[ i ] = 0; weightIndices[ i ] = 0; } vertex.skinWeights.fromArray( weights ); vertex.skinIndices.fromArray( weightIndices ); //vertex.skinWeights.normalize(); } if ( normalInfo ) { vertex.normal.fromArray( getData( polygonVertexIndex, polygonIndex, vertexIndex, normalInfo ) ); } if ( uvInfo ) { vertex.uv.fromArray( getData( polygonVertexIndex, polygonIndex, vertexIndex, uvInfo ) ); } //Add vertex to face buffer. faceVertexBuffer.push( vertex ); // If index was negative to start with, we have finished this individual face // and can generate the face data to the geometry. if ( endOfFace ) { var face = new Face(); var materials = getData( polygonVertexIndex, polygonIndex, vertexIndex, materialInfo ); face.genTrianglesFromVertices( faceVertexBuffer ); face.materialIndex = materials[ 0 ]; geometry.faces.push( face ); faceVertexBuffer = []; polygonIndex ++; endOfFace = false; } } /** * @type {{vertexBuffer: number[], normalBuffer: number[], uvBuffer: number[], skinIndexBuffer: number[], skinWeightBuffer: number[], materialIndexBuffer: number[]}} */ var bufferInfo = geometry.flattenToBuffers(); var geo = new THREE.BufferGeometry(); geo.name = geometryNode.name; geo.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( bufferInfo.vertexBuffer ), 3 ) ); if ( bufferInfo.normalBuffer.length > 0 ) { geo.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( bufferInfo.normalBuffer ), 3 ) ); } if ( bufferInfo.uvBuffer.length > 0 ) { geo.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( bufferInfo.uvBuffer ), 2 ) ); } if ( deformer ) { geo.addAttribute( 'skinIndex', new THREE.BufferAttribute( new Float32Array( bufferInfo.skinIndexBuffer ), 4 ) ); geo.addAttribute( 'skinWeight', new THREE.BufferAttribute( new Float32Array( bufferInfo.skinWeightBuffer ), 4 ) ); geo.FBX_Deformer = deformer; } // Convert the material indices of each vertex into rendering groups on the geometry. var prevMaterialIndex = bufferInfo.materialIndexBuffer[ 0 ]; var startIndex = 0; for ( var materialBufferIndex = 0; materialBufferIndex < bufferInfo.materialIndexBuffer.length; ++ materialBufferIndex ) { if ( bufferInfo.materialIndexBuffer[ materialBufferIndex ] !== prevMaterialIndex ) { geo.addGroup( startIndex, materialBufferIndex - startIndex, prevMaterialIndex ); startIndex = materialBufferIndex; prevMaterialIndex = bufferInfo.materialIndexBuffer[ materialBufferIndex ]; } } return geo; /** * Parses normal information for geometry. * @param {FBXGeometryNode} geometryNode * @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} */ function getNormals( geometryNode ) { var NormalNode = geometryNode.subNodes.LayerElementNormal[ 0 ]; var mappingType = NormalNode.properties.MappingInformationType; var referenceType = NormalNode.properties.ReferenceInformationType; var buffer = parseFloatArray( NormalNode.subNodes.Normals.properties.a ); var indexBuffer = []; if ( referenceType === 'IndexToDirect' ) { indexBuffer = parseIntArray( NormalNode.subNodes.NormalIndex.properties.a ); } return { dataSize: 3, buffer: buffer, indices: indexBuffer, mappingType: mappingType, referenceType: referenceType }; } /** * Parses UV information for geometry. * @param {FBXGeometryNode} geometryNode * @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} */ function getUVs( geometryNode ) { var UVNode = geometryNode.subNodes.LayerElementUV[ 0 ]; var mappingType = UVNode.properties.MappingInformationType; var referenceType = UVNode.properties.ReferenceInformationType; var buffer = parseFloatArray( UVNode.subNodes.UV.properties.a ); var indexBuffer = []; if ( referenceType === 'IndexToDirect' ) { indexBuffer = parseIntArray( UVNode.subNodes.UVIndex.properties.a ); } return { dataSize: 2, buffer: buffer, indices: indexBuffer, mappingType: mappingType, referenceType: referenceType }; } /** * Parses material application information for geometry. * @param {FBXGeometryNode} * @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} */ function getMaterials( geometryNode ) { var MaterialNode = geometryNode.subNodes.LayerElementMaterial[ 0 ]; var mappingType = MaterialNode.properties.MappingInformationType; var referenceType = MaterialNode.properties.ReferenceInformationType; var materialIndexBuffer = parseIntArray( MaterialNode.subNodes.Materials.properties.a ); // Since materials are stored as indices, there's a bit of a mismatch between FBX and what // we expect. So we create an intermediate buffer that points to the index in the buffer, // for conforming with the other functions we've written for other data. var materialIndices = []; materialIndexBuffer.forEach( function ( materialIndex, index ) { materialIndices.push( index ); } ); return { dataSize: 1, buffer: materialIndexBuffer, indices: materialIndices, mappingType: mappingType, referenceType: referenceType }; } /** * Function uses the infoObject and given indices to return value array of object. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex). * @param {number} polygonIndex - Index of polygon in geometry. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore). * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data. * @returns {number[]} */ function getData( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) { var GetData = { ByPolygonVertex: { /** * Function uses the infoObject and given indices to return value array of object. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex). * @param {number} polygonIndex - Index of polygon in geometry. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore). * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data. * @returns {number[]} */ Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) { return infoObject.buffer.slice( ( polygonVertexIndex * infoObject.dataSize ), ( polygonVertexIndex * infoObject.dataSize ) + infoObject.dataSize ); }, /** * Function uses the infoObject and given indices to return value array of object. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex). * @param {number} polygonIndex - Index of polygon in geometry. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore). * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data. * @returns {number[]} */ IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) { var index = infoObject.indices[ polygonVertexIndex ]; return infoObject.buffer.slice( ( index * infoObject.dataSize ), ( index * infoObject.dataSize ) + infoObject.dataSize ); } }, ByPolygon: { /** * Function uses the infoObject and given indices to return value array of object. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex). * @param {number} polygonIndex - Index of polygon in geometry. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore). * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data. * @returns {number[]} */ Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) { return infoObject.buffer.slice( polygonIndex * infoObject.dataSize, polygonIndex * infoObject.dataSize + infoObject.dataSize ); }, /** * Function uses the infoObject and given indices to return value array of object. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex). * @param {number} polygonIndex - Index of polygon in geometry. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore). * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data. * @returns {number[]} */ IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) { var index = infoObject.indices[ polygonIndex ]; return infoObject.buffer.slice( index * infoObject.dataSize, index * infoObject.dataSize + infoObject.dataSize ); } }, AllSame: { /** * Function uses the infoObject and given indices to return value array of object. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex). * @param {number} polygonIndex - Index of polygon in geometry. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore). * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data. * @returns {number[]} */ IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) { return infoObject.buffer.slice( infoObject.indices[ 0 ] * infoObject.dataSize, infoObject.indices[ 0 ] * infoObject.dataSize + infoObject.dataSize ); } } }; return GetData[ infoObject.mappingType ][ infoObject.referenceType ]( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ); } } } /** * Specialty function for parsing NurbsCurve based Geometry Nodes. * @param {FBXGeometryNode} geometryNode * @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} relationships * @returns {THREE.BufferGeometry} */ function parseNurbsGeometry( geometryNode, relationships ) { if ( THREE.NURBSCurve === undefined ) { console.error( "THREE.FBXLoader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry." ); return new THREE.BufferGeometry(); } var order = parseInt( geometryNode.properties.Order ); if ( isNaN( order ) ) { console.error( "FBXLoader: Invalid Order " + geometryNode.properties.Order + " given for geometry ID: " + geometryNode.id ); return new THREE.BufferGeometry(); } var knots = parseFloatArray( geometryNode.subNodes.KnotVector.properties.a ); var controlPoints = []; var pointsValues = parseFloatArray( geometryNode.subNodes.Points.properties.a ); for ( var i = 0; i < pointsValues.length; i += 4 ) { controlPoints.push( new THREE.Vector4( pointsValues[ i ], pointsValues[ i + 1 ], pointsValues[ i + 2 ], pointsValues[ i + 3 ] ) ); } if ( geometryNode.properties.Form === 'Closed' ) { controlPoints.push( controlPoints[ 0 ] ); } var curve = new THREE.NURBSCurve( order - 1, knots, controlPoints ); var vertices = curve.getPoints( controlPoints.length * 1.5 ); var vertexBuffer = []; vertices.forEach( function ( position ) { var array = position.toArray(); vertexBuffer = vertexBuffer.concat( array ); } ); var geometry = new THREE.BufferGeometry(); geometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( vertexBuffer ), 3 ) ); return geometry; } } } /** * Finally generates Scene graph and Scene graph Objects. * @param {{Objects: {subNodes: {Model: Object.<number, FBXModelNode>}}}} FBXTree * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections * @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}>} deformerMap * @param {Map<number, THREE.BufferGeometry>} geometryMap * @param {Map<number, THREE.Material>} materialMap * @returns {THREE.Group} */ function parseScene( FBXTree, connections, deformerMap, geometryMap, materialMap ) { var sceneGraph = new THREE.Group(); var ModelNode = FBXTree.Objects.subNodes.Model; /** * @type {Array.<THREE.Object3D>} */ var modelArray = []; /** * @type {Map.<number, THREE.Object3D>} */ var modelMap = new Map(); for ( var nodeID in ModelNode ) { var id = parseInt( nodeID ); var node = ModelNode[ nodeID ]; var conns = connections.get( id ); var model = null; for ( var i = 0; i < conns.parents.length; ++ i ) { deformerMap.forEach( function ( deformer ) { if ( deformer.map.has( conns.parents[ i ].ID ) ) { model = new THREE.Bone(); var index = deformer.array.findIndex( function ( subDeformer ) { return subDeformer.FBX_ID === conns.parents[ i ].ID; } ); deformer.bones[ index ] = model; } } ); } if ( ! model ) { switch ( node.attrType ) { case "Mesh": /** * @type {?THREE.BufferGeometry} */ var geometry = null; /** * @type {THREE.MultiMaterial|THREE.Material} */ var material = null; /** * @type {Array.<THREE.Material>} */ var materials = []; conns.children.forEach( function ( child ) { if ( geometryMap.has( child.ID ) ) { geometry = geometryMap.get( child.ID ); } if ( materialMap.has( child.ID ) ) { materials.push( materialMap.get( child.ID ) ); } } ); if ( materials.length > 1 ) { material = new THREE.MultiMaterial( materials ); } else if ( materials.length > 0 ) { material = materials[ 0 ]; } else { material = new THREE.MeshBasicMaterial( { color: 0x3300ff } ); } if ( geometry.FBX_Deformer ) { materials.forEach( function ( material ) { material.skinning = true; } ); material.skinning = true; model = new THREE.SkinnedMesh( geometry, material ); } else { model = new THREE.Mesh( geometry, material ); } break; case "NurbsCurve": var geometry = null; conns.children.forEach( function ( child ) { if ( geometryMap.has( child.ID ) ) { geometry = geometryMap.get( child.ID ); } } ); // FBX does not list materials for Nurbs lines, so we'll just put our own in here. material = new THREE.LineBasicMaterial( { color: 0x3300ff, linewidth: 5 } ); model = new THREE.Line( geometry, material ); break; default: model = new THREE.Object3D(); break; } } model.name = node.attrName.replace( /:/, '' ).replace( /_/, '' ).replace( /-/, '' ); model.FBX_ID = id; modelArray.push( model ); modelMap.set( id, model ); } modelArray.forEach( function ( model ) { var node = ModelNode[ model.FBX_ID ]; if ( 'Lcl_Translation' in node.properties ) { model.position.fromArray( parseFloatArray( node.properties.Lcl_Translation.value ) ); } if ( 'Lcl_Rotation' in node.properties ) { var rotation = parseFloatArray( node.properties.Lcl_Rotation.value ).map( function ( value ) { return value * Math.PI / 180; } ); rotation.push( 'ZYX' ); model.rotation.fromArray( rotation ); } if ( 'Lcl_Scaling' in node.properties ) { model.scale.fromArray( parseFloatArray( node.properties.Lcl_Scaling.value ) ); } var conns = connections.get( model.FBX_ID ); for ( var parentIndex = 0; parentIndex < conns.parents.length; parentIndex ++ ) { var pIndex = modelArray.findIndex( function ( mod ) { return mod.FBX_ID === conns.parents[ parentIndex ].ID; } ); if ( pIndex > - 1 ) { modelArray[ pIndex ].add( model ); break; } } if ( model.parent === null ) { sceneGraph.add( model ); } } ); // Now with the bones created, we can update the skeletons and bind them to the skinned meshes. sceneGraph.updateMatrixWorld( true ); // Put skeleton into bind pose. var BindPoseNode = FBXTree.Objects.subNodes.Pose; for ( var nodeID in BindPoseNode ) { if ( BindPoseNode[ nodeID ].attrType === 'BindPose' ) { BindPoseNode = BindPoseNode[ nodeID ]; break; } } if ( BindPoseNode ) { var PoseNode = BindPoseNode.subNodes.PoseNode; var worldMatrices = new Map(); PoseNode.forEach( function ( node ) { var rawMatWrd = parseMatrixArray( node.subNodes.Matrix.properties.a ); worldMatrices.set( parseInt( node.id ), rawMatWrd ); } ); } deformerMap.forEach( function ( deformer, FBX_ID ) { deformer.array.forEach( function ( subDeformer, subDeformerIndex ) { /** * @type {THREE.Bone} */ var bone = deformer.bones[ subDeformerIndex ]; if ( ! worldMatrices.has( bone.FBX_ID ) ) { return; } var mat = worldMatrices.get( bone.FBX_ID ); bone.matrixWorld.copy( mat ); } ); // Now that skeleton is in bind pose, bind to model. deformer.skeleton = new THREE.Skeleton( deformer.bones ); var conns = connections.get( FBX_ID ); conns.parents.forEach( function ( parent ) { if ( geometryMap.has( parent.ID ) ) { var geoID = parent.ID; var geoConns = connections.get( geoID ); for ( var i = 0; i < geoConns.parents.length; ++ i ) { if ( modelMap.has( geoConns.parents[ i ].ID ) ) { var model = modelMap.get( geoConns.parents[ i ].ID ); //ASSERT model typeof SkinnedMesh model.bind( deformer.skeleton, model.matrixWorld ); break; } } } } ); } ); // Skeleton is now bound, we are now free to set up the // scene graph. modelArray.forEach( function ( model ) { var node = ModelNode[ model.FBX_ID ]; if ( 'Lcl_Translation' in node.properties ) { model.position.fromArray( parseFloatArray( node.properties.Lcl_Translation.value ) ); } if ( 'Lcl_Rotation' in node.properties ) { var rotation = parseFloatArray( node.properties.Lcl_Rotation.value ).map( function ( value ) { return value * Math.PI / 180; } ); rotation.push( 'ZYX' ); model.rotation.fromArray( rotation ); } if ( 'Lcl_Scaling' in node.properties ) { model.scale.fromArray( parseFloatArray( node.properties.Lcl_Scaling.value ) ); } } ); // Silly hack with the animation parsing. We're gonna pretend the scene graph has a skeleton // to attach animations to, since FBXs treat animations as animations for the entire scene, // not just for individual objects. sceneGraph.skeleton = { bones: modelArray }; var animations = parseAnimations( FBXTree, connections, sceneGraph ); addAnimations( sceneGraph, animations ); return sceneGraph; } /** * Parses animation information from FBXTree and generates an AnimationInfoObject. * @param {{Objects: {subNodes: {AnimationCurveNode: any, AnimationCurve: any, AnimationLayer: any, AnimationStack: any}}}} FBXTree * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections */ function parseAnimations( FBXTree, connections, sceneGraph ) { var rawNodes = FBXTree.Objects.subNodes.AnimationCurveNode; var rawCurves = FBXTree.Objects.subNodes.AnimationCurve; var rawLayers = FBXTree.Objects.subNodes.AnimationLayer; var rawStacks = FBXTree.Objects.subNodes.AnimationStack; /** * @type {{ curves: Map<number, { T: { id: number; attr: string; internalID: number; attrX: boolean; attrY: boolean; attrZ: boolean; containerBoneID: number; containerID: number; curves: { x: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; y: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; z: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; }; }, R: { id: number; attr: string; internalID: number; attrX: boolean; attrY: boolean; attrZ: boolean; containerBoneID: number; containerID: number; curves: { x: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; y: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; z: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; }; }, S: { id: number; attr: string; internalID: number; attrX: boolean; attrY: boolean; attrZ: boolean; containerBoneID: number; containerID: number; curves: { x: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; y: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; z: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; }; } }>, layers: Map<number, { T: { id: number; attr: string; internalID: number; attrX: boolean; attrY: boolean; attrZ: boolean; containerBoneID: number; containerID: number; curves: { x: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; y: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; z: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; }, }, R: { id: number; attr: string; internalID: number; attrX: boolean; attrY: boolean; attrZ: boolean; containerBoneID: number; containerID: number; curves: { x: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; y: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; z: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; }, }, S: { id: number; attr: string; internalID: number; attrX: boolean; attrY: boolean; attrZ: boolean; containerBoneID: number; containerID: number; curves: { x: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; y: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; z: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; }, } }[]>, stacks: Map<number, { name: string, layers: { T: { id: number; attr: string; internalID: number; attrX: boolean; attrY: boolean; attrZ: boolean; containerBoneID: number; containerID: number; curves: { x: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; y: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; z: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; }; }; R: { id: number; attr: string; internalID: number; attrX: boolean; attrY: boolean; attrZ: boolean; containerBoneID: number; containerID: number; curves: { x: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; y: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; z: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; }; }; S: { id: number; attr: string; internalID: number; attrX: boolean; attrY: boolean; attrZ: boolean; containerBoneID: number; containerID: number; curves: { x: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; y: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; z: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; }; }; }[][], length: number, frames: number }>, length: number, fps: number, frames: number }} */ var returnObject = { curves: new Map(), layers: new Map(), stacks: new Map(), length: 0, fps: 30, frames: 0 }; /** * @type {Array.<{ id: number; attr: string; internalID: number; attrX: boolean; attrY: boolean; attrZ: boolean; containerBoneID: number; containerID: number; }>} */ var animationCurveNodes = []; for ( var nodeID in rawNodes ) { if ( nodeID.match( /\d+/ ) ) { var animationNode = parseAnimationNode( FBXTree, rawNodes[ nodeID ], connections, sceneGraph ); animationCurveNodes.push( animationNode ); } } /** * @type {Map.<number, { id: number, attr: string, internalID: number, attrX: boolean, attrY: boolean, attrZ: boolean, containerBoneID: number, containerID: number, curves: { x: { version: any, id: number, internalID: number, times: number[], values: number[], attrFlag: number[], attrData: number[], }, y: { version: any, id: number, internalID: number, times: number[], values: number[], attrFlag: number[], attrData: number[], }, z: { version: any, id: number, internalID: number, times: number[], values: number[], attrFlag: number[], attrData: number[], } } }>} */ var tmpMap = new Map(); for ( var animationCurveNodeIndex = 0; animationCurveNodeIndex < animationCurveNodes.length; ++ animationCurveNodeIndex ) { if ( animationCurveNodes[ animationCurveNodeIndex ] === null ) { continue; } tmpMap.set( animationCurveNodes[ animationCurveNodeIndex ].id, animationCurveNodes[ animationCurveNodeIndex ] ); } /** * @type {{ version: any, id: number, internalID: number, times: number[], values: number[], attrFlag: number[], attrData: number[], }[]} */ var animationCurves = []; for ( nodeID in rawCurves ) { if ( nodeID.match( /\d+/ ) ) { var animationCurve = parseAnimationCurve( rawCurves[ nodeID ] ); animationCurves.push( animationCurve ); var firstParentConn = connections.get( animationCurve.id ).parents[ 0 ]; var firstParentID = firstParentConn.ID; var firstParentRelationship = firstParentConn.relationship; var axis = ''; if ( firstParentRelationship.match( /X/ ) ) { axis = 'x'; } else if ( firstParentRelationship.match( /Y/ ) ) { axis = 'y'; } else if ( firstParentRelationship.match( /Z/ ) ) { axis = 'z'; } else { continue; } tmpMap.get( firstParentID ).curves[ axis ] = animationCurve; } } tmpMap.forEach( function ( curveNode ) { var id = curveNode.containerBoneID; if ( ! returnObject.curves.has( id ) ) { returnObject.curves.set( id, { T: null, R: null, S: null } ); } returnObject.curves.get( id )[ curveNode.attr ] = curveNode; } ); for ( var nodeID in rawLayers ) { /** * @type {{ T: { id: number; attr: string; internalID: number; attrX: boolean; attrY: boolean; attrZ: boolean; containerBoneID: number; containerID: number; curves: { x: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; y: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; z: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; }, }, R: { id: number; attr: string; internalID: number; attrX: boolean; attrY: boolean; attrZ: boolean; containerBoneID: number; containerID: number; curves: { x: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; y: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; z: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; }, }, S: { id: number; attr: string; internalID: number; attrX: boolean; attrY: boolean; attrZ: boolean; containerBoneID: number; containerID: number; curves: { x: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; y: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; z: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; }, } }[]} */ var layer = []; var children = connections.get( parseInt( nodeID ) ).children; for ( var childIndex = 0; childIndex < children.length; childIndex ++ ) { // Skip lockInfluenceWeights if ( tmpMap.has( children[ childIndex ].ID ) ) { var curveNode = tmpMap.get( children[ childIndex ].ID ); var boneID = curveNode.containerBoneID; if ( layer[ boneID ] === undefined ) { layer[ boneID ] = { T: null, R: null, S: null }; } layer[ boneID ][ curveNode.attr ] = curveNode; } } returnObject.layers.set( parseInt( nodeID ), layer ); } for ( var nodeID in rawStacks ) { var layers = []; var children = connections.get( parseInt( nodeID ) ).children; var maxTimeStamp = 0; var minTimeStamp = Number.MAX_VALUE; for ( var childIndex = 0; childIndex < children.length; ++ childIndex ) { if ( returnObject.layers.has( children[ childIndex ].ID ) ) { var currentLayer = returnObject.layers.get( children[ childIndex ].ID ); layers.push( currentLayer ); currentLayer.forEach( function ( layer ) { if ( layer ) { getCurveNodeMaxMinTimeStamps( layer ); } /** * Sets the maxTimeStamp and minTimeStamp variables if it has timeStamps that are either larger or smaller * than the max or min respectively. * @param {{ T: { id: number, attr: string, internalID: number, attrX: boolean, attrY: boolean, attrZ: boolean, containerBoneID: number, containerID: number, curves: { x: { version: any, id: number, internalID: number, times: number[], values: number[], attrFlag: number[], attrData: number[], }, y: { version: any, id: number, internalID: number, times: number[], values: number[], attrFlag: number[], attrData: number[], }, z: { version: any, id: number, internalID: number, times: number[], values: number[], attrFlag: number[], attrData: number[], }, }, }, R: { id: number, attr: string, internalID: number, attrX: boolean, attrY: boolean, attrZ: boolean, containerBoneID: number, containerID: number, curves: { x: { version: any, id: number, internalID: number, times: number[], values: number[], attrFlag: number[], attrData: number[], }, y: { version: any, id: number, internalID: number, times: number[], values: number[], attrFlag: number[], attrData: number[], }, z: { version: any, id: number, internalID: number, times: number[], values: number[], attrFlag: number[], attrData: number[], }, }, }, S: { id: number, attr: string, internalID: number, attrX: boolean, attrY: boolean, attrZ: boolean, containerBoneID: number, containerID: number, curves: { x: { version: any, id: number, internalID: number, times: number[], values: number[], attrFlag: number[], attrData: number[], }, y: { version: any, id: number, internalID: number, times: number[], values: number[], attrFlag: number[], attrData: number[], }, z: { version: any, id: number, internalID: number, times: number[], values: number[], attrFlag: number[], attrData: number[], }, }, }, }} layer */ function getCurveNodeMaxMinTimeStamps( layer ) { /** * Sets the maxTimeStamp and minTimeStamp if one of the curve's time stamps * exceeds the maximum or minimum. * @param {{ x: { version: any, id: number, internalID: number, times: number[], values: number[], attrFlag: number[], attrData: number[], }, y: { version: any, id: number, internalID: number, times: number[], values: number[], attrFlag: number[], attrData: number[], }, z: { version: any, id: number, internalID: number, times: number[], values: number[], attrFlag: number[], attrData: number[], } }} curve */ function getCurveMaxMinTimeStamp( curve ) { /** * Sets the maxTimeStamp and minTimeStamp if one of its timestamps exceeds the maximum or minimum. * @param {{times: number[]}} axis */ function getCurveAxisMaxMinTimeStamps( axis ) { maxTimeStamp = axis.times[ axis.times.length - 1 ] > maxTimeStamp ? axis.times[ axis.times.length - 1 ] : maxTimeStamp; minTimeStamp = axis.times[ 0 ] < minTimeStamp ? axis.times[ 0 ] : minTimeStamp; } if ( curve.x ) { getCurveAxisMaxMinTimeStamps( curve.x ); } if ( curve.y ) { getCurveAxisMaxMinTimeStamps( curve.y ); } if ( curve.z ) { getCurveAxisMaxMinTimeStamps( curve.z ); } } if ( layer.R ) { getCurveMaxMinTimeStamp( layer.R.curves ); } if ( layer.S ) { getCurveMaxMinTimeStamp( layer.S.curves ); } if ( layer.T ) { getCurveMaxMinTimeStamp( layer.T.curves ); } } } ); } } // Do we have an animation clip with actual length? if ( maxTimeStamp > minTimeStamp ) { returnObject.stacks.set( parseInt( nodeID ), { name: rawStacks[ nodeID ].attrName, layers: layers, length: maxTimeStamp - minTimeStamp, frames: ( maxTimeStamp - minTimeStamp ) * 30 } ); } } return returnObject; /** * @param {Object} FBXTree * @param {{id: number, attrName: string, properties: Object<string, any>}} animationCurveNode * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections * @param {{skeleton: {bones: {FBX_ID: number}[]}}} sceneGraph */ function parseAnimationNode( FBXTree, animationCurveNode, connections, sceneGraph ) { var returnObject = { /** * @type {number} */ id: animationCurveNode.id, /** * @type {string} */ attr: animationCurveNode.attrName, /** * @type {number} */ internalID: animationCurveNode.id, /** * @type {boolean} */ attrX: false, /** * @type {boolean} */ attrY: false, /** * @type {boolean} */ attrZ: false, /** * @type {number} */ containerBoneID: - 1, /** * @type {number} */ containerID: - 1, curves: { x: null, y: null, z: null } }; if ( returnObject.attr.match( /S|R|T/ ) ) { for ( var attributeKey in animationCurveNode.properties ) { if ( attributeKey.match( /X/ ) ) { returnObject.attrX = true; } if ( attributeKey.match( /Y/ ) ) { returnObject.attrY = true; } if ( attributeKey.match( /Z/ ) ) { returnObject.attrZ = true; } } } else { return null; } var conns = connections.get( returnObject.id ); var containerIndices = conns.parents; for ( var containerIndicesIndex = containerIndices.length - 1; containerIndicesIndex >= 0; -- containerIndicesIndex ) { var boneID = sceneGraph.skeleton.bones.findIndex( function ( bone ) { return bone.FBX_ID === containerIndices[ containerIndicesIndex ].ID; } ); if ( boneID > - 1 ) { returnObject.containerBoneID = boneID; returnObject.containerID = containerIndices[ containerIndicesIndex ].ID; break; } } return returnObject; } /** * @param {{id: number, subNodes: {KeyTime: {properties: {a: string}}, KeyValueFloat: {properties: {a: string}}, KeyAttrFlags: {properties: {a: string}}, KeyAttrDataFloat: {properties: {a: string}}}}} animationCurve */ function parseAnimationCurve( animationCurve ) { return { version: null, id: animationCurve.id, internalID: animationCurve.id, times: parseFloatArray( animationCurve.subNodes.KeyTime.properties.a ).map( function ( time ) { return ConvertFBXTimeToSeconds( time ); } ), values: parseFloatArray( animationCurve.subNodes.KeyValueFloat.properties.a ), attrFlag: parseIntArray( animationCurve.subNodes.KeyAttrFlags.properties.a ), attrData: parseFloatArray( animationCurve.subNodes.KeyAttrDataFloat.properties.a ) }; } } /** * @param {{ curves: Map<number, { T: { id: number; attr: string; internalID: number; attrX: boolean; attrY: boolean; attrZ: boolean; containerBoneID: number; containerID: number; curves: { x: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; y: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; z: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; }; }; R: { id: number; attr: string; internalID: number; attrX: boolean; attrY: boolean; attrZ: boolean; containerBoneID: number; containerID: number; curves: { x: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; y: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; z: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; }; }; S: { id: number; attr: string; internalID: number; attrX: boolean; attrY: boolean; attrZ: boolean; containerBoneID: number; containerID: number; curves: { x: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; y: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; z: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; }; }; }>; layers: Map<number, { T: { id: number; attr: string; internalID: number; attrX: boolean; attrY: boolean; attrZ: boolean; containerBoneID: number; containerID: number; curves: { x: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; y: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; z: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; }; }; R: { id: number; attr: string; internalID: number; attrX: boolean; attrY: boolean; attrZ: boolean; containerBoneID: number; containerID: number; curves: { x: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; y: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; z: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; }; }; S: { id: number; attr: string; internalID: number; attrX: boolean; attrY: boolean; attrZ: boolean; containerBoneID: number; containerID: number; curves: { x: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; y: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; z: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; }; }; }[]>; stacks: Map<number, { name: string; layers: { T: { id: number; attr: string; internalID: number; attrX: boolean; attrY: boolean; attrZ: boolean; containerBoneID: number; containerID: number; curves: { x: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; y: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; z: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; }; }; R: { id: number; attr: string; internalID: number; attrX: boolean; attrY: boolean; attrZ: boolean; containerBoneID: number; containerID: number; curves: { x: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; y: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; z: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; }; }; S: { id: number; attr: string; internalID: number; attrX: boolean; attrY: boolean; attrZ: boolean; containerBoneID: number; containerID: number; curves: { x: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; y: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; z: { version: any; id: number; internalID: number; times: number[]; values: number[]; attrFlag: number[]; attrData: number[]; }; }; }; }[][]; length: number; frames: number; }>; length: number; fps: number; frames: number; }} animations, * @param {{skeleton: { bones: THREE.Bone[]}}} group */ function addAnimations( group, animations ) { if ( group.animations === undefined ) { group.animations = []; } animations.stacks.forEach( function ( stack ) { var animationData = { name: stack.name, fps: 30, length: stack.length, hierarchy: [] }; var bones = group.skeleton.bones; bones.forEach( function ( bone ) { var name = bone.name.replace( /.*:/, '' ); var parentIndex = bones.findIndex( function ( parentBone ) { return bone.parent === parentBone; } ); animationData.hierarchy.push( { parent: parentIndex, name: name, keys: [] } ); } ); for ( var frame = 0; frame < stack.frames; frame ++ ) { bones.forEach( function ( bone, boneIndex ) { var animationNode = stack.layers[ 0 ][ boneIndex ]; animationData.hierarchy.forEach( function ( node ) { if ( node.name === bone.name ) { node.keys.push( generateKey( animationNode, bone, frame ) ); } } ); } ); } group.animations.push( THREE.AnimationClip.parseAnimation( animationData, bones ) ); /** * @param {THREE.Bone} bone */ function generateKey( animationNode, bone, frame ) { var key = { time: frame / animations.fps, pos: bone.position.toArray(), rot: bone.quaternion.toArray(), scl: bone.scale.toArray() }; if ( animationNode === undefined ) { return key; } try { if ( hasCurve( animationNode, 'T' ) && hasKeyOnFrame( animationNode.T, frame ) ) { key.pos = [ animationNode.T.curves.x.values[ frame ], animationNode.T.curves.y.values[ frame ], animationNode.T.curves.z.values[ frame ] ]; } if ( hasCurve( animationNode, 'R' ) && hasKeyOnFrame( animationNode.R, frame ) ) { var rotationX = degreeToRadian( animationNode.R.curves.x.values[ frame ] ); var rotationY = degreeToRadian( animationNode.R.curves.y.values[ frame ] ); var rotationZ = degreeToRadian( animationNode.R.curves.z.values[ frame ] ); var euler = new THREE.Euler( rotationX, rotationY, rotationZ, 'ZYX' ); key.rot = new THREE.Quaternion().setFromEuler( euler ).toArray(); } if ( hasCurve( animationNode, 'S' ) && hasKeyOnFrame( animationNode.S, frame ) ) { key.scl = [ animationNode.S.curves.x.values[ frame ], animationNode.S.curves.y.values[ frame ], animationNode.S.curves.z.values[ frame ] ]; } } catch ( error ) { // Curve is not fully plotted. console.log( bone ); console.log( error ); } return key; function hasCurve( animationNode, attribute ) { if ( animationNode === undefined ) { return false; } var attributeNode = animationNode[ attribute ]; if ( ! attributeNode ) { return false; } return [ 'x', 'y', 'z' ].every( function ( key ) { return attributeNode.curves[ key ] !== undefined; } ); } function hasKeyOnFrame( attributeNode, frame ) { return [ 'x', 'y', 'z' ].every( function ( key ) { return isKeyExistOnFrame( attributeNode.curves[ key ], frame ); function isKeyExistOnFrame( curve, frame ) { return curve.values[ frame ] !== undefined; } } ); } } } ); } // UTILS /** * Parses Vector3 property from FBXTree. Property is given as .value.x, .value.y, etc. * @param {FBXVector3} property - Property to parse as Vector3. * @returns {THREE.Vector3} */ function parseVector3( property ) { return new THREE.Vector3( parseFloat( property.value.x ), parseFloat( property.value.y ), parseFloat( property.value.z ) ); } /** * Parses Color property from FBXTree. Property is given as .value.x, .value.y, etc. * @param {FBXVector3} property - Property to parse as Color. * @returns {THREE.Color} */ function parseColor( property ) { return new THREE.Color().fromArray( parseVector3( property ).toArray() ); } } } ); /** * An instance of a Vertex with data for drawing vertices to the screen. * @constructor */ function Vertex() { /** * Position of the vertex. * @type {THREE.Vector3} */ this.position = new THREE.Vector3( ); /** * Normal of the vertex * @type {THREE.Vector3} */ this.normal = new THREE.Vector3( ); /** * UV coordinates of the vertex. * @type {THREE.Vector2} */ this.uv = new THREE.Vector2( ); /** * Indices of the bones vertex is influenced by. * @type {THREE.Vector4} */ this.skinIndices = new THREE.Vector4( 0, 0, 0, 0 ); /** * Weights that each bone influences the vertex. * @type {THREE.Vector4} */ this.skinWeights = new THREE.Vector4( 0, 0, 0, 0 ); } Object.assign( Vertex.prototype, { copy: function ( target ) { var returnVar = target || new Vertex(); returnVar.position.copy( this.position ); returnVar.normal.copy( this.normal ); returnVar.uv.copy( this.uv ); returnVar.skinIndices.copy( this.skinIndices ); returnVar.skinWeights.copy( this.skinWeights ); return returnVar; }, flattenToBuffers: function () { var vertexBuffer = this.position.toArray(); var normalBuffer = this.normal.toArray(); var uvBuffer = this.uv.toArray(); var skinIndexBuffer = this.skinIndices.toArray(); var skinWeightBuffer = this.skinWeights.toArray(); return { vertexBuffer: vertexBuffer, normalBuffer: normalBuffer, uvBuffer: uvBuffer, skinIndexBuffer: skinIndexBuffer, skinWeightBuffer: skinWeightBuffer, }; } } ); /** * @constructor */ function Triangle() { /** * @type {{position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]} */ this.vertices = [ ]; } Object.assign( Triangle.prototype, { copy: function ( target ) { var returnVar = target || new Triangle(); for ( var i = 0; i < this.vertices.length; ++ i ) { this.vertices[ i ].copy( returnVar.vertices[ i ] ); } return returnVar; }, flattenToBuffers: function () { var vertexBuffer = []; var normalBuffer = []; var uvBuffer = []; var skinIndexBuffer = []; var skinWeightBuffer = []; this.vertices.forEach( function ( vertex ) { var flatVertex = vertex.flattenToBuffers(); vertexBuffer = vertexBuffer.concat( flatVertex.vertexBuffer ); normalBuffer = normalBuffer.concat( flatVertex.normalBuffer ); uvBuffer = uvBuffer.concat( flatVertex.uvBuffer ); skinIndexBuffer = skinIndexBuffer.concat( flatVertex.skinIndexBuffer ); skinWeightBuffer = skinWeightBuffer.concat( flatVertex.skinWeightBuffer ); } ); return { vertexBuffer: vertexBuffer, normalBuffer: normalBuffer, uvBuffer: uvBuffer, skinIndexBuffer: skinIndexBuffer, skinWeightBuffer: skinWeightBuffer, }; } } ); /** * @constructor */ function Face() { /** * @type {{vertices: {position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}[]} */ this.triangles = [ ]; this.materialIndex = 0; } Object.assign( Face.prototype, { copy: function ( target ) { var returnVar = target || new Face(); for ( var i = 0; i < this.triangles.length; ++ i ) { this.triangles[ i ].copy( returnVar.triangles[ i ] ); } returnVar.materialIndex = this.materialIndex; return returnVar; }, genTrianglesFromVertices: function ( vertexArray ) { for ( var i = 2; i < vertexArray.length; ++ i ) { var triangle = new Triangle(); triangle.vertices[ 0 ] = vertexArray[ 0 ]; triangle.vertices[ 1 ] = vertexArray[ i - 1 ]; triangle.vertices[ 2 ] = vertexArray[ i ]; this.triangles.push( triangle ); } }, flattenToBuffers: function () { var vertexBuffer = []; var normalBuffer = []; var uvBuffer = []; var skinIndexBuffer = []; var skinWeightBuffer = []; var materialIndexBuffer = []; var materialIndex = this.materialIndex; this.triangles.forEach( function ( triangle ) { var flatTriangle = triangle.flattenToBuffers(); vertexBuffer = vertexBuffer.concat( flatTriangle.vertexBuffer ); normalBuffer = normalBuffer.concat( flatTriangle.normalBuffer ); uvBuffer = uvBuffer.concat( flatTriangle.uvBuffer ); skinIndexBuffer = skinIndexBuffer.concat( flatTriangle.skinIndexBuffer ); skinWeightBuffer = skinWeightBuffer.concat( flatTriangle.skinWeightBuffer ); materialIndexBuffer = materialIndexBuffer.concat( [ materialIndex, materialIndex, materialIndex ] ); } ); return { vertexBuffer: vertexBuffer, normalBuffer: normalBuffer, uvBuffer: uvBuffer, skinIndexBuffer: skinIndexBuffer, skinWeightBuffer: skinWeightBuffer, materialIndexBuffer: materialIndexBuffer }; } } ); /** * @constructor */ function Geometry() { /** * @type {{triangles: {vertices: {position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}[], materialIndex: number}[]} */ this.faces = [ ]; /** * @type {{}|THREE.Skeleton} */ this.skeleton = null; } Object.assign( Geometry.prototype, { /** * @returns {{vertexBuffer: number[], normalBuffer: number[], uvBuffer: number[], skinIndexBuffer: number[], skinWeightBuffer: number[], materialIndexBuffer: number[]}} */ flattenToBuffers: function () { var vertexBuffer = []; var normalBuffer = []; var uvBuffer = []; var skinIndexBuffer = []; var skinWeightBuffer = []; var materialIndexBuffer = []; this.faces.forEach( function ( face ) { var flatFace = face.flattenToBuffers(); vertexBuffer = vertexBuffer.concat( flatFace.vertexBuffer ); normalBuffer = normalBuffer.concat( flatFace.normalBuffer ); uvBuffer = uvBuffer.concat( flatFace.uvBuffer ); skinIndexBuffer = skinIndexBuffer.concat( flatFace.skinIndexBuffer ); skinWeightBuffer = skinWeightBuffer.concat( flatFace.skinWeightBuffer ); materialIndexBuffer = materialIndexBuffer.concat( flatFace.materialIndexBuffer ); } ); return { vertexBuffer: vertexBuffer, normalBuffer: normalBuffer, uvBuffer: uvBuffer, skinIndexBuffer: skinIndexBuffer, skinWeightBuffer: skinWeightBuffer, materialIndexBuffer: materialIndexBuffer }; } } ); function TextParser() {} Object.assign( TextParser.prototype, { getPrevNode: function () { return this.nodeStack[ this.currentIndent - 2 ]; }, getCurrentNode: function () { return this.nodeStack[ this.currentIndent - 1 ]; }, getCurrentProp: function () { return this.currentProp; }, pushStack: function ( node ) { this.nodeStack.push( node ); this.currentIndent += 1; }, popStack: function () { this.nodeStack.pop(); this.currentIndent -= 1; }, setCurrentProp: function ( val, name ) { this.currentProp = val; this.currentPropName = name; }, // ----------parse --------------------------------------------------- parse: function ( text ) { this.currentIndent = 0; this.allNodes = new FBXTree(); this.nodeStack = []; this.currentProp = []; this.currentPropName = ''; var split = text.split( "\n" ); for ( var line in split ) { var l = split[ line ]; // short cut if ( l.match( /^[\s\t]*;/ ) ) { continue; } // skip comment line if ( l.match( /^[\s\t]*$/ ) ) { continue; } // skip empty line // beginning of node var beginningOfNodeExp = new RegExp( "^\\t{" + this.currentIndent + "}(\\w+):(.*){", '' ); var match = l.match( beginningOfNodeExp ); if ( match ) { var nodeName = match[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, "" ); var nodeAttrs = match[ 2 ].split( ',' ).map( function ( element ) { return element.trim().replace( /^"/, '' ).replace( /"$/, '' ); } ); this.parseNodeBegin( l, nodeName, nodeAttrs || null ); continue; } // node's property var propExp = new RegExp( "^\\t{" + ( this.currentIndent ) + "}(\\w+):[\\s\\t\\r\\n](.*)" ); var match = l.match( propExp ); if ( match ) { var propName = match[ 1 ].replace( /^"/, '' ).replace( /"$/, "" ).trim(); var propValue = match[ 2 ].replace( /^"/, '' ).replace( /"$/, "" ).trim(); this.parseNodeProperty( l, propName, propValue ); continue; } // end of node var endOfNodeExp = new RegExp( "^\\t{" + ( this.currentIndent - 1 ) + "}}" ); if ( l.match( endOfNodeExp ) ) { this.nodeEnd(); continue; } // for special case, // // Vertices: *8670 { // a: 0.0356229953467846,13.9599733352661,-0.399196773.....(snip) // -0.0612030513584614,13.960485458374,-0.409748703241348,-0.10..... // 0.12490539252758,13.7450733184814,-0.454119384288788,0.09272..... // 0.0836158767342567,13.5432004928589,-0.435397416353226,0.028..... // // these case the lines must contiue with previous line if ( l.match( /^[^\s\t}]/ ) ) { this.parseNodePropertyContinued( l ); } } return this.allNodes; }, parseNodeBegin: function ( line, nodeName, nodeAttrs ) { // var nodeName = match[1]; var node = { 'name': nodeName, properties: {}, 'subNodes': {} }; var attrs = this.parseNodeAttr( nodeAttrs ); var currentNode = this.getCurrentNode(); // a top node if ( this.currentIndent === 0 ) { this.allNodes.add( nodeName, node ); } else { // a subnode // already exists subnode, then append it if ( nodeName in currentNode.subNodes ) { var tmp = currentNode.subNodes[ nodeName ]; // console.log( "duped entry found\nkey: " + nodeName + "\nvalue: " + propValue ); if ( this.isFlattenNode( currentNode.subNodes[ nodeName ] ) ) { if ( attrs.id === '' ) { currentNode.subNodes[ nodeName ] = []; currentNode.subNodes[ nodeName ].push( tmp ); } else { currentNode.subNodes[ nodeName ] = {}; currentNode.subNodes[ nodeName ][ tmp.id ] = tmp; } } if ( attrs.id === '' ) { currentNode.subNodes[ nodeName ].push( node ); } else { currentNode.subNodes[ nodeName ][ attrs.id ] = node; } } else if ( typeof attrs.id === 'number' || attrs.id.match( /^\d+$/ ) ) { currentNode.subNodes[ nodeName ] = {}; currentNode.subNodes[ nodeName ][ attrs.id ] = node; } else { currentNode.subNodes[ nodeName ] = node; } } // for this ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ // NodeAttribute: 1001463072, "NodeAttribute::", "LimbNode" { if ( nodeAttrs ) { node.id = attrs.id; node.attrName = attrs.name; node.attrType = attrs.type; } this.pushStack( node ); }, parseNodeAttr: function ( attrs ) { var id = attrs[ 0 ]; if ( attrs[ 0 ] !== "" ) { id = parseInt( attrs[ 0 ] ); if ( isNaN( id ) ) { // PolygonVertexIndex: *16380 { id = attrs[ 0 ]; } } var name; var type; if ( attrs.length > 1 ) { name = attrs[ 1 ].replace( /^(\w+)::/, '' ); type = attrs[ 2 ]; } return { id: id, name: name || '', type: type || '' }; }, parseNodeProperty: function ( line, propName, propValue ) { var currentNode = this.getCurrentNode(); var parentName = currentNode.name; // special case parent node's is like "Properties70" // these chilren nodes must treat with careful if ( parentName !== undefined ) { var propMatch = parentName.match( /Properties(\d)+/ ); if ( propMatch ) { this.parseNodeSpecialProperty( line, propName, propValue ); return; } } // special case Connections if ( propName == 'C' ) { var connProps = propValue.split( ',' ).slice( 1 ); var from = parseInt( connProps[ 0 ] ); var to = parseInt( connProps[ 1 ] ); var rest = propValue.split( ',' ).slice( 3 ); propName = 'connections'; propValue = [ from, to ]; propValue = propValue.concat( rest ); if ( currentNode.properties[ propName ] === undefined ) { currentNode.properties[ propName ] = []; } } // special case Connections if ( propName == 'Node' ) { var id = parseInt( propValue ); currentNode.properties.id = id; currentNode.id = id; } // already exists in properties, then append this if ( propName in currentNode.properties ) { // console.log( "duped entry found\nkey: " + propName + "\nvalue: " + propValue ); if ( Array.isArray( currentNode.properties[ propName ] ) ) { currentNode.properties[ propName ].push( propValue ); } else { currentNode.properties[ propName ] += propValue; } } else { // console.log( propName + ": " + propValue ); if ( Array.isArray( currentNode.properties[ propName ] ) ) { currentNode.properties[ propName ].push( propValue ); } else { currentNode.properties[ propName ] = propValue; } } this.setCurrentProp( currentNode.properties, propName ); }, // TODO: parseNodePropertyContinued: function ( line ) { this.currentProp[ this.currentPropName ] += line; }, parseNodeSpecialProperty: function ( line, propName, propValue ) { // split this // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1 // into array like below // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ] var props = propValue.split( '",' ).map( function ( element ) { return element.trim().replace( /^\"/, '' ).replace( /\s/, '_' ); } ); var innerPropName = props[ 0 ]; var innerPropType1 = props[ 1 ]; var innerPropType2 = props[ 2 ]; var innerPropFlag = props[ 3 ]; var innerPropValue = props[ 4 ]; /* if ( innerPropValue === undefined ) { innerPropValue = props[3]; } */ // cast value in its type switch ( innerPropType1 ) { case "int": innerPropValue = parseInt( innerPropValue ); break; case "double": innerPropValue = parseFloat( innerPropValue ); break; case "ColorRGB": case "Vector3D": var tmp = innerPropValue.split( ',' ); innerPropValue = new THREE.Vector3( tmp[ 0 ], tmp[ 1 ], tmp[ 2 ] ); break; } // CAUTION: these props must append to parent's parent this.getPrevNode().properties[ innerPropName ] = { 'type': innerPropType1, 'type2': innerPropType2, 'flag': innerPropFlag, 'value': innerPropValue }; this.setCurrentProp( this.getPrevNode().properties, innerPropName ); }, nodeEnd: function () { this.popStack(); }, /* ---------------------------------------------------------------- */ /* util */ isFlattenNode: function ( node ) { return ( 'subNodes' in node && 'properties' in node ) ? true : false; } } ); function FBXTree() {} Object.assign( FBXTree.prototype, { add: function ( key, val ) { this[ key ] = val; }, searchConnectionParent: function ( id ) { if ( this.__cache_search_connection_parent === undefined ) { this.__cache_search_connection_parent = []; } if ( this.__cache_search_connection_parent[ id ] !== undefined ) { return this.__cache_search_connection_parent[ id ]; } else { this.__cache_search_connection_parent[ id ] = []; } var conns = this.Connections.properties.connections; var results = []; for ( var i = 0; i < conns.length; ++ i ) { if ( conns[ i ][ 0 ] == id ) { // 0 means scene root var res = conns[ i ][ 1 ] === 0 ? - 1 : conns[ i ][ 1 ]; results.push( res ); } } if ( results.length > 0 ) { this.__cache_search_connection_parent[ id ] = this.__cache_search_connection_parent[ id ].concat( results ); return results; } else { this.__cache_search_connection_parent[ id ] = [ - 1 ]; return [ - 1 ]; } }, searchConnectionChildren: function ( id ) { if ( this.__cache_search_connection_children === undefined ) { this.__cache_search_connection_children = []; } if ( this.__cache_search_connection_children[ id ] !== undefined ) { return this.__cache_search_connection_children[ id ]; } else { this.__cache_search_connection_children[ id ] = []; } var conns = this.Connections.properties.connections; var res = []; for ( var i = 0; i < conns.length; ++ i ) { if ( conns[ i ][ 1 ] == id ) { // 0 means scene root res.push( conns[ i ][ 0 ] === 0 ? - 1 : conns[ i ][ 0 ] ); // there may more than one kid, then search to the end } } if ( res.length > 0 ) { this.__cache_search_connection_children[ id ] = this.__cache_search_connection_children[ id ].concat( res ); return res; } else { this.__cache_search_connection_children[ id ] = [ ]; return [ ]; } }, searchConnectionType: function ( id, to ) { var key = id + ',' + to; // TODO: to hash if ( this.__cache_search_connection_type === undefined ) { this.__cache_search_connection_type = {}; } if ( this.__cache_search_connection_type[ key ] !== undefined ) { return this.__cache_search_connection_type[ key ]; } else { this.__cache_search_connection_type[ key ] = ''; } var conns = this.Connections.properties.connections; for ( var i = 0; i < conns.length; ++ i ) { if ( conns[ i ][ 0 ] == id && conns[ i ][ 1 ] == to ) { // 0 means scene root this.__cache_search_connection_type[ key ] = conns[ i ][ 2 ]; return conns[ i ][ 2 ]; } } this.__cache_search_connection_type[ id ] = null; return null; } } ); /** * @returns {boolean} */ function isFbxFormatASCII( text ) { var CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ]; var cursor = 0; var read = function ( offset ) { var result = text[ offset - 1 ]; text = text.slice( cursor + offset ); cursor ++; return result; }; for ( var i = 0; i < CORRECT.length; ++ i ) { var num = read( 1 ); if ( num == CORRECT[ i ] ) { return false; } } return true; } /** * @returns {number} */ function getFbxVersion( text ) { var versionRegExp = /FBXVersion: (\d+)/; var match = text.match( versionRegExp ); if ( match ) { var version = parseInt( match[ 1 ] ); return version; } throw new Error( 'FBXLoader: Cannot find the version number for the file given.' ); } /** * Converts FBX ticks into real time seconds. * @param {number} time - FBX tick timestamp to convert. * @returns {number} - FBX tick in real world time. */ function ConvertFBXTimeToSeconds( time ) { // Constant is FBX ticks per second. return time / 46186158000; } /** * Parses comma separated list of float numbers and returns them in an array. * @example * // Returns [ 5.6, 9.4, 2.5, 1.4 ] * parseFloatArray( "5.6,9.4,2.5,1.4" ) * @returns {number[]} */ function parseFloatArray( floatString ) { return floatString.split( ',' ).map( function ( stringValue ) { return parseFloat( stringValue ); } ); } /** * Parses comma separated list of int numbers and returns them in an array. * @example * // Returns [ 5, 8, 2, 3 ] * parseFloatArray( "5,8,2,3" ) * @returns {number[]} */ function parseIntArray( intString ) { return intString.split( ',' ).map( function ( stringValue ) { return parseInt( stringValue ); } ); } function parseMatrixArray( floatString ) { return new THREE.Matrix4().fromArray( parseFloatArray( floatString ) ); } /** * Converts number from degrees into radians. * @param {number} value * @returns {number} */ function degreeToRadian( value ) { return value * Math.PI / 180; } } )();
'use strict'; /** * @description * Private service to sanitize uris for links and images. Used by $compile and $sanitize. */ function $$SanitizeUriProvider() { var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/, imgSrcSanitizationWhitelist = /^\s*(https?|ftp|file):|data:image\//; /** * @description * Retrieves or overrides the default regular expression that is used for whitelisting of safe * urls during a[href] sanitization. * * The sanitization is a security measure aimed at prevent XSS attacks via html links. * * Any url about to be assigned to a[href] via data-binding is first normalized and turned into * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` * regular expression. If a match is found, the original url is written into the dom. Otherwise, * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. * * @param {RegExp=} regexp New regexp to whitelist urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ this.aHrefSanitizationWhitelist = function(regexp) { if (isDefined(regexp)) { aHrefSanitizationWhitelist = regexp; return this; } return aHrefSanitizationWhitelist; }; /** * @description * Retrieves or overrides the default regular expression that is used for whitelisting of safe * urls during img[src] sanitization. * * The sanitization is a security measure aimed at prevent XSS attacks via html links. * * Any url about to be assigned to img[src] via data-binding is first normalized and turned into * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` * regular expression. If a match is found, the original url is written into the dom. Otherwise, * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. * * @param {RegExp=} regexp New regexp to whitelist urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ this.imgSrcSanitizationWhitelist = function(regexp) { if (isDefined(regexp)) { imgSrcSanitizationWhitelist = regexp; return this; } return imgSrcSanitizationWhitelist; }; this.$get = function() { return function sanitizeUri(uri, isImage) { var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist; var normalizedVal; // NOTE: urlResolve() doesn't support IE < 8 so we don't sanitize for that case. if (!msie || msie >= 8 ) { normalizedVal = urlResolve(uri).href; if (normalizedVal !== '' && !normalizedVal.match(regex)) { return 'unsafe:'+normalizedVal; } } return uri; }; }; }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareLaptopMac = (props) => ( <SvgIcon {...props}> <path d="M20 18c1.1 0 1.99-.9 1.99-2L22 5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v11c0 1.1.9 2 2 2H0c0 1.1.9 2 2 2h20c1.1 0 2-.9 2-2h-4zM4 5h16v11H4V5zm8 14c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z"/> </SvgIcon> ); HardwareLaptopMac = pure(HardwareLaptopMac); HardwareLaptopMac.displayName = 'HardwareLaptopMac'; HardwareLaptopMac.muiName = 'SvgIcon'; export default HardwareLaptopMac;
module.exports = ChainInstance; function ChainInstance(chain, cb) { var instances = null; var loading = false; var queue = []; var load = function () { loading = true; chain.run(function (err, items) { instances = items; return next(); }); }; var promise = function(hwd, next) { return function () { if (!loading) { load(); } queue.push({ hwd: hwd, args: arguments }); return calls; }; }; var next = function () { if (queue.length === 0) return; var item = queue.shift(); item.hwd.apply(calls, item.args); }; var calls = { filter: promise(function (cb) { instances = instances.filter(cb); return next(); }), forEach: promise(function (cb) { instances.forEach(cb); return next(); }), sort: promise(function (cb) { instances.sort(cb); return next(); }), count: promise(function (cb) { cb(instances.length); return next(); }), get: promise(function (cb) { cb(instances); return next(); }), save: promise(function (cb) { var saveNext = function (i) { if (i >= instances.length) { if (typeof cb === "function") { cb(); } return next(); } return instances[i].save(function (err) { if (err) { if (typeof cb === "function") { cb(err); } return next(); } return saveNext(i + 1); }); }; return saveNext(0); }) }; if (typeof cb === "function") { return calls.forEach(cb); } return calls; }
YUI.add('editor-lists', function (Y, NAME) { /** * Handles list manipulation inside the Editor. Adds keyboard manipulation and execCommand support. * Adds overrides for the <a href="Plugin.ExecCommand.html#method_COMMANDS.insertorderedlist">insertorderedlist</a> * and <a href="Plugin.ExecCommand.html#method_COMMANDS.insertunorderedlist">insertunorderedlist</a> execCommands. * @class Plugin.EditorLists * @constructor * @extends Base * @module editor * @submodule editor-lists */ var EditorLists = function() { EditorLists.superclass.constructor.apply(this, arguments); }, LI = 'li', OL = 'ol', UL = 'ul', HOST = 'host'; Y.extend(EditorLists, Y.Base, { /** * Listener for host's nodeChange event and captures the tabkey interaction only when inside a list node. * @private * @method _onNodeChange * @param {Event} e The Event facade passed from the host. */ _onNodeChange: function(e) { var inst = this.get(HOST).getInstance(), li, newList, sTab, par, moved = false, tag, focusEnd = false; if (e.changedType === 'tab') { if (e.changedNode.test(LI + ', ' + LI + ' *')) { Y.log('Overriding TAB to move lists around', 'info', 'editorLists'); e.changedEvent.halt(); e.preventDefault(); li = e.changedNode; sTab = e.changedEvent.shiftKey; par = li.ancestor(OL + ',' + UL); tag = UL; if (par.get('tagName').toLowerCase() === OL) { tag = OL; } Y.log('ShiftKey: ' + sTab, 'info', 'editorLists'); if (!li.test(LI)) { li = li.ancestor(LI); } if (sTab) { if (li.ancestor(LI)) { Y.log('Shifting list up one level', 'info', 'editorLists'); li.ancestor(LI).insert(li, 'after'); moved = true; focusEnd = true; } } else { //li.setStyle('border', '1px solid red'); if (li.previous(LI)) { Y.log('Shifting list down one level', 'info', 'editorLists'); newList = inst.Node.create('<' + tag + '></' + tag + '>'); li.previous(LI).append(newList); newList.append(li); moved = true; } } } if (moved) { if (!li.test(LI)) { li = li.ancestor(LI); } li.all(EditorLists.REMOVE).remove(); if (Y.UA.ie) { li = li.append(EditorLists.NON).one(EditorLists.NON_SEL); } //Selection here.. Y.log('Selecting the new node', 'info', 'editorLists'); (new inst.EditorSelection()).selectNode(li, true, focusEnd); } } }, initializer: function() { this.get(HOST).on('nodeChange', Y.bind(this._onNodeChange, this)); } }, { /** * The non element placeholder, used for positioning the cursor and filling empty items * @property NON * @static */ NON: '<span class="yui-non">&nbsp;</span>', /** * The selector query to get all non elements * @property NONSEL * @static */ NON_SEL: 'span.yui-non', /** * The items to removed from a list when a list item is moved, currently removes BR nodes * @property REMOVE * @static */ REMOVE: 'br', /** * editorLists * @property NAME * @static */ NAME: 'editorLists', /** * lists * @property NS * @static */ NS: 'lists', ATTRS: { host: { value: false } } }); Y.namespace('Plugin'); Y.Plugin.EditorLists = EditorLists; }, '@VERSION@', {"requires": ["editor-base"]});
/* * file.js: Transport for outputting to a local log file * * (C) 2010 Charlie Robbins * MIT LICENCE * */ var events = require('events'), fs = require('fs'), path = require('path'), util = require('util'), async = require('async'), colors = require('colors'), common = require('../common'), Transport = require('./transport').Transport, isWritable = require('isstream').isWritable, Stream = require('stream').Stream; // // ### function File (options) // #### @options {Object} Options for this instance. // Constructor function for the File transport object responsible // for persisting log messages and metadata to one or more files. // var File = exports.File = function (options) { Transport.call(this, options); // // Helper function which throws an `Error` in the event // that any of the rest of the arguments is present in `options`. // function throwIf (target /*, illegal... */) { Array.prototype.slice.call(arguments, 1).forEach(function (name) { if (options[name]) { throw new Error('Cannot set ' + name + ' and ' + target + 'together'); } }); } if (options.filename || options.dirname) { throwIf('filename or dirname', 'stream'); this._basename = this.filename = options.filename ? path.basename(options.filename) : 'winston.log'; this.dirname = options.dirname || path.dirname(options.filename); this.options = options.options || { flags: 'a' }; // // "24 bytes" is maybe a good value for logging lines. // this.options.highWaterMark = this.options.highWaterMark || 24; } else if (options.stream) { throwIf('stream', 'filename', 'maxsize'); this._stream = options.stream; this._isStreams2 = isWritable(this._stream); // // We need to listen for drain events when // write() returns false. This can make node // mad at times. // this._stream.setMaxListeners(Infinity); } else { throw new Error('Cannot log to file without filename or stream.'); } this.json = options.json !== false; this.logstash = options.logstash || false; this.colorize = options.colorize || false; this.maxsize = options.maxsize || null; this.rotationFormat = options.rotationFormat || false; this.maxFiles = options.maxFiles || null; this.prettyPrint = options.prettyPrint || false; this.label = options.label || null; this.timestamp = options.timestamp != null ? options.timestamp : true; this.eol = options.eol || '\n'; this.tailable = options.tailable || false; this.depth = options.depth || null; this.showLevel = options.showLevel === undefined ? true : options.showLevel; if (this.json) { this.stringify = options.stringify; } // // Internal state variables representing the number // of files this instance has created and the current // size (in bytes) of the current logfile. // this._size = 0; this._created = 0; this._buffer = []; this._draining = false; this._opening = false; }; // // Inherit from `winston.Transport`. // util.inherits(File, Transport); // // Expose the name of this Transport on the prototype // File.prototype.name = 'file'; // // ### function log (level, msg, [meta], callback) // #### @level {string} Level at which to log the message. // #### @msg {string} Message to log // #### @meta {Object} **Optional** Additional metadata to attach // #### @callback {function} Continuation to respond to when complete. // Core logging method exposed to Winston. Metadata is optional. // File.prototype.log = function (level, msg, meta, callback) { if (this.silent) { return callback(null, true); } var self = this; if (typeof msg !== 'string') { msg = '' + msg; } var output = common.log({ level: level, message: msg, meta: meta, json: this.json, logstash: this.logstash, colorize: this.colorize, prettyPrint: this.prettyPrint, timestamp: this.timestamp, stringify: this.stringify, label: this.label, depth: this.depth, formatter: this.formatter, humanReadableUnhandledException: this.humanReadableUnhandledException }) + this.eol; if (!this.filename) { // // If there is no `filename` on this instance then it was configured // with a raw `WriteableStream` instance and we should not perform any // size restrictions. // this._write(output, callback); this._size += output.length; this._lazyDrain(); } else { this.open(function (err) { if (err) { // // If there was an error enqueue the message // return self._buffer.push([output, callback]); } self._write(output, callback); self._size += output.length; self._lazyDrain(); }); } }; // // ### function _write (data, cb) // #### @data {String|Buffer} Data to write to the instance's stream. // #### @cb {function} Continuation to respond to when complete. // Write to the stream, ensure execution of a callback on completion. // File.prototype._write = function(data, callback) { if (this._isStreams2) { this._stream.write(data); return callback && process.nextTick(function () { callback(null, true); }); } // If this is a file write stream, we could use the builtin // callback functionality, however, the stream is not guaranteed // to be an fs.WriteStream. var ret = this._stream.write(data); if (!callback) return; if (ret === false) { return this._stream.once('drain', function() { callback(null, true); }); } process.nextTick(function () { callback(null, true); }); }; // // ### function query (options, callback) // #### @options {Object} Loggly-like query options for this instance. // #### @callback {function} Continuation to respond to when complete. // Query the transport. Options object is optional. // File.prototype.query = function (options, callback) { if (typeof options === 'function') { callback = options; options = {}; } var file = path.join(this.dirname, this.filename), options = this.normalizeQuery(options), buff = '', results = [], row = 0; var stream = fs.createReadStream(file, { encoding: 'utf8' }); stream.on('error', function (err) { if (stream.readable) { stream.destroy(); } if (!callback) return; return err.code !== 'ENOENT' ? callback(err) : callback(null, results); }); stream.on('data', function (data) { var data = (buff + data).split(/\n+/), l = data.length - 1, i = 0; for (; i < l; i++) { if (!options.start || row >= options.start) { add(data[i]); } row++; } buff = data[l]; }); stream.on('close', function () { if (buff) add(buff, true); if (options.order === 'desc') { results = results.reverse(); } if (callback) callback(null, results); }); function add(buff, attempt) { try { var log = JSON.parse(buff); if (check(log)) push(log); } catch (e) { if (!attempt) { stream.emit('error', e); } } } function push(log) { if (options.rows && results.length >= options.rows) { if (stream.readable) { stream.destroy(); } return; } if (options.fields) { var obj = {}; options.fields.forEach(function (key) { obj[key] = log[key]; }); log = obj; } results.push(log); } function check(log) { if (!log) return; if (typeof log !== 'object') return; var time = new Date(log.timestamp); if ((options.from && time < options.from) || (options.until && time > options.until)) { return; } return true; } }; // // ### function stream (options) // #### @options {Object} Stream options for this instance. // Returns a log stream for this transport. Options object is optional. // File.prototype.stream = function (options) { var file = path.join(this.dirname, this.filename), options = options || {}, stream = new Stream; var tail = { file: file, start: options.start }; stream.destroy = common.tailFile(tail, function (err, line) { if(err){ return stream.emit('error',err); } try { stream.emit('data', line); line = JSON.parse(line); stream.emit('log', line); } catch (e) { stream.emit('error', e); } }); return stream; }; // // ### function open (callback) // #### @callback {function} Continuation to respond to when complete // Checks to see if a new file needs to be created based on the `maxsize` // (if any) and the current size of the file used. // File.prototype.open = function (callback) { if (this.opening) { // // If we are already attempting to open the next // available file then respond with a value indicating // that the message should be buffered. // return callback(true); } else if (!this._stream || (this.maxsize && this._size >= this.maxsize)) { // // If we dont have a stream or have exceeded our size, then create // the next stream and respond with a value indicating that // the message should be buffered. // callback(true); return this._createStream(); } // // Otherwise we have a valid (and ready) stream. // callback(); }; // // ### function close () // Closes the stream associated with this instance. // File.prototype.close = function () { var self = this; if (this._stream) { this._stream.end(); this._stream.destroySoon(); this._stream.once('drain', function () { self.emit('flush'); self.emit('closed'); }); } }; // // ### function flush () // Flushes any buffered messages to the current `stream` // used by this instance. // File.prototype.flush = function () { var self = this; // If nothing to flush, there will be no "flush" event from native stream // Thus, the "open" event will never be fired (see _createStream.createAndFlush function) // That means, self.opening will never set to false and no logs will be written to disk if (!this._buffer.length) { return self.emit('flush'); } // // Iterate over the `_buffer` of enqueued messaged // and then write them to the newly created stream. // this._buffer.forEach(function (item) { var str = item[0], callback = item[1]; process.nextTick(function () { self._write(str, callback); self._size += str.length; }); }); // // Quickly truncate the `_buffer` once the write operations // have been started // self._buffer.length = 0; // // When the stream has drained we have flushed // our buffer. // self._stream.once('drain', function () { self.emit('flush'); self.emit('logged'); }); }; // // ### @private function _createStream () // Attempts to open the next appropriate file for this instance // based on the common state (such as `maxsize` and `_basename`). // File.prototype._createStream = function () { var self = this; this.opening = true; (function checkFile (target) { var fullname = path.join(self.dirname, target); // // Creates the `WriteStream` and then flushes any // buffered messages. // function createAndFlush (size) { if (self._stream) { self._stream.end(); self._stream.destroySoon(); } self._size = size; self.filename = target; self._stream = fs.createWriteStream(fullname, self.options); self._isStreams2 = isWritable(self._stream); // // We need to listen for drain events when // write() returns false. This can make node // mad at times. // self._stream.setMaxListeners(Infinity); // // When the current stream has finished flushing // then we can be sure we have finished opening // and thus can emit the `open` event. // self.once('flush', function () { // Because "flush" event is based on native stream "drain" event, // logs could be written inbetween "self.flush()" and here // Therefore, we need to flush again to make sure everything is flushed self.flush(); self.opening = false; self.emit('open', fullname); }); // // Remark: It is possible that in the time it has taken to find the // next logfile to be written more data than `maxsize` has been buffered, // but for sensible limits (10s - 100s of MB) this seems unlikely in less // than one second. // self.flush(); } fs.stat(fullname, function (err, stats) { if (err) { if (err.code !== 'ENOENT') { return self.emit('error', err); } return createAndFlush(0); } if (!stats || (self.maxsize && stats.size >= self.maxsize)) { // // If `stats.size` is greater than the `maxsize` for // this instance then try again // return self._incFile(function() { checkFile(self._getFile()); }); } createAndFlush(stats.size); }); })(this._getFile()); }; File.prototype._incFile = function (callback) { var ext = path.extname(this._basename), basename = path.basename(this._basename, ext), oldest, target; if (!this.tailable) { this._created += 1; this._checkMaxFilesIncrementing(ext, basename, callback); } else { this._checkMaxFilesTailable(ext, basename, callback); } }; // // ### @private function _getFile () // Gets the next filename to use for this instance // in the case that log filesizes are being capped. // File.prototype._getFile = function () { var ext = path.extname(this._basename), basename = path.basename(this._basename, ext); // // Caveat emptor (indexzero): rotationFormat() was broken by design // when combined with max files because the set of files to unlink // is never stored. // return !this.tailable && this._created ? basename + (this.rotationFormat ? this.rotationFormat() : this._created) + ext : basename + ext; }; // // ### @private function _checkMaxFilesIncrementing () // Increment the number of files created or // checked by this instance. // File.prototype._checkMaxFilesIncrementing = function (ext, basename, callback) { var oldest, target; // Check for maxFiles option and delete file if (!this.maxFiles || this._created < this.maxFiles) { return callback(); } oldest = this._created - this.maxFiles; target = path.join(this.dirname, basename + (oldest === 0 ? oldest : '') + ext); fs.unlink(target, callback); }; // // ### @private function _checkMaxFilesTailable () // // Roll files forward based on integer, up to maxFiles. // e.g. if base if file.log and it becomes oversized, roll // to file1.log, and allow file.log to be re-used. If // file is oversized again, roll file1.log to file2.log, // roll file.log to file1.log, and so on. File.prototype._checkMaxFilesTailable = function (ext, basename, callback) { var tasks = [], self = this; if (!this.maxFiles) return; for (var x = this.maxFiles - 1; x > 0; x--) { tasks.push(function (i) { return function (cb) { var tmppath = path.join(self.dirname, basename + (i - 1) + ext); fs.exists(tmppath, function (exists) { if (!exists) { return cb(null); } fs.rename(tmppath, path.join(self.dirname, basename + i + ext), cb); }); }; }(x)); } async.series(tasks, function (err) { fs.rename( path.join(self.dirname, basename + ext), path.join(self.dirname, basename + 1 + ext), callback ); }); }; // // ### @private function _lazyDrain () // Lazily attempts to emit the `logged` event when `this.stream` has // drained. This is really just a simple mutex that only works because // Node.js is single-threaded. // File.prototype._lazyDrain = function () { var self = this; if (!this._draining && this._stream) { this._draining = true; this._stream.once('drain', function () { this._draining = false; self.emit('logged'); }); } };
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule PerformanceOverlay * @flow */ 'use strict'; var PerformanceLogger = require('PerformanceLogger'); var React = require('React'); var StyleSheet = require('StyleSheet'); var Text = require('Text'); var View = require('View'); var PerformanceOverlay = React.createClass({ render: function() { var perfLogs = PerformanceLogger.getTimespans(); var items = []; for (var key in perfLogs) { if (perfLogs[key].totalTime) { var unit = (key === 'BundleSize') ? 'b' : 'ms'; items.push( <View style={styles.row} key={key}> <Text style={[styles.text, styles.label]}>{key}</Text> <Text style={[styles.text, styles.totalTime]}> {perfLogs[key].totalTime + unit} </Text> </View> ); } } return ( <View style={styles.container}> {items} </View> ); } }); var styles = StyleSheet.create({ container: { height: 100, paddingTop: 10, }, label: { flex: 1, }, row: { flexDirection: 'row', paddingHorizontal: 10, }, text: { color: 'white', fontSize: 12, }, totalTime: { paddingRight: 100, }, }); module.exports = PerformanceOverlay;
var crypto = require('crypto'); var EventEmitter = require('events').EventEmitter; var util = require('util'); var pgPass = require('pgpass'); var TypeOverrides = require('./type-overrides'); var ConnectionParameters = require('./connection-parameters'); var Query = require('./query'); var defaults = require('./defaults'); var Connection = require('./connection'); var Client = function(config) { EventEmitter.call(this); this.connectionParameters = new ConnectionParameters(config); this.user = this.connectionParameters.user; this.database = this.connectionParameters.database; this.port = this.connectionParameters.port; this.host = this.connectionParameters.host; this.password = this.connectionParameters.password; var c = config || {}; this._types = new TypeOverrides(c.types); this.connection = c.connection || new Connection({ stream: c.stream, ssl: this.connectionParameters.ssl }); this.queryQueue = []; this.binary = c.binary || defaults.binary; this.encoding = 'utf8'; this.processID = null; this.secretKey = null; this.ssl = this.connectionParameters.ssl || false; }; util.inherits(Client, EventEmitter); Client.prototype.connect = function(callback) { var self = this; var con = this.connection; if(this.host && this.host.indexOf('/') === 0) { con.connect(this.host + '/.s.PGSQL.' + this.port); } else { con.connect(this.port, this.host); } //once connection is established send startup message con.on('connect', function() { if(self.ssl) { con.requestSsl(); } else { con.startup(self.getStartupConf()); } }); con.on('sslconnect', function() { con.startup(self.getStartupConf()); }); function checkPgPass(cb) { return function(msg) { if (null !== self.password) { cb(msg); } else { pgPass(self.connectionParameters, function(pass){ if (undefined !== pass) { self.connectionParameters.password = self.password = pass; } cb(msg); }); } }; } //password request handling con.on('authenticationCleartextPassword', checkPgPass(function() { con.password(self.password); })); //password request handling con.on('authenticationMD5Password', checkPgPass(function(msg) { var inner = Client.md5(self.password + self.user); var outer = Client.md5(Buffer.concat([new Buffer(inner), msg.salt])); var md5password = "md5" + outer; con.password(md5password); })); con.once('backendKeyData', function(msg) { self.processID = msg.processID; self.secretKey = msg.secretKey; }); //hook up query handling events to connection //after the connection initially becomes ready for queries con.once('readyForQuery', function() { //delegate rowDescription to active query con.on('rowDescription', function(msg) { self.activeQuery.handleRowDescription(msg); }); //delegate dataRow to active query con.on('dataRow', function(msg) { self.activeQuery.handleDataRow(msg); }); //delegate portalSuspended to active query con.on('portalSuspended', function(msg) { self.activeQuery.handlePortalSuspended(con); }); //deletagate emptyQuery to active query con.on('emptyQuery', function(msg) { self.activeQuery.handleEmptyQuery(con); }); //delegate commandComplete to active query con.on('commandComplete', function(msg) { self.activeQuery.handleCommandComplete(msg, con); }); //if a prepared statement has a name and properly parses //we track that its already been executed so we don't parse //it again on the same client con.on('parseComplete', function(msg) { if(self.activeQuery.name) { con.parsedStatements[self.activeQuery.name] = true; } }); con.on('copyInResponse', function(msg) { self.activeQuery.handleCopyInResponse(self.connection); }); con.on('copyData', function (msg) { self.activeQuery.handleCopyData(msg, self.connection); }); con.on('notification', function(msg) { self.emit('notification', msg); }); //process possible callback argument to Client#connect if (callback) { callback(null, self); //remove callback for proper error handling //after the connect event callback = null; } self.emit('connect'); }); con.on('readyForQuery', function() { var activeQuery = self.activeQuery; self.activeQuery = null; self.readyForQuery = true; self._pulseQueryQueue(); if(activeQuery) { activeQuery.handleReadyForQuery(); } }); con.on('error', function(error) { if(self.activeQuery) { var activeQuery = self.activeQuery; self.activeQuery = null; return activeQuery.handleError(error, con); } if(!callback) { return self.emit('error', error); } callback(error); callback = null; }); con.once('end', function() { if ( callback ) { // haven't received a connection message yet ! var err = new Error('Connection terminated'); callback(err); callback = null; return; } if(self.activeQuery) { var disconnectError = new Error('Connection terminated'); self.activeQuery.handleError(disconnectError, con); self.activeQuery = null; } self.emit('end'); }); con.on('notice', function(msg) { self.emit('notice', msg); }); }; Client.prototype.getStartupConf = function() { var params = this.connectionParameters; var data = { user: params.user, database: params.database }; var appName = params.application_name || params.fallback_application_name; if (appName) { data.application_name = appName; } return data; }; Client.prototype.cancel = function(client, query) { if(client.activeQuery == query) { var con = this.connection; if(this.host && this.host.indexOf('/') === 0) { con.connect(this.host + '/.s.PGSQL.' + this.port); } else { con.connect(this.port, this.host); } //once connection is established send cancel message con.on('connect', function() { con.cancel(client.processID, client.secretKey); }); } else if(client.queryQueue.indexOf(query) != -1) { client.queryQueue.splice(client.queryQueue.indexOf(query), 1); } }; Client.prototype.setTypeParser = function(oid, format, parseFn) { return this._types.setTypeParser(oid, format, parseFn); }; Client.prototype.getTypeParser = function(oid, format) { return this._types.getTypeParser(oid, format); }; // Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c Client.prototype.escapeIdentifier = function(str) { var escaped = '"'; for(var i = 0; i < str.length; i++) { var c = str[i]; if(c === '"') { escaped += c + c; } else { escaped += c; } } escaped += '"'; return escaped; }; // Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c Client.prototype.escapeLiteral = function(str) { var hasBackslash = false; var escaped = '\''; for(var i = 0; i < str.length; i++) { var c = str[i]; if(c === '\'') { escaped += c + c; } else if (c === '\\') { escaped += c + c; hasBackslash = true; } else { escaped += c; } } escaped += '\''; if(hasBackslash === true) { escaped = ' E' + escaped; } return escaped; }; Client.prototype._pulseQueryQueue = function() { if(this.readyForQuery===true) { this.activeQuery = this.queryQueue.shift(); if(this.activeQuery) { this.readyForQuery = false; this.hasExecuted = true; this.activeQuery.submit(this.connection); } else if(this.hasExecuted) { this.activeQuery = null; this.emit('drain'); } } }; Client.prototype.copyFrom = function (text) { throw new Error("For PostgreSQL COPY TO/COPY FROM support npm install pg-copy-streams"); }; Client.prototype.copyTo = function (text) { throw new Error("For PostgreSQL COPY TO/COPY FROM support npm install pg-copy-streams"); }; Client.prototype.query = function(config, values, callback) { //can take in strings, config object or query object var query = (typeof config.submit == 'function') ? config : new Query(config, values, callback); if(this.binary && !query.binary) { query.binary = true; } if(query._result) { query._result._getTypeParser = this._types.getTypeParser.bind(this._types); } this.queryQueue.push(query); this._pulseQueryQueue(); return query; }; Client.prototype.end = function() { this.connection.end(); }; Client.md5 = function(string) { return crypto.createHash('md5').update(string).digest('hex'); }; // expose a Query constructor Client.Query = Query; module.exports = Client;
(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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ /** * MUI CSS/JS main module * @module main */ (function(win) { 'use strict'; // return if library has been loaded already if (win._muiLoadedJS) return; else win._muiLoadedJS = true; // load dependencies var jqLite = require('src/js/lib/jqLite'), dropdown = require('src/js/dropdown'), overlay = require('src/js/overlay'), ripple = require('src/js/ripple'), select = require('src/js/select'), tabs = require('src/js/tabs'), textfield = require('src/js/textfield'); // expose api win.mui = { overlay: overlay, tabs: tabs.api }; // init libraries jqLite.ready(function() { textfield.initListeners(); select.initListeners(); ripple.initListeners(); dropdown.initListeners(); tabs.initListeners(); }); })(window); },{"src/js/dropdown":6,"src/js/lib/jqLite":7,"src/js/overlay":8,"src/js/ripple":9,"src/js/select":10,"src/js/tabs":11,"src/js/textfield":12}],2:[function(require,module,exports){ /** * MUI config module * @module config */ /** Define module API */ module.exports = { /** Use debug mode */ debug: true }; },{}],3:[function(require,module,exports){ /** * MUI CSS/JS form helpers module * @module lib/forms.py */ 'use strict'; var wrapperPadding = 15, // from CSS inputHeight = 32, // from CSS rowHeight = 42, // from CSS menuPadding = 8; // from CSS /** * Menu position/size/scroll helper * @returns {Object} Object with keys 'height', 'top', 'scrollTop' */ function getMenuPositionalCSSFn(wrapperEl, numRows, selectedRow) { var viewHeight = document.documentElement.clientHeight; // determine 'height' var h = numRows * rowHeight + 2 * menuPadding, height = Math.min(h, viewHeight); // determine 'top' var top, initTop, minTop, maxTop; initTop = (menuPadding + rowHeight) - (wrapperPadding + inputHeight); initTop -= selectedRow * rowHeight; minTop = -1 * wrapperEl.getBoundingClientRect().top; maxTop = (viewHeight - height) + minTop; top = Math.min(Math.max(initTop, minTop), maxTop); // determine 'scrollTop' var scrollTop = 0, scrollIdeal, scrollMax; if (h > viewHeight) { scrollIdeal = (menuPadding + (selectedRow + 1) * rowHeight) - (-1 * top + wrapperPadding + inputHeight); scrollMax = numRows * rowHeight + 2 * menuPadding - height; scrollTop = Math.min(scrollIdeal, scrollMax); } return { 'height': height + 'px', 'top': top + 'px', 'scrollTop': scrollTop }; } /** Define module API */ module.exports = { getMenuPositionalCSS: getMenuPositionalCSSFn }; },{}],4:[function(require,module,exports){ /** * MUI CSS/JS jqLite module * @module lib/jqLite */ 'use strict'; /** * Add a class to an element. * @param {Element} element - The DOM element. * @param {string} cssClasses - Space separated list of class names. */ function jqLiteAddClass(element, cssClasses) { if (!cssClasses || !element.setAttribute) return; var existingClasses = _getExistingClasses(element), splitClasses = cssClasses.split(' '), cssClass; for (var i=0; i < splitClasses.length; i++) { cssClass = splitClasses[i].trim(); if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) { existingClasses += cssClass + ' '; } } element.setAttribute('class', existingClasses.trim()); } /** * Get or set CSS properties. * @param {Element} element - The DOM element. * @param {string} [name] - The property name. * @param {string} [value] - The property value. */ function jqLiteCss(element, name, value) { // Return full style object if (name === undefined) { return getComputedStyle(element); } var nameType = jqLiteType(name); // Set multiple values if (nameType === 'object') { for (var key in name) element.style[_camelCase(key)] = name[key]; return; } // Set a single value if (nameType === 'string' && value !== undefined) { element.style[_camelCase(name)] = value; } var styleObj = getComputedStyle(element), isArray = (jqLiteType(name) === 'array'); // Read single value if (!isArray) return _getCurrCssProp(element, name, styleObj); // Read multiple values var outObj = {}, key; for (var i=0; i < name.length; i++) { key = name[i]; outObj[key] = _getCurrCssProp(element, key, styleObj); } return outObj; } /** * Check if element has class. * @param {Element} element - The DOM element. * @param {string} cls - The class name string. */ function jqLiteHasClass(element, cls) { if (!cls || !element.getAttribute) return false; return (_getExistingClasses(element).indexOf(' ' + cls + ' ') > -1); } /** * Return the type of a variable. * @param {} somevar - The JavaScript variable. */ function jqLiteType(somevar) { // handle undefined if (somevar === undefined) return 'undefined'; // handle others (of type [object <Type>]) var typeStr = Object.prototype.toString.call(somevar); if (typeStr.indexOf('[object ') === 0) { return typeStr.slice(8, -1).toLowerCase(); } else { throw new Error("MUI: Could not understand type: " + typeStr); } } /** * Attach an event handler to a DOM element * @param {Element} element - The DOM element. * @param {string} events - Space separated event names. * @param {Function} callback - The callback function. * @param {Boolean} useCapture - Use capture flag. */ function jqLiteOn(element, events, callback, useCapture) { useCapture = (useCapture === undefined) ? false : useCapture; var cache = element._muiEventCache = element._muiEventCache || {}; events.split(' ').map(function(event) { // add to DOM element.addEventListener(event, callback, useCapture); // add to cache cache[event] = cache[event] || []; cache[event].push([callback, useCapture]); }); } /** * Remove an event handler from a DOM element * @param {Element} element - The DOM element. * @param {string} events - Space separated event names. * @param {Function} callback - The callback function. * @param {Boolean} useCapture - Use capture flag. */ function jqLiteOff(element, events, callback, useCapture) { useCapture = (useCapture === undefined) ? false : useCapture; // remove from cache var cache = element._muiEventCache = element._muiEventCache || {}, argsList, args, i; events.split(' ').map(function(event) { argsList = cache[event] || []; i = argsList.length; while (i--) { args = argsList[i]; // remove all events if callback is undefined if (callback === undefined || (args[0] === callback && args[1] === useCapture)) { // remove from cache argsList.splice(i, 1); // remove from DOM element.removeEventListener(event, args[0], args[1]); } } }); } /** * Attach an event hander which will only execute once per element per event * @param {Element} element - The DOM element. * @param {string} events - Space separated event names. * @param {Function} callback - The callback function. * @param {Boolean} useCapture - Use capture flag. */ function jqLiteOne(element, events, callback, useCapture) { events.split(' ').map(function(event) { jqLiteOn(element, event, function onFn(ev) { // execute callback if (callback) callback.apply(this, arguments); // remove wrapper jqLiteOff(element, event, onFn); }, useCapture); }); } /** * Get or set horizontal scroll position * @param {Element} element - The DOM element * @param {number} [value] - The scroll position */ function jqLiteScrollLeft(element, value) { var win = window; // get if (value === undefined) { if (element === win) { var docEl = document.documentElement; return (win.pageXOffset || docEl.scrollLeft) - (docEl.clientLeft || 0); } else { return element.scrollLeft; } } // set if (element === win) win.scrollTo(value, jqLiteScrollTop(win)); else element.scrollLeft = value; } /** * Get or set vertical scroll position * @param {Element} element - The DOM element * @param {number} value - The scroll position */ function jqLiteScrollTop(element, value) { var win = window; // get if (value === undefined) { if (element === win) { var docEl = document.documentElement; return (win.pageYOffset || docEl.scrollTop) - (docEl.clientTop || 0); } else { return element.scrollTop; } } // set if (element === win) win.scrollTo(jqLiteScrollLeft(win), value); else element.scrollTop = value; } /** * Return object representing top/left offset and element height/width. * @param {Element} element - The DOM element. */ function jqLiteOffset(element) { var win = window, rect = element.getBoundingClientRect(), scrollTop = jqLiteScrollTop(win), scrollLeft = jqLiteScrollLeft(win); return { top: rect.top + scrollTop, left: rect.left + scrollLeft, height: rect.height, width: rect.width }; } /** * Attach a callback to the DOM ready event listener * @param {Function} fn - The callback function. */ function jqLiteReady(fn) { var done = false, top = true, doc = document, win = doc.defaultView, root = doc.documentElement, add = doc.addEventListener ? 'addEventListener' : 'attachEvent', rem = doc.addEventListener ? 'removeEventListener' : 'detachEvent', pre = doc.addEventListener ? '' : 'on'; var init = function(e) { if (e.type == 'readystatechange' && doc.readyState != 'complete') { return; } (e.type == 'load' ? win : doc)[rem](pre + e.type, init, false); if (!done && (done = true)) fn.call(win, e.type || e); }; var poll = function() { try { root.doScroll('left'); } catch(e) { setTimeout(poll, 50); return; } init('poll'); }; if (doc.readyState == 'complete') { fn.call(win, 'lazy'); } else { if (doc.createEventObject && root.doScroll) { try { top = !win.frameElement; } catch(e) { } if (top) poll(); } doc[add](pre + 'DOMContentLoaded', init, false); doc[add](pre + 'readystatechange', init, false); win[add](pre + 'load', init, false); } } /** * Remove classes from a DOM element * @param {Element} element - The DOM element. * @param {string} cssClasses - Space separated list of class names. */ function jqLiteRemoveClass(element, cssClasses) { if (!cssClasses || !element.setAttribute) return; var existingClasses = _getExistingClasses(element), splitClasses = cssClasses.split(' '), cssClass; for (var i=0; i < splitClasses.length; i++) { cssClass = splitClasses[i].trim(); while (existingClasses.indexOf(' ' + cssClass + ' ') >= 0) { existingClasses = existingClasses.replace(' ' + cssClass + ' ', ' '); } } element.setAttribute('class', existingClasses.trim()); } // ------------------------------ // Utilities // ------------------------------ var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g, MOZ_HACK_REGEXP = /^moz([A-Z])/, ESCAPE_REGEXP = /([.*+?^=!:${}()|\[\]\/\\])/g; function _getExistingClasses(element) { var classes = (element.getAttribute('class') || '').replace(/[\n\t]/g, ''); return ' ' + classes + ' '; } function _camelCase(name) { return name. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) { return offset ? letter.toUpperCase() : letter; }). replace(MOZ_HACK_REGEXP, 'Moz$1'); } function _escapeRegExp(string) { return string.replace(ESCAPE_REGEXP, "\\$1"); } function _getCurrCssProp(elem, name, computed) { var ret; // try computed style ret = computed.getPropertyValue(name); // try style attribute (if element is not attached to document) if (ret === '' && !elem.ownerDocument) ret = elem.style[_camelCase(name)]; return ret; } /** * Module API */ module.exports = { /** Add classes */ addClass: jqLiteAddClass, /** Get or set CSS properties */ css: jqLiteCss, /** Check for class */ hasClass: jqLiteHasClass, /** Remove event handlers */ off: jqLiteOff, /** Return offset values */ offset: jqLiteOffset, /** Add event handlers */ on: jqLiteOn, /** Add an execute-once event handler */ one: jqLiteOne, /** DOM ready event handler */ ready: jqLiteReady, /** Remove classes */ removeClass: jqLiteRemoveClass, /** Check JavaScript variable instance type */ type: jqLiteType, /** Get or set horizontal scroll position */ scrollLeft: jqLiteScrollLeft, /** Get or set vertical scroll position */ scrollTop: jqLiteScrollTop }; },{}],5:[function(require,module,exports){ /** * MUI CSS/JS utilities module * @module lib/util */ 'use strict'; var config = require('../config'), jqLite = require('./jqLite'), nodeInsertedCallbacks = [], scrollLock = 0, scrollLockCls = 'mui-body--scroll-lock', scrollLockPos, _supportsPointerEvents; /** * Logging function */ function logFn() { var win = window; if (config.debug && typeof win.console !== "undefined") { try { win.console.log.apply(win.console, arguments); } catch (a) { var e = Array.prototype.slice.call(arguments); win.console.log(e.join("\n")); } } } /** * Load CSS text in new stylesheet * @param {string} cssText - The css text. */ function loadStyleFn(cssText) { var doc = document, head; // copied from jQuery head = doc.head || doc.getElementsByTagName('head')[0] || doc.documentElement; var e = doc.createElement('style'); e.type = 'text/css'; if (e.styleSheet) e.styleSheet.cssText = cssText; else e.appendChild(doc.createTextNode(cssText)); // add to document head.insertBefore(e, head.firstChild); return e; } /** * Raise an error * @param {string} msg - The error message. */ function raiseErrorFn(msg, useConsole) { if (useConsole) { if (typeof console !== 'undefined') console.error('MUI Warning: ' + msg); } else { throw new Error('MUI: ' + msg); } } /** * Register callbacks on muiNodeInserted event * @param {function} callbackFn - The callback function. */ function onNodeInsertedFn(callbackFn) { nodeInsertedCallbacks.push(callbackFn); // initalize listeners if (nodeInsertedCallbacks._initialized === undefined) { var doc = document, events = 'animationstart mozAnimationStart webkitAnimationStart'; jqLite.on(doc, events, animationHandlerFn); nodeInsertedCallbacks._initialized = true; } } /** * Execute muiNodeInserted callbacks * @param {Event} ev - The DOM event. */ function animationHandlerFn(ev) { // check animation name if (ev.animationName !== 'mui-node-inserted') return; var el = ev.target; // iterate through callbacks for (var i=nodeInsertedCallbacks.length - 1; i >= 0; i--) { nodeInsertedCallbacks[i](el); } } /** * Convert Classname object, with class as key and true/false as value, to an * class string. * @param {Object} classes The classes * @return {String} class string */ function classNamesFn(classes) { var cs = ''; for (var i in classes) { cs += (classes[i]) ? i + ' ' : ''; } return cs.trim(); } /** * Check if client supports pointer events. */ function supportsPointerEventsFn() { // check cache if (_supportsPointerEvents !== undefined) return _supportsPointerEvents; var element = document.createElement('x'); element.style.cssText = 'pointer-events:auto'; _supportsPointerEvents = (element.style.pointerEvents === 'auto'); return _supportsPointerEvents; } /** * Create callback closure. * @param {Object} instance - The object instance. * @param {String} funcName - The name of the callback function. */ function callbackFn(instance, funcName) { return function() {instance[funcName].apply(instance, arguments);}; } /** * Dispatch event. * @param {Element} element - The DOM element. * @param {String} eventType - The event type. * @param {Boolean} bubbles=true - If true, event bubbles. * @param {Boolean} cancelable=true = If true, event is cancelable * @param {Object} [data] - Data to add to event object */ function dispatchEventFn(element, eventType, bubbles, cancelable, data) { var ev = document.createEvent('HTMLEvents'), bubbles = (bubbles !== undefined) ? bubbles : true, cancelable = (cancelable !== undefined) ? cancelable : true, k; ev.initEvent(eventType, bubbles, cancelable); // add data to event object if (data) for (k in data) ev[k] = data[k]; // dispatch if (element) element.dispatchEvent(ev); return ev; } /** * Turn on window scroll lock. */ function enableScrollLockFn() { // increment counter scrollLock += 1 // add lock if (scrollLock === 1) { var win = window, doc = document; scrollLockPos = {left: jqLite.scrollLeft(win), top: jqLite.scrollTop(win)}; jqLite.addClass(doc.body, scrollLockCls); win.scrollTo(scrollLockPos.left, scrollLockPos.top); } } /** * Turn off window scroll lock. * @param {Boolean} resetPos - Reset scroll position to original value. */ function disableScrollLockFn(resetPos) { // ignore if (scrollLock === 0) return; // decrement counter scrollLock -= 1 // remove lock if (scrollLock === 0) { var win = window, doc = document; jqLite.removeClass(doc.body, scrollLockCls); if (resetPos) win.scrollTo(scrollLockPos.left, scrollLockPos.top); } } /** * requestAnimationFrame polyfilled * @param {Function} callback - The callback function */ function requestAnimationFrameFn(callback) { var fn = window.requestAnimationFrame; if (fn) fn(callback); else setTimeout(callback, 0); } /** * Define the module API */ module.exports = { /** Create callback closures */ callback: callbackFn, /** Classnames object to string */ classNames: classNamesFn, /** Disable scroll lock */ disableScrollLock: disableScrollLockFn, /** Dispatch event */ dispatchEvent: dispatchEventFn, /** Enable scroll lock */ enableScrollLock: enableScrollLockFn, /** Log messages to the console when debug is turned on */ log: logFn, /** Load CSS text as new stylesheet */ loadStyle: loadStyleFn, /** Register muiNodeInserted handler */ onNodeInserted: onNodeInsertedFn, /** Raise MUI error */ raiseError: raiseErrorFn, /** Request animation frame */ requestAnimationFrame: requestAnimationFrameFn, /** Support Pointer Events check */ supportsPointerEvents: supportsPointerEventsFn }; },{"../config":2,"./jqLite":4}],6:[function(require,module,exports){ /** * MUI CSS/JS dropdown module * @module dropdowns */ 'use strict'; var jqLite = require('./lib/jqLite'), util = require('./lib/util'), attrKey = 'data-mui-toggle', attrSelector = '[data-mui-toggle="dropdown"]', openClass = 'mui--is-open', menuClass = 'mui-dropdown__menu'; /** * Initialize toggle element. * @param {Element} toggleEl - The toggle element. */ function initialize(toggleEl) { // check flag if (toggleEl._muiDropdown === true) return; else toggleEl._muiDropdown = true; // use type "button" to prevent form submission by default if (!toggleEl.hasAttribute('type')) toggleEl.type = 'button'; // attach click handler jqLite.on(toggleEl, 'click', clickHandler); } /** * Handle click events on dropdown toggle element. * @param {Event} ev - The DOM event */ function clickHandler(ev) { // only left clicks if (ev.button !== 0) return; var toggleEl = this; // exit if toggle button is disabled if (toggleEl.getAttribute('disabled') !== null) return; // toggle dropdown toggleDropdown(toggleEl); } /** * Toggle the dropdown. * @param {Element} toggleEl - The dropdown toggle element. */ function toggleDropdown(toggleEl) { var wrapperEl = toggleEl.parentNode, menuEl = toggleEl.nextElementSibling, doc = wrapperEl.ownerDocument; // exit if no menu element if (!menuEl || !jqLite.hasClass(menuEl, menuClass)) { return util.raiseError('Dropdown menu element not found'); } // method to close dropdown function closeDropdownFn() { jqLite.removeClass(menuEl, openClass); // remove event handlers jqLite.off(doc, 'click', closeDropdownFn); } // method to open dropdown function openDropdownFn() { // position menu element below toggle button var wrapperRect = wrapperEl.getBoundingClientRect(), toggleRect = toggleEl.getBoundingClientRect(); var top = toggleRect.top - wrapperRect.top + toggleRect.height; jqLite.css(menuEl, 'top', top + 'px'); // add open class to wrapper jqLite.addClass(menuEl, openClass); // close dropdown when user clicks outside of menu setTimeout(function() {jqLite.on(doc, 'click', closeDropdownFn);}, 0); } // toggle dropdown if (jqLite.hasClass(menuEl, openClass)) closeDropdownFn(); else openDropdownFn(); } /** Define module API */ module.exports = { /** Initialize module listeners */ initListeners: function() { var doc = document; // markup elements available when method is called var elList = doc.querySelectorAll(attrSelector); for (var i=elList.length - 1; i >= 0; i--) initialize(elList[i]); // listen for new elements util.onNodeInserted(function(el) { if (el.getAttribute(attrKey) === 'dropdown') initialize(el); }); } }; },{"./lib/jqLite":4,"./lib/util":5}],7:[function(require,module,exports){ module.exports=require(4) },{}],8:[function(require,module,exports){ /** * MUI CSS/JS overlay module * @module overlay */ 'use strict'; var util = require('./lib/util'), jqLite = require('./lib/jqLite'), overlayId = 'mui-overlay', bodyClass = 'mui--overflow-hidden', iosRegex = /(iPad|iPhone|iPod)/g; /** * Turn overlay on/off. * @param {string} action - Turn overlay "on"/"off". * @param {object} [options] * @config {boolean} [keyboard] - If true, close when escape key is pressed. * @config {boolean} [static] - If false, close when backdrop is clicked. * @config {Function} [onclose] - Callback function to execute on close * @param {Element} [childElement] - Child element to add to overlay. */ function overlayFn(action) { var overlayEl; if (action === 'on') { // extract arguments var arg, options, childElement; // pull options and childElement from arguments for (var i=arguments.length - 1; i > 0; i--) { arg = arguments[i]; if (jqLite.type(arg) === 'object') options = arg; if (arg instanceof Element && arg.nodeType === 1) childElement = arg; } // option defaults options = options || {}; if (options.keyboard === undefined) options.keyboard = true; if (options.static === undefined) options.static = false; // execute method overlayEl = overlayOn(options, childElement); } else if (action === 'off') { overlayEl = overlayOff(); } else { // raise error util.raiseError("Expecting 'on' or 'off'"); } return overlayEl; } /** * Turn on overlay. * @param {object} options - Overlay options. * @param {Element} childElement - The child element. */ function overlayOn(options, childElement) { var bodyEl = document.body, overlayEl = document.getElementById(overlayId); // add overlay util.enableScrollLock(); //jqLite.addClass(bodyEl, bodyClass); if (!overlayEl) { // create overlayEl overlayEl = document.createElement('div'); overlayEl.setAttribute('id', overlayId); // add child element if (childElement) overlayEl.appendChild(childElement); bodyEl.appendChild(overlayEl); } else { // remove existing children while (overlayEl.firstChild) overlayEl.removeChild(overlayEl.firstChild); // add child element if (childElement) overlayEl.appendChild(childElement); } // iOS bugfix if (iosRegex.test(navigator.userAgent)) { jqLite.css(overlayEl, 'cursor', 'pointer'); } // handle options if (options.keyboard) addKeyupHandler(); else removeKeyupHandler(); if (options.static) removeClickHandler(overlayEl); else addClickHandler(overlayEl); // attach options overlayEl.muiOptions = options; return overlayEl; } /** * Turn off overlay. */ function overlayOff() { var overlayEl = document.getElementById(overlayId), callbackFn; if (overlayEl) { // remove children while (overlayEl.firstChild) overlayEl.removeChild(overlayEl.firstChild); // remove overlay element overlayEl.parentNode.removeChild(overlayEl); // callback reference callbackFn = overlayEl.muiOptions.onclose; // remove click handler removeClickHandler(overlayEl); } util.disableScrollLock(); // remove keyup handler removeKeyupHandler(); // execute callback if (callbackFn) callbackFn(); return overlayEl; } /** * Add keyup handler. */ function addKeyupHandler() { jqLite.on(document, 'keyup', onKeyup); } /** * Remove keyup handler. */ function removeKeyupHandler() { jqLite.off(document, 'keyup', onKeyup); } /** * Teardown overlay when escape key is pressed. */ function onKeyup(ev) { if (ev.keyCode === 27) overlayOff(); } /** * Add click handler. */ function addClickHandler(overlayEl) { jqLite.on(overlayEl, 'click', onClick); } /** * Remove click handler. */ function removeClickHandler(overlayEl) { jqLite.off(overlayEl, 'click', onClick); } /** * Teardown overlay when backdrop is clicked. */ function onClick(ev) { if (ev.target.id === overlayId) overlayOff(); } /** Define module API */ module.exports = overlayFn; },{"./lib/jqLite":4,"./lib/util":5}],9:[function(require,module,exports){ /** * MUI CSS/JS ripple module * @module ripple */ 'use strict'; var jqLite = require('./lib/jqLite'), util = require('./lib/util'), btnClass = 'mui-btn', btnFABClass = 'mui-btn--fab', rippleClass = 'mui-ripple-effect', supportsTouch = 'ontouchstart' in document.documentElement, mouseDownEvents = (supportsTouch) ? 'touchstart' : 'mousedown', mouseUpEvents = (supportsTouch) ? 'touchend' : 'mouseup mouseleave', animationDuration = 600; /** * Add ripple effects to button element. * @param {Element} buttonEl - The button element. */ function initialize(buttonEl) { // check flag if (buttonEl._muiRipple === true) return; else buttonEl._muiRipple = true; // exit if element is INPUT (doesn't support absolute positioned children) if (buttonEl.tagName === 'INPUT') return; // attach event handler jqLite.on(buttonEl, mouseDownEvents, mouseDownHandler); } /** * MouseDown Event handler. * @param {Event} ev - The DOM event */ function mouseDownHandler(ev) { // only left clicks if (ev.type === 'mousedown' && ev.button !== 0) return; var buttonEl = this; // exit if button is disabled if (buttonEl.disabled === true) return; // add mouseup event to button once if (!buttonEl.muiMouseUp) { jqLite.on(buttonEl, mouseUpEvents, mouseUpHandler); buttonEl.muiMouseUp = true; } // create ripple element var rippleEl = createRippleEl(ev, buttonEl); buttonEl.appendChild(rippleEl); // animate in util.requestAnimationFrame(function() { jqLite.addClass(rippleEl, 'mui--animate-in mui--active'); }); } /** * MouseUp event handler. * @param {Event} ev - The DOM event */ function mouseUpHandler(ev) { var children = this.children, i = children.length, rippleEls = [], el; // animate out ripples while (i--) { el = children[i]; if (jqLite.hasClass(el, rippleClass)) { jqLite.addClass(el, 'mui--animate-out'); rippleEls.push(el); } } // remove ripples after animation if (rippleEls.length) { setTimeout(function() { var i = rippleEls.length, el, parentNode; // remove elements while (i--) { el = rippleEls[i]; parentNode = el.parentNode; if (parentNode) parentNode.removeChild(el); } }, animationDuration); } } /** * Create ripple element * @param {Element} - buttonEl - The button element. */ function createRippleEl(ev, buttonEl) { // get (x, y) position of click var offset = jqLite.offset(buttonEl), clickEv = (ev.type === 'touchstart') ? ev.touches[0] : ev, xPos = clickEv.pageX - offset.left, yPos = clickEv.pageY - offset.top, diameter, radius, rippleEl; // calculate diameter diameter = Math.sqrt(offset.width * offset.width + offset.height * offset.height) * 2; // create element rippleEl = document.createElement('div'), rippleEl.className = rippleClass; radius = diameter / 2; jqLite.css(rippleEl, { height: diameter + 'px', width: diameter + 'px', top: yPos - radius + 'px', left: xPos - radius + 'px' }); return rippleEl; } /** Define module API */ module.exports = { /** Initialize module listeners */ initListeners: function() { var doc = document; // markup elements available when method is called var elList = doc.getElementsByClassName(btnClass); for (var i=elList.length - 1; i >= 0; i--) initialize(elList[i]); // listen for new elements util.onNodeInserted(function(el) { if (jqLite.hasClass(el, btnClass)) initialize(el); }); } }; },{"./lib/jqLite":4,"./lib/util":5}],10:[function(require,module,exports){ /** * MUI CSS/JS select module * @module forms/select */ 'use strict'; var jqLite = require('./lib/jqLite'), util = require('./lib/util'), formlib = require('./lib/forms'), wrapperClass = 'mui-select', cssSelector = '.mui-select > select', menuClass = 'mui-select__menu', selectedClass = 'mui--is-selected', doc = document, win = window; /** * Initialize select element. * @param {Element} selectEl - The select element. */ function initialize(selectEl) { // check flag if (selectEl._muiSelect === true) return; else selectEl._muiSelect = true; // use default behavior on touch devices if ('ontouchstart' in doc.documentElement) return; // initialize element new Select(selectEl); } /** * Creates a new Select object * @class */ function Select(selectEl) { // instance variables this.selectEl = selectEl; this.wrapperEl = selectEl.parentNode; this.useDefault = false; // currently unused but let's keep just in case // attach event handlers jqLite.on(selectEl, 'mousedown', util.callback(this, 'mousedownHandler')); jqLite.on(selectEl, 'focus', util.callback(this, 'focusHandler')); jqLite.on(selectEl, 'click', util.callback(this, 'clickHandler')); // make wrapper focusable and fix firefox bug this.wrapperEl.tabIndex = -1; var callbackFn = util.callback(this, 'wrapperFocusHandler'); jqLite.on(this.wrapperEl, 'focus', callbackFn); } /** * Disable default dropdown on mousedown. * @param {Event} ev - The DOM event */ Select.prototype.mousedownHandler = function(ev) { if (ev.button !== 0 || this.useDefault === true) return; ev.preventDefault(); } /** * Handle focus event on select element. * @param {Event} ev - The DOM event */ Select.prototype.focusHandler = function(ev) { // check flag if (this.useDefault === true) return; var selectEl = this.selectEl, wrapperEl = this.wrapperEl, tabIndex = selectEl.tabIndex, keydownFn = util.callback(this, 'keydownHandler'); // attach keydown handler jqLite.on(doc, 'keydown', keydownFn); // disable tabfocus once selectEl.tabIndex = -1; jqLite.one(wrapperEl, 'blur', function() { selectEl.tabIndex = tabIndex; jqLite.off(doc, 'keydown', keydownFn); }); // defer focus to parent wrapperEl.focus(); } /** * Handle keydown events on doc **/ Select.prototype.keydownHandler = function(ev) { var keyCode = ev.keyCode; // spacebar, down, up if (keyCode === 32 || keyCode === 38 || keyCode === 40) { // prevent win scroll ev.preventDefault(); if (this.selectEl.disabled !== true) this.renderMenu(); } } /** * Handle focus event on wrapper element. */ Select.prototype.wrapperFocusHandler = function() { // firefox bugfix if (this.selectEl.disabled) return this.wrapperEl.blur(); } /** * Handle click events on select element. * @param {Event} ev - The DOM event */ Select.prototype.clickHandler = function(ev) { // only left clicks if (ev.button !== 0) return; this.renderMenu(); } /** * Render options dropdown. */ Select.prototype.renderMenu = function() { // check and reset flag if (this.useDefault === true) return this.useDefault = false; new Menu(this.wrapperEl, this.selectEl); } /** * Creates a new Menu * @class */ function Menu(wrapperEl, selectEl) { // add scroll lock util.enableScrollLock(); // instance variables this.indexMap = {}; this.origIndex = null; this.currentIndex = null; this.selectEl = selectEl; this.menuEl = this._createMenuEl(wrapperEl, selectEl); this.clickCallbackFn = util.callback(this, 'clickHandler'); this.keydownCallbackFn = util.callback(this, 'keydownHandler'); this.destroyCallbackFn = util.callback(this, 'destroy'); // add to DOM wrapperEl.appendChild(this.menuEl); jqLite.scrollTop(this.menuEl, this.menuEl._muiScrollTop); // blur active element setTimeout(function() { // ie10 bugfix if (doc.activeElement.nodeName.toLowerCase() !== "body") { doc.activeElement.blur(); } }, 0); // attach event handlers jqLite.on(this.menuEl, 'click', this.clickCallbackFn); jqLite.on(doc, 'keydown', this.keydownCallbackFn); jqLite.on(win, 'resize', this.destroyCallbackFn); // attach event handler after current event loop exits var fn = this.destroyCallbackFn; setTimeout(function() {jqLite.on(doc, 'click', fn);}, 0); } /** * Create menu element * @param {Element} selectEl - The select element */ Menu.prototype._createMenuEl = function(wrapperEl, selectEl) { var menuEl = doc.createElement('div'), childEls = selectEl.children, indexNum = 0, indexMap = this.indexMap, selectedRow = 0, loopEl, rowEl, optionEls, inGroup, i, iMax, j, jMax; menuEl.className = menuClass; for (i=0, iMax=childEls.length; i < iMax; i++) { loopEl = childEls[i]; if (loopEl.tagName === 'OPTGROUP') { // add row item to menu rowEl = doc.createElement('div'); rowEl.textContent = loopEl.label; rowEl.className = 'mui-optgroup__label'; menuEl.appendChild(rowEl); inGroup = true; optionEls = loopEl.children; } else { inGroup = false; optionEls = [loopEl]; } // loop through option elements for (j=0, jMax=optionEls.length; j < jMax; j++) { loopEl = optionEls[j]; // add row item to menu rowEl = doc.createElement('div'); rowEl.textContent = loopEl.textContent; rowEl._muiIndex = indexNum; // handle selected options if (loopEl.selected) { rowEl.className = selectedClass; selectedRow = menuEl.children.length; } // handle optgroup options if (inGroup) jqLite.addClass(rowEl, 'mui-optgroup__option'); menuEl.appendChild(rowEl); // add to index map indexMap[indexNum] = rowEl; indexNum += 1; } } // save indices var selectedIndex = selectEl.selectedIndex; this.origIndex = selectedIndex; this.currentIndex = selectedIndex; // set position var props = formlib.getMenuPositionalCSS( wrapperEl, menuEl.children.length, selectedRow ); jqLite.css(menuEl, props); menuEl._muiScrollTop = props.scrollTop; return menuEl; } /** * Handle keydown events on doc element. * @param {Event} ev - The DOM event */ Menu.prototype.keydownHandler = function(ev) { var keyCode = ev.keyCode; // tab if (keyCode === 9) return this.destroy(); // escape | up | down | enter if (keyCode === 27 || keyCode === 40 || keyCode === 38 || keyCode === 13) { ev.preventDefault(); } if (keyCode === 27) { this.destroy(); } else if (keyCode === 40) { this.increment(); } else if (keyCode === 38) { this.decrement(); } else if (keyCode === 13) { this.selectCurrent(); this.destroy(); } } /** * Handle click events on menu element. * @param {Event} ev - The DOM event */ Menu.prototype.clickHandler = function(ev) { // don't allow events to bubble ev.stopPropagation(); var index = ev.target._muiIndex; // ignore clicks on non-items if (index === undefined) return; // select option this.currentIndex = index; this.selectCurrent(); // destroy menu this.destroy(); } /** * Increment selected item */ Menu.prototype.increment = function() { if (this.currentIndex === this.selectEl.length - 1) return; // un-select old row jqLite.removeClass(this.indexMap[this.currentIndex], selectedClass); // select new row this.currentIndex += 1; jqLite.addClass(this.indexMap[this.currentIndex], selectedClass); } /** * Decrement selected item */ Menu.prototype.decrement = function() { if (this.currentIndex === 0) return; // un-select old row jqLite.removeClass(this.indexMap[this.currentIndex], selectedClass); // select new row this.currentIndex -= 1; jqLite.addClass(this.indexMap[this.currentIndex], selectedClass); } /** * Select current item */ Menu.prototype.selectCurrent = function() { if (this.currentIndex !== this.origIndex) { this.selectEl.selectedIndex = this.currentIndex; // trigger change event util.dispatchEvent(this.selectEl, 'change'); } } /** * Destroy menu and detach event handlers */ Menu.prototype.destroy = function() { // remove element and focus element var parentNode = this.menuEl.parentNode; if (parentNode) parentNode.removeChild(this.menuEl); this.selectEl.focus(); // remove scroll lock util.disableScrollLock(true); // remove event handlers jqLite.off(this.menuEl, 'click', this.clickCallbackFn); jqLite.off(doc, 'keydown', this.keydownCallbackFn); jqLite.off(doc, 'click', this.destroyCallbackFn); jqLite.off(win, 'resize', this.destroyCallbackFn); } /** Define module API */ module.exports = { /** Initialize module listeners */ initListeners: function() { // markup elements available when method is called var elList = doc.querySelectorAll(cssSelector); for (var i=elList.length - 1; i >= 0; i--) initialize(elList[i]); // listen for new elements util.onNodeInserted(function(el) { if (el.tagName === 'SELECT' && jqLite.hasClass(el.parentNode, wrapperClass)) { initialize(el); } }); } }; },{"./lib/forms":3,"./lib/jqLite":4,"./lib/util":5}],11:[function(require,module,exports){ /** * MUI CSS/JS tabs module * @module tabs */ 'use strict'; var jqLite = require('./lib/jqLite'), util = require('./lib/util'), attrKey = 'data-mui-toggle', attrSelector = '[' + attrKey + '="tab"]', controlsAttrKey = 'data-mui-controls', activeClass = 'mui--is-active', showstartKey = 'mui.tabs.showstart', showendKey = 'mui.tabs.showend', hidestartKey = 'mui.tabs.hidestart', hideendKey = 'mui.tabs.hideend'; /** * Initialize the toggle element * @param {Element} toggleEl - The toggle element. */ function initialize(toggleEl) { // check flag if (toggleEl._muiTabs === true) return; else toggleEl._muiTabs = true; // attach click handler jqLite.on(toggleEl, 'click', clickHandler); } /** * Handle clicks on the toggle element. * @param {Event} ev - The DOM event. */ function clickHandler(ev) { // only left clicks if (ev.button !== 0) return; var toggleEl = this; // exit if toggle element is disabled if (toggleEl.getAttribute('disabled') !== null) return; activateTab(toggleEl); } /** * Activate the tab controlled by the toggle element. * @param {Element} toggleEl - The toggle element. */ function activateTab(currToggleEl) { var currTabEl = currToggleEl.parentNode, currPaneId = currToggleEl.getAttribute(controlsAttrKey), currPaneEl = document.getElementById(currPaneId), prevTabEl, prevPaneEl, prevPaneId, prevToggleEl, currData, prevData, ev1, ev2, cssSelector; // exit if already active if (jqLite.hasClass(currTabEl, activeClass)) return; // raise error if pane doesn't exist if (!currPaneEl) util.raiseError('Tab pane "' + currPaneId + '" not found'); // get previous pane prevPaneEl = getActiveSibling(currPaneEl); prevPaneId = prevPaneEl.id; // get previous toggle and tab elements cssSelector = '[' + controlsAttrKey + '="' + prevPaneId + '"]'; prevToggleEl = document.querySelectorAll(cssSelector)[0]; prevTabEl = prevToggleEl.parentNode; // define event data currData = {paneId: currPaneId, relatedPaneId: prevPaneId}; prevData = {paneId: prevPaneId, relatedPaneId: currPaneId}; // dispatch 'hidestart', 'showstart' events ev1 = util.dispatchEvent(prevToggleEl, hidestartKey, true, true, prevData); ev2 = util.dispatchEvent(currToggleEl, showstartKey, true, true, currData); // let events bubble setTimeout(function() { // exit if either event was canceled if (ev1.defaultPrevented || ev2.defaultPrevented) return; // de-activate previous if (prevTabEl) jqLite.removeClass(prevTabEl, activeClass); if (prevPaneEl) jqLite.removeClass(prevPaneEl, activeClass); // activate current jqLite.addClass(currTabEl, activeClass); jqLite.addClass(currPaneEl, activeClass); // dispatch 'hideend', 'showend' events util.dispatchEvent(prevToggleEl, hideendKey, true, false, prevData); util.dispatchEvent(currToggleEl, showendKey, true, false, currData); }, 0); } /** * Get previous active sibling. * @param {Element} el - The anchor element. */ function getActiveSibling(el) { var elList = el.parentNode.children, q = elList.length, activeEl = null, tmpEl; while (q-- && !activeEl) { tmpEl = elList[q]; if (tmpEl !== el && jqLite.hasClass(tmpEl, activeClass)) activeEl = tmpEl } return activeEl; } /** Define module API */ module.exports = { /** Initialize module listeners */ initListeners: function() { // markup elements available when method is called var elList = document.querySelectorAll(attrSelector); for (var i=elList.length - 1; i >= 0; i--) initialize(elList[i]); // TODO: listen for new elements util.onNodeInserted(function(el) { if (el.getAttribute(attrKey) === 'tab') initialize(el); }); }, /** External API */ api: { activate: function(paneId) { var cssSelector = '[' + controlsAttrKey + '=' + paneId + ']', toggleEl = document.querySelectorAll(cssSelector); if (!toggleEl.length) { util.raiseError('Tab control for pane "' + paneId + '" not found'); } activateTab(toggleEl[0]); } } }; },{"./lib/jqLite":4,"./lib/util":5}],12:[function(require,module,exports){ /** * MUI CSS/JS form-control module * @module forms/form-control */ 'use strict'; var jqLite = require('./lib/jqLite'), util = require('./lib/util'), cssSelector = '.mui-textfield > input, .mui-textfield > textarea', emptyClass = 'mui--is-empty', notEmptyClass = 'mui--is-not-empty', dirtyClass = 'mui--is-dirty', floatingLabelClass = 'mui-textfield--float-label'; /** * Initialize input element. * @param {Element} inputEl - The input element. */ function initialize(inputEl) { // check flag if (inputEl._muiTextfield === true) return; else inputEl._muiTextfield = true; if (inputEl.value.length) jqLite.addClass(inputEl, notEmptyClass); else jqLite.addClass(inputEl, emptyClass); jqLite.on(inputEl, 'input change', inputHandler); // add dirty class on focus jqLite.on(inputEl, 'focus', function(){jqLite.addClass(this, dirtyClass);}); } /** * Handle input events. */ function inputHandler() { var inputEl = this; if (inputEl.value.length) { jqLite.removeClass(inputEl, emptyClass); jqLite.addClass(inputEl, notEmptyClass); } else { jqLite.removeClass(inputEl, notEmptyClass); jqLite.addClass(inputEl, emptyClass) } jqLite.addClass(inputEl, dirtyClass); } /** Define module API */ module.exports = { /** Initialize input elements */ initialize: initialize, /** Initialize module listeners */ initListeners: function() { var doc = document; // markup elements available when method is called var elList = doc.querySelectorAll(cssSelector); for (var i=elList.length - 1; i >= 0; i--) initialize(elList[i]); // listen for new elements util.onNodeInserted(function(el) { if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') initialize(el); }); // add transition css for floating labels setTimeout(function() { var css = '.mui-textfield.mui-textfield--float-label > label {' + [ '-webkit-transition', '-moz-transition', '-o-transition', 'transition', '' ].join(':all .15s ease-out;') + '}'; util.loadStyle(css); }, 150); // pointer-events shim for floating labels if (util.supportsPointerEvents() === false) { jqLite.on(document, 'click', function(ev) { var targetEl = ev.target; if (targetEl.tagName === 'LABEL' && jqLite.hasClass(targetEl.parentNode, floatingLabelClass)) { var inputEl = targetEl.previousElementSibling; if (inputEl) inputEl.focus(); } }); } } }; },{"./lib/jqLite":4,"./lib/util":5}]},{},[1])
AT.prototype.atSepHelpers = { sepText: function(){ return T9n.get(AccountsTemplates.texts.sep, markIfMissing=false); }, };
/* * Date Format 1.2.3 * (c) 2007-2009 Steven Levithan <stevenlevithan.com> * MIT license * * Includes enhancements by Scott Trenda <scott.trenda.net> * and Kris Kowal <cixar.com/~kris.kowal/> * * Accepts a date, a mask, or a date and a mask. * Returns a formatted version of the given date. * The date defaults to the current date/time. * The mask defaults to dateFormat.masks.default. */ var dateFormat = function () { var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g, timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g, timezoneClip = /[^-+\dA-Z]/g, pad = function (val, len) { val = String(val); len = len || 2; while (val.length < len) val = "0" + val; return val; }; // Regexes and supporting functions are cached through closure return function (date, mask, utc) { var dF = dateFormat; // You can't provide utc if you skip other args (use the "UTC:" mask prefix) if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) { mask = date; date = undefined; } // Passing date through Date applies Date.parse, if necessary date = date ? new Date(date) : new Date; if (isNaN(date)) throw SyntaxError("invalid date"); mask = String(dF.masks[mask] || mask || dF.masks["default"]); // Allow setting the utc argument via the mask if (mask.slice(0, 4) == "UTC:") { mask = mask.slice(4); utc = true; } var _ = utc ? "getUTC" : "get", d = date[_ + "Date"](), D = date[_ + "Day"](), m = date[_ + "Month"](), y = date[_ + "FullYear"](), H = date[_ + "Hours"](), M = date[_ + "Minutes"](), s = date[_ + "Seconds"](), L = date[_ + "Milliseconds"](), o = utc ? 0 : date.getTimezoneOffset(), flags = { d: d, dd: pad(d), ddd: dF.i18n.dayNames[D], dddd: dF.i18n.dayNames[D + 7], m: m + 1, mm: pad(m + 1), mmm: dF.i18n.monthNames[m], mmmm: dF.i18n.monthNames[m + 12], yy: String(y).slice(2), yyyy: y, h: H % 12 || 12, hh: pad(H % 12 || 12), H: H, HH: pad(H), M: M, MM: pad(M), s: s, ss: pad(s), l: pad(L, 3), L: pad(L > 99 ? Math.round(L / 10) : L), t: H < 12 ? "a" : "p", tt: H < 12 ? "am" : "pm", T: H < 12 ? "A" : "P", TT: H < 12 ? "AM" : "PM", Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""), o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4), S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10] }; return mask.replace(token, function ($0) { return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1); }); }; }(); // Some common format strings dateFormat.masks = { "default": "ddd mmm dd yyyy HH:MM:ss", shortDate: "m/d/yy", mediumDate: "mmm d, yyyy", longDate: "mmmm d, yyyy", fullDate: "dddd, mmmm d, yyyy", shortTime: "h:MM TT", mediumTime: "h:MM:ss TT", longTime: "h:MM:ss TT Z", isoDate: "yyyy-mm-dd", isoTime: "HH:MM:ss", isoDateTime: "yyyy-mm-dd'T'HH:MM:ss", isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'" }; // Internationalization strings dateFormat.i18n = { dayNames: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], monthNames: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] }; // For convenience... Date.prototype.format = function (mask, utc) { return dateFormat(this, mask, utc); };
app.controller("LayersLayergroupSimpleController", [ "$scope", function($scope) { angular.extend($scope, { center: { lat: 39, lng: -100, zoom: 3 }, layers: { baselayers: { xyz: { name: 'OpenStreetMap (XYZ)', url: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', type: 'xyz' } }, overlays: {} } }); var tileLayer = { name: 'Countries', type: 'xyz', url: 'http://{s}.tiles.mapbox.com/v3/milkator.press_freedom/{z}/{x}/{y}.png', visible: true, layerOptions: { attribution: 'Map data &copy; 2013 Natural Earth | Data &copy; 2013 <a href="http://www.reporter-ohne-grenzen.de/ranglisten/rangliste-2013/">ROG/RSF</a>', maxZoom: 5 } }; var utfGrid = { name: 'UtfGrid', type: 'utfGrid', url: 'http://{s}.tiles.mapbox.com/v3/milkator.press_freedom/{z}/{x}/{y}.grid.json?callback={cb}', visible: true, pluginOptions: { maxZoom: 5, resolution: 4 } }; var group = { name: 'Group Layer', type: 'group', visible: true, layerOptions: { layers: [ tileLayer, utfGrid], maxZoom: 5 } }; $scope.layers['overlays']['Group Layer'] = group; $scope.$on('leafletDirectiveMap.utfgridMouseover', function(event, leafletEvent) { $scope.country = leafletEvent.data.name; }); }]);
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v5.0.0-alpha.5 * @link http://www.ag-grid.com/ * @license MIT */ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var csvCreator_1 = require("./csvCreator"); var rowRenderer_1 = require("./rendering/rowRenderer"); var headerRenderer_1 = require("./headerRendering/headerRenderer"); var filterManager_1 = require("./filter/filterManager"); var columnController_1 = require("./columnController/columnController"); var selectionController_1 = require("./selectionController"); var gridOptionsWrapper_1 = require("./gridOptionsWrapper"); var gridPanel_1 = require("./gridPanel/gridPanel"); var valueService_1 = require("./valueService"); var masterSlaveService_1 = require("./masterSlaveService"); var eventService_1 = require("./eventService"); var floatingRowModel_1 = require("./rowControllers/floatingRowModel"); var constants_1 = require("./constants"); var context_1 = require("./context/context"); var gridCore_1 = require("./gridCore"); var sortController_1 = require("./sortController"); var paginationController_1 = require("./rowControllers/paginationController"); var focusedCellController_1 = require("./focusedCellController"); var utils_1 = require("./utils"); var cellRendererFactory_1 = require("./rendering/cellRendererFactory"); var cellEditorFactory_1 = require("./rendering/cellEditorFactory"); var GridApi = (function () { function GridApi() { } GridApi.prototype.init = function () { if (this.rowModel.getType() === constants_1.Constants.ROW_MODEL_TYPE_NORMAL) { this.inMemoryRowModel = this.rowModel; } }; /** Used internally by grid. Not intended to be used by the client. Interface may change between releases. */ GridApi.prototype.__getMasterSlaveService = function () { return this.masterSlaveService; }; GridApi.prototype.getFirstRenderedRow = function () { return this.rowRenderer.getFirstVirtualRenderedRow(); }; GridApi.prototype.getLastRenderedRow = function () { return this.rowRenderer.getLastVirtualRenderedRow(); }; GridApi.prototype.getDataAsCsv = function (params) { return this.csvCreator.getDataAsCsv(params); }; GridApi.prototype.exportDataAsCsv = function (params) { this.csvCreator.exportDataAsCsv(params); }; GridApi.prototype.setDatasource = function (datasource) { if (this.gridOptionsWrapper.isRowModelPagination()) { this.paginationController.setDatasource(datasource); } else if (this.gridOptionsWrapper.isRowModelVirtual()) { this.rowModel.setDatasource(datasource); } else { console.warn("ag-Grid: you can only use a datasource when gridOptions.rowModelType is '" + constants_1.Constants.ROW_MODEL_TYPE_VIRTUAL + "' or '" + constants_1.Constants.ROW_MODEL_TYPE_PAGINATION + "'"); } }; GridApi.prototype.setViewportDatasource = function (viewportDatasource) { if (this.gridOptionsWrapper.isRowModelViewport()) { // this is bad coding, because it's using an interface that's exposed in the enterprise. // really we should create an interface in the core for viewportDatasource and let // the enterprise implement it, rather than casting to 'any' here this.rowModel.setViewportDatasource(viewportDatasource); } else { console.warn("ag-Grid: you can only use a datasource when gridOptions.rowModelType is '" + constants_1.Constants.ROW_MODEL_TYPE_VIEWPORT + "'"); } }; GridApi.prototype.setRowData = function (rowData) { if (this.gridOptionsWrapper.isRowModelDefault()) { this.inMemoryRowModel.setRowData(rowData, true); } else { console.log('cannot call setRowData unless using normal row model'); } }; GridApi.prototype.setFloatingTopRowData = function (rows) { this.floatingRowModel.setFloatingTopRowData(rows); }; GridApi.prototype.setFloatingBottomRowData = function (rows) { this.floatingRowModel.setFloatingBottomRowData(rows); }; GridApi.prototype.setColumnDefs = function (colDefs) { this.columnController.setColumnDefs(colDefs); }; GridApi.prototype.refreshRows = function (rowNodes) { this.rowRenderer.refreshRows(rowNodes); }; GridApi.prototype.refreshCells = function (rowNodes, colIds, animate) { if (animate === void 0) { animate = false; } this.rowRenderer.refreshCells(rowNodes, colIds, animate); }; GridApi.prototype.rowDataChanged = function (rows) { this.rowRenderer.rowDataChanged(rows); }; GridApi.prototype.refreshView = function () { this.rowRenderer.refreshView(); }; GridApi.prototype.softRefreshView = function () { this.rowRenderer.softRefreshView(); }; GridApi.prototype.refreshGroupRows = function () { this.rowRenderer.refreshGroupRows(); }; GridApi.prototype.refreshHeader = function () { // need to review this - the refreshHeader should also refresh all icons in the header this.headerRenderer.refreshHeader(); }; GridApi.prototype.isAnyFilterPresent = function () { return this.filterManager.isAnyFilterPresent(); }; GridApi.prototype.isAdvancedFilterPresent = function () { return this.filterManager.isAdvancedFilterPresent(); }; GridApi.prototype.isQuickFilterPresent = function () { return this.filterManager.isQuickFilterPresent(); }; GridApi.prototype.getModel = function () { return this.rowModel; }; GridApi.prototype.onGroupExpandedOrCollapsed = function (refreshFromIndex) { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call onGroupExpandedOrCollapsed unless using normal row model'); } this.inMemoryRowModel.refreshModel(constants_1.Constants.STEP_MAP, refreshFromIndex); }; GridApi.prototype.refreshInMemoryRowModel = function () { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call refreshInMemoryRowModel unless using normal row model'); } this.inMemoryRowModel.refreshModel(constants_1.Constants.STEP_EVERYTHING); }; GridApi.prototype.expandAll = function () { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call expandAll unless using normal row model'); } this.inMemoryRowModel.expandOrCollapseAll(true); }; GridApi.prototype.collapseAll = function () { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call collapseAll unless using normal row model'); } this.inMemoryRowModel.expandOrCollapseAll(false); }; GridApi.prototype.addVirtualRowListener = function (eventName, rowIndex, callback) { if (typeof eventName !== 'string') { console.log('ag-Grid: addVirtualRowListener is deprecated, please use addRenderedRowListener.'); } this.addRenderedRowListener(eventName, rowIndex, callback); }; GridApi.prototype.addRenderedRowListener = function (eventName, rowIndex, callback) { if (eventName === 'virtualRowRemoved') { console.log('ag-Grid: event virtualRowRemoved is deprecated, now called renderedRowRemoved'); eventName = '' + ''; } if (eventName === 'virtualRowSelected') { console.log('ag-Grid: event virtualRowSelected is deprecated, to register for individual row ' + 'selection events, add a listener directly to the row node.'); } this.rowRenderer.addRenderedRowListener(eventName, rowIndex, callback); }; GridApi.prototype.setQuickFilter = function (newFilter) { this.filterManager.setQuickFilter(newFilter); }; GridApi.prototype.selectIndex = function (index, tryMulti, suppressEvents) { console.log('ag-Grid: do not use api for selection, call node.setSelected(value) instead'); if (suppressEvents) { console.log('ag-Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it'); } this.selectionController.selectIndex(index, tryMulti); }; GridApi.prototype.deselectIndex = function (index, suppressEvents) { if (suppressEvents === void 0) { suppressEvents = false; } console.log('ag-Grid: do not use api for selection, call node.setSelected(value) instead'); if (suppressEvents) { console.log('ag-Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it'); } this.selectionController.deselectIndex(index); }; GridApi.prototype.selectNode = function (node, tryMulti, suppressEvents) { if (tryMulti === void 0) { tryMulti = false; } if (suppressEvents === void 0) { suppressEvents = false; } console.log('ag-Grid: API for selection is deprecated, call node.setSelected(value) instead'); if (suppressEvents) { console.log('ag-Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it'); } node.setSelectedParams({ newValue: true, clearSelection: !tryMulti }); }; GridApi.prototype.deselectNode = function (node, suppressEvents) { if (suppressEvents === void 0) { suppressEvents = false; } console.log('ag-Grid: API for selection is deprecated, call node.setSelected(value) instead'); if (suppressEvents) { console.log('ag-Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it'); } node.setSelectedParams({ newValue: false }); }; GridApi.prototype.selectAll = function () { this.selectionController.selectAllRowNodes(); }; GridApi.prototype.deselectAll = function () { this.selectionController.deselectAllRowNodes(); }; GridApi.prototype.recomputeAggregates = function () { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call recomputeAggregates unless using normal row model'); } this.inMemoryRowModel.refreshModel(constants_1.Constants.STEP_AGGREGATE); }; GridApi.prototype.sizeColumnsToFit = function () { if (this.gridOptionsWrapper.isForPrint()) { console.warn('ag-grid: sizeColumnsToFit does not work when forPrint=true'); return; } this.gridPanel.sizeColumnsToFit(); }; GridApi.prototype.showLoadingOverlay = function () { this.gridPanel.showLoadingOverlay(); }; GridApi.prototype.showNoRowsOverlay = function () { this.gridPanel.showNoRowsOverlay(); }; GridApi.prototype.hideOverlay = function () { this.gridPanel.hideOverlay(); }; GridApi.prototype.isNodeSelected = function (node) { console.log('ag-Grid: no need to call api.isNodeSelected(), just call node.isSelected() instead'); return node.isSelected(); }; GridApi.prototype.getSelectedNodesById = function () { console.error('ag-Grid: since version 3.4, getSelectedNodesById no longer exists, use getSelectedNodes() instead'); return null; }; GridApi.prototype.getSelectedNodes = function () { return this.selectionController.getSelectedNodes(); }; GridApi.prototype.getSelectedRows = function () { return this.selectionController.getSelectedRows(); }; GridApi.prototype.getBestCostNodeSelection = function () { return this.selectionController.getBestCostNodeSelection(); }; GridApi.prototype.getRenderedNodes = function () { return this.rowRenderer.getRenderedNodes(); }; GridApi.prototype.ensureColIndexVisible = function (index) { console.warn('ag-Grid: ensureColIndexVisible(index) no longer supported, use ensureColumnVisible(colKey) instead.'); }; GridApi.prototype.ensureColumnVisible = function (key) { this.gridPanel.ensureColumnVisible(key); }; GridApi.prototype.ensureIndexVisible = function (index) { this.gridPanel.ensureIndexVisible(index); }; GridApi.prototype.ensureNodeVisible = function (comparator) { this.gridCore.ensureNodeVisible(comparator); }; GridApi.prototype.forEachLeafNode = function (callback) { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call forEachNodeAfterFilter unless using normal row model'); } this.inMemoryRowModel.forEachLeafNode(callback); }; GridApi.prototype.forEachNode = function (callback) { this.rowModel.forEachNode(callback); }; GridApi.prototype.forEachNodeAfterFilter = function (callback) { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call forEachNodeAfterFilter unless using normal row model'); } this.inMemoryRowModel.forEachNodeAfterFilter(callback); }; GridApi.prototype.forEachNodeAfterFilterAndSort = function (callback) { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call forEachNodeAfterFilterAndSort unless using normal row model'); } this.inMemoryRowModel.forEachNodeAfterFilterAndSort(callback); }; GridApi.prototype.getFilterApiForColDef = function (colDef) { console.warn('ag-grid API method getFilterApiForColDef deprecated, use getFilterApi instead'); return this.getFilterApi(colDef); }; GridApi.prototype.getFilterApi = function (key) { var column = this.columnController.getPrimaryColumn(key); if (column) { return this.filterManager.getFilterApi(column); } }; GridApi.prototype.destroyFilter = function (key) { var column = this.columnController.getPrimaryColumn(key); if (column) { return this.filterManager.destroyFilter(column); } }; GridApi.prototype.getColumnDef = function (key) { var column = this.columnController.getPrimaryColumn(key); if (column) { return column.getColDef(); } else { return null; } }; GridApi.prototype.onFilterChanged = function () { this.filterManager.onFilterChanged(); }; GridApi.prototype.setSortModel = function (sortModel) { this.sortController.setSortModel(sortModel); }; GridApi.prototype.getSortModel = function () { return this.sortController.getSortModel(); }; GridApi.prototype.setFilterModel = function (model) { this.filterManager.setFilterModel(model); }; GridApi.prototype.getFilterModel = function () { return this.filterManager.getFilterModel(); }; GridApi.prototype.getFocusedCell = function () { return this.focusedCellController.getFocusedCell(); }; GridApi.prototype.setFocusedCell = function (rowIndex, colKey, floating) { this.focusedCellController.setFocusedCell(rowIndex, colKey, floating, true); }; GridApi.prototype.setHeaderHeight = function (headerHeight) { this.gridOptionsWrapper.setHeaderHeight(headerHeight); }; GridApi.prototype.showToolPanel = function (show) { this.gridCore.showToolPanel(show); }; GridApi.prototype.isToolPanelShowing = function () { return this.gridCore.isToolPanelShowing(); }; GridApi.prototype.doLayout = function () { this.gridCore.doLayout(); }; GridApi.prototype.getValue = function (colKey, rowNode) { var column = this.columnController.getPrimaryColumn(colKey); return this.valueService.getValue(column, rowNode); }; GridApi.prototype.addEventListener = function (eventType, listener) { this.eventService.addEventListener(eventType, listener); }; GridApi.prototype.addGlobalListener = function (listener) { this.eventService.addGlobalListener(listener); }; GridApi.prototype.removeEventListener = function (eventType, listener) { this.eventService.removeEventListener(eventType, listener); }; GridApi.prototype.removeGlobalListener = function (listener) { this.eventService.removeGlobalListener(listener); }; GridApi.prototype.dispatchEvent = function (eventType, event) { this.eventService.dispatchEvent(eventType, event); }; GridApi.prototype.destroy = function () { this.context.destroy(); }; GridApi.prototype.resetQuickFilter = function () { this.rowModel.forEachNode(function (node) { return node.quickFilterAggregateText = null; }); }; GridApi.prototype.getRangeSelections = function () { if (this.rangeController) { return this.rangeController.getCellRanges(); } else { console.warn('ag-Grid: cell range selection is only available in ag-Grid Enterprise'); return null; } }; GridApi.prototype.addRangeSelection = function (rangeSelection) { if (!this.rangeController) { console.warn('ag-Grid: cell range selection is only available in ag-Grid Enterprise'); } this.rangeController.addRange(rangeSelection); }; GridApi.prototype.clearRangeSelection = function () { if (!this.rangeController) { console.warn('ag-Grid: cell range selection is only available in ag-Grid Enterprise'); } this.rangeController.clearSelection(); }; GridApi.prototype.copySelectedRowsToClipboard = function () { if (!this.clipboardService) { console.warn('ag-Grid: clipboard is only available in ag-Grid Enterprise'); } this.clipboardService.copySelectedRowsToClipboard(); }; GridApi.prototype.copySelectedRangeToClipboard = function () { if (!this.clipboardService) { console.warn('ag-Grid: clipboard is only available in ag-Grid Enterprise'); } this.clipboardService.copySelectedRangeToClipboard(); }; GridApi.prototype.copySelectedRangeDown = function () { if (!this.clipboardService) { console.warn('ag-Grid: clipboard is only available in ag-Grid Enterprise'); } this.clipboardService.copyRangeDown(); }; GridApi.prototype.showColumnMenuAfterButtonClick = function (colKey, buttonElement) { var column = this.columnController.getPrimaryColumn(colKey); this.menuFactory.showMenuAfterButtonClick(column, buttonElement); }; GridApi.prototype.showColumnMenuAfterMouseClick = function (colKey, mouseEvent) { var column = this.columnController.getPrimaryColumn(colKey); this.menuFactory.showMenuAfterMouseEvent(column, mouseEvent); }; GridApi.prototype.stopEditing = function (cancel) { if (cancel === void 0) { cancel = false; } this.rowRenderer.stopEditing(cancel); }; GridApi.prototype.addAggFunc = function (key, aggFunc) { if (this.aggFuncService) { this.aggFuncService.addAggFunc(key, aggFunc); } }; GridApi.prototype.addAggFuncs = function (aggFuncs) { if (this.aggFuncService) { this.aggFuncService.addAggFuncs(aggFuncs); } }; GridApi.prototype.clearAggFuncs = function () { if (this.aggFuncService) { this.aggFuncService.clear(); } }; __decorate([ context_1.Autowired('csvCreator'), __metadata('design:type', csvCreator_1.CsvCreator) ], GridApi.prototype, "csvCreator", void 0); __decorate([ context_1.Autowired('gridCore'), __metadata('design:type', gridCore_1.GridCore) ], GridApi.prototype, "gridCore", void 0); __decorate([ context_1.Autowired('rowRenderer'), __metadata('design:type', rowRenderer_1.RowRenderer) ], GridApi.prototype, "rowRenderer", void 0); __decorate([ context_1.Autowired('headerRenderer'), __metadata('design:type', headerRenderer_1.HeaderRenderer) ], GridApi.prototype, "headerRenderer", void 0); __decorate([ context_1.Autowired('filterManager'), __metadata('design:type', filterManager_1.FilterManager) ], GridApi.prototype, "filterManager", void 0); __decorate([ context_1.Autowired('columnController'), __metadata('design:type', columnController_1.ColumnController) ], GridApi.prototype, "columnController", void 0); __decorate([ context_1.Autowired('selectionController'), __metadata('design:type', selectionController_1.SelectionController) ], GridApi.prototype, "selectionController", void 0); __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata('design:type', gridOptionsWrapper_1.GridOptionsWrapper) ], GridApi.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.Autowired('gridPanel'), __metadata('design:type', gridPanel_1.GridPanel) ], GridApi.prototype, "gridPanel", void 0); __decorate([ context_1.Autowired('valueService'), __metadata('design:type', valueService_1.ValueService) ], GridApi.prototype, "valueService", void 0); __decorate([ context_1.Autowired('masterSlaveService'), __metadata('design:type', masterSlaveService_1.MasterSlaveService) ], GridApi.prototype, "masterSlaveService", void 0); __decorate([ context_1.Autowired('eventService'), __metadata('design:type', eventService_1.EventService) ], GridApi.prototype, "eventService", void 0); __decorate([ context_1.Autowired('floatingRowModel'), __metadata('design:type', floatingRowModel_1.FloatingRowModel) ], GridApi.prototype, "floatingRowModel", void 0); __decorate([ context_1.Autowired('context'), __metadata('design:type', context_1.Context) ], GridApi.prototype, "context", void 0); __decorate([ context_1.Autowired('rowModel'), __metadata('design:type', Object) ], GridApi.prototype, "rowModel", void 0); __decorate([ context_1.Autowired('sortController'), __metadata('design:type', sortController_1.SortController) ], GridApi.prototype, "sortController", void 0); __decorate([ context_1.Autowired('paginationController'), __metadata('design:type', paginationController_1.PaginationController) ], GridApi.prototype, "paginationController", void 0); __decorate([ context_1.Autowired('focusedCellController'), __metadata('design:type', focusedCellController_1.FocusedCellController) ], GridApi.prototype, "focusedCellController", void 0); __decorate([ context_1.Optional('rangeController'), __metadata('design:type', Object) ], GridApi.prototype, "rangeController", void 0); __decorate([ context_1.Optional('clipboardService'), __metadata('design:type', Object) ], GridApi.prototype, "clipboardService", void 0); __decorate([ context_1.Optional('aggFuncService'), __metadata('design:type', Object) ], GridApi.prototype, "aggFuncService", void 0); __decorate([ context_1.Autowired('menuFactory'), __metadata('design:type', Object) ], GridApi.prototype, "menuFactory", void 0); __decorate([ context_1.Autowired('cellRendererFactory'), __metadata('design:type', cellRendererFactory_1.CellRendererFactory) ], GridApi.prototype, "cellRendererFactory", void 0); __decorate([ context_1.Autowired('cellEditorFactory'), __metadata('design:type', cellEditorFactory_1.CellEditorFactory) ], GridApi.prototype, "cellEditorFactory", void 0); __decorate([ context_1.PostConstruct, __metadata('design:type', Function), __metadata('design:paramtypes', []), __metadata('design:returntype', void 0) ], GridApi.prototype, "init", null); GridApi = __decorate([ context_1.Bean('gridApi'), __metadata('design:paramtypes', []) ], GridApi); return GridApi; })(); exports.GridApi = GridApi;
/* -*- Mode: Javascript; indent-tabs-mode:nil; js-indent-level: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /************************************************************* * * MathJax/localization/vi/MathML.js * * Copyright (c) 2009-2015 The MathJax Consortium * * 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. * */ MathJax.Localization.addTranslation("vi","MathML",{ version: "2.5.0", isLoaded: true, strings: { BadMglyph: "mglyph h\u1ECFng: %1", BadMglyphFont: "Ph\u00F4ng ch\u1EEF h\u1ECFng: %1", MathPlayer: "MathJax kh\u00F4ng th\u1EC3 thi\u1EBFt l\u1EADp MathPlayer.\n\nN\u1EBFu MathPlayer ch\u01B0a \u0111\u01B0\u1EE3c c\u00E0i \u0111\u1EB7t, b\u1EA1n c\u1EA7n ph\u1EA3i c\u00E0i \u0111\u1EB7t n\u00F3 tr\u01B0\u1EDBc ti\u00EAn.\nN\u1EBFu kh\u00F4ng, c\u00E1c t\u00F9y ch\u1ECDn b\u1EA3o m\u1EADt c\u1EE7a b\u1EA1n c\u00F3 th\u1EC3 ng\u0103n tr\u1EDF c\u00E1c \u0111i\u1EC1u khi\u1EC3n ActiveX. H\u00E3y ch\u1ECDn T\u00F9y ch\u1ECDn Internet trong tr\u00ECnh \u0111\u01A1n C\u00F4ng c\u1EE5, qua th\u1EBB B\u1EA3o m\u1EADt, v\u00E0 b\u1EA5m n\u00FAt M\u1EE9c t\u00F9y ch\u1EC9nh. Ki\u1EC3m c\u00E1c h\u1ED9p \u201CCh\u1EA1y \u0111i\u1EC1u khi\u1EC3n ActiveX\u201D v\u00E0 \u201CH\u00E0nh vi nh\u1ECB ph\u00E2n v\u00E0 k\u1ECBch b\u1EA3n\u201D.\n\nHi\u1EC7n t\u1EA1i b\u1EA1n s\u1EBD g\u1EB7p c\u00E1c th\u00F4ng b\u00E1o l\u1ED7i thay v\u00EC to\u00E1n h\u1ECDc \u0111\u01B0\u1EE3c k\u1EBFt xu\u1EA5t.", CantCreateXMLParser: "MathJax kh\u00F4ng th\u1EC3 t\u1EA1o ra b\u1ED9 ph\u00E2n t\u00EDch XML cho MathML. H\u00E3y ch\u1ECDn T\u00F9y ch\u1ECDn Internet trong tr\u00ECnh \u0111\u01A1n C\u00F4ng c\u1EE5, qua th\u1EBB B\u1EA3o m\u1EADt, v\u00E0 b\u1EA5m n\u00FAt M\u1EE9c t\u00F9y ch\u1EC9nh. Ki\u1EC3m h\u1ED9p \u201CScript c\u00E1c \u0111i\u1EC1u khi\u1EC3n ActiveX \u0111\u01B0\u1EE3c \u0111\u00E1nh d\u1EA5u l\u00E0 an to\u00E0n\u201D.\n\nMathJax s\u1EBD kh\u00F4ng th\u1EC3 x\u1EED l\u00FD c\u00E1c ph\u01B0\u01A1ng tr\u00ECnh MathML.", UnknownNodeType: "Ki\u1EC3u n\u00FAt kh\u00F4ng r\u00F5: %1", UnexpectedTextNode: "N\u00FAt v\u0103n b\u1EA3n b\u1EA5t ng\u1EEB: %1", ErrorParsingMathML: "L\u1ED7i khi ph\u00E2n t\u00EDch MathML", ParsingError: "L\u1ED7i khi ph\u00E2n t\u00EDch MathML: %1", MathMLSingleElement: "MathML ph\u1EA3i ch\u1EC9 c\u00F3 m\u1ED9t ph\u1EA7n t\u1EED g\u1ED1c", MathMLRootElement: "Ph\u1EA7n t\u1EED g\u1ED1c c\u1EE7a MathML ph\u1EA3i l\u00E0 \u003Cmath\u003E, ch\u1EE9 kh\u00F4ng ph\u1EA3i %1" } }); MathJax.Ajax.loadComplete("[MathJax]/localization/vi/MathML.js");
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ /** * Expose `Emitter`. */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks['$' + event] = this._callbacks['$' + event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ function on() { this.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; if (0 == arguments.length) { this._callbacks = {}; return this; } var callbacks = this._callbacks['$' + event]; if (!callbacks) return this; if (1 == arguments.length) { delete this._callbacks['$' + event]; return this; } var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks['$' + event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks['$' + event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; },{}],2:[function(require,module,exports){ /*! * domready (c) Dustin Diaz 2012 - License MIT */ !function (name, definition) { if (typeof module != 'undefined') module.exports = definition() else if (typeof define == 'function' && typeof define.amd == 'object') {} else this[name] = definition() }('domready', function (ready) { var fns = [], fn, f = false , doc = document , testEl = doc.documentElement , hack = testEl.doScroll , domContentLoaded = 'DOMContentLoaded' , addEventListener = 'addEventListener' , onreadystatechange = 'onreadystatechange' , readyState = 'readyState' , loadedRgx = hack ? /^loaded|^c/ : /^loaded|c/ , loaded = loadedRgx.test(doc[readyState]) function flush(f) { loaded = 1 while (f = fns.shift()) f() } doc[addEventListener] && doc[addEventListener](domContentLoaded, fn = function () { doc.removeEventListener(domContentLoaded, fn, f) flush() }, f) hack && doc.attachEvent(onreadystatechange, fn = function () { if (/^c/.test(doc[readyState])) { doc.detachEvent(onreadystatechange, fn) flush() } }) return (ready = hack ? function (fn) { self != top ? loaded ? fn() : fns.push(fn) : function () { try { testEl.doScroll('left') } catch (e) { return setTimeout(function() { ready(fn) }, 50) } fn() }() } : function (fn) { loaded ? fn() : fns.push(fn) }) }) },{}],3:[function(require,module,exports){ (function (global){ /*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */ ;(function () { var isLoader = typeof define === "function" && define.amd; var objectTypes = { "function": true, "object": true }; var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; var root = objectTypes[typeof window] && window || this, freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global; if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) { root = freeGlobal; } function runInContext(context, exports) { context || (context = root["Object"]()); exports || (exports = root["Object"]()); var Number = context["Number"] || root["Number"], String = context["String"] || root["String"], Object = context["Object"] || root["Object"], Date = context["Date"] || root["Date"], SyntaxError = context["SyntaxError"] || root["SyntaxError"], TypeError = context["TypeError"] || root["TypeError"], Math = context["Math"] || root["Math"], nativeJSON = context["JSON"] || root["JSON"]; if (typeof nativeJSON == "object" && nativeJSON) { exports.stringify = nativeJSON.stringify; exports.parse = nativeJSON.parse; } var objectProto = Object.prototype, getClass = objectProto.toString, isProperty, forEach, undef; var isExtended = new Date(-3509827334573292); try { isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 && isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708; } catch (exception) {} function has(name) { if (has[name] !== undef) { return has[name]; } var isSupported; if (name == "bug-string-char-index") { isSupported = "a"[0] != "a"; } else if (name == "json") { isSupported = has("json-stringify") && has("json-parse"); } else { var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}'; if (name == "json-stringify") { var stringify = exports.stringify, stringifySupported = typeof stringify == "function" && isExtended; if (stringifySupported) { (value = function () { return 1; }).toJSON = value; try { stringifySupported = stringify(0) === "0" && stringify(new Number()) === "0" && stringify(new String()) == '""' && stringify(getClass) === undef && stringify(undef) === undef && stringify() === undef && stringify(value) === "1" && stringify([value]) == "[1]" && stringify([undef]) == "[null]" && stringify(null) == "null" && stringify([undef, getClass, null]) == "[null,null,null]" && stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized && stringify(null, value) === "1" && stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" && stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' && stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' && stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' && stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"'; } catch (exception) { stringifySupported = false; } } isSupported = stringifySupported; } if (name == "json-parse") { var parse = exports.parse; if (typeof parse == "function") { try { if (parse("0") === 0 && !parse(false)) { value = parse(serialized); var parseSupported = value["a"].length == 5 && value["a"][0] === 1; if (parseSupported) { try { parseSupported = !parse('"\t"'); } catch (exception) {} if (parseSupported) { try { parseSupported = parse("01") !== 1; } catch (exception) {} } if (parseSupported) { try { parseSupported = parse("1.") !== 1; } catch (exception) {} } } } } catch (exception) { parseSupported = false; } } isSupported = parseSupported; } } return has[name] = !!isSupported; } if (!has("json")) { var functionClass = "[object Function]", dateClass = "[object Date]", numberClass = "[object Number]", stringClass = "[object String]", arrayClass = "[object Array]", booleanClass = "[object Boolean]"; var charIndexBuggy = has("bug-string-char-index"); if (!isExtended) { var floor = Math.floor; var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; var getDay = function (year, month) { return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400); }; } if (!(isProperty = objectProto.hasOwnProperty)) { isProperty = function (property) { var members = {}, constructor; if ((members.__proto__ = null, members.__proto__ = { "toString": 1 }, members).toString != getClass) { isProperty = function (property) { var original = this.__proto__, result = property in (this.__proto__ = null, this); this.__proto__ = original; return result; }; } else { constructor = members.constructor; isProperty = function (property) { var parent = (this.constructor || constructor).prototype; return property in this && !(property in parent && this[property] === parent[property]); }; } members = null; return isProperty.call(this, property); }; } forEach = function (object, callback) { var size = 0, Properties, members, property; (Properties = function () { this.valueOf = 0; }).prototype.valueOf = 0; members = new Properties(); for (property in members) { if (isProperty.call(members, property)) { size++; } } Properties = members = null; if (!size) { members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"]; forEach = function (object, callback) { var isFunction = getClass.call(object) == functionClass, property, length; var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty; for (property in object) { if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) { callback(property); } } for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property)); }; } else if (size == 2) { forEach = function (object, callback) { var members = {}, isFunction = getClass.call(object) == functionClass, property; for (property in object) { if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) { callback(property); } } }; } else { forEach = function (object, callback) { var isFunction = getClass.call(object) == functionClass, property, isConstructor; for (property in object) { if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) { callback(property); } } if (isConstructor || isProperty.call(object, (property = "constructor"))) { callback(property); } }; } return forEach(object, callback); }; if (!has("json-stringify")) { var Escapes = { 92: "\\\\", 34: '\\"', 8: "\\b", 12: "\\f", 10: "\\n", 13: "\\r", 9: "\\t" }; var leadingZeroes = "000000"; var toPaddedString = function (width, value) { return (leadingZeroes + (value || 0)).slice(-width); }; var unicodePrefix = "\\u00"; var quote = function (value) { var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10; var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value); for (; index < length; index++) { var charCode = value.charCodeAt(index); switch (charCode) { case 8: case 9: case 10: case 12: case 13: case 34: case 92: result += Escapes[charCode]; break; default: if (charCode < 32) { result += unicodePrefix + toPaddedString(2, charCode.toString(16)); break; } result += useCharIndex ? symbols[index] : value.charAt(index); } } return result + '"'; }; var serialize = function (property, object, callback, properties, whitespace, indentation, stack) { var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result; try { value = object[property]; } catch (exception) {} if (typeof value == "object" && value) { className = getClass.call(value); if (className == dateClass && !isProperty.call(value, "toJSON")) { if (value > -1 / 0 && value < 1 / 0) { if (getDay) { date = floor(value / 864e5); for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++); for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++); date = 1 + date - getDay(year, month); time = (value % 864e5 + 864e5) % 864e5; hours = floor(time / 36e5) % 24; minutes = floor(time / 6e4) % 60; seconds = floor(time / 1e3) % 60; milliseconds = time % 1e3; } else { year = value.getUTCFullYear(); month = value.getUTCMonth(); date = value.getUTCDate(); hours = value.getUTCHours(); minutes = value.getUTCMinutes(); seconds = value.getUTCSeconds(); milliseconds = value.getUTCMilliseconds(); } value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) + "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) + "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) + "." + toPaddedString(3, milliseconds) + "Z"; } else { value = null; } } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) { value = value.toJSON(property); } } if (callback) { value = callback.call(object, property, value); } if (value === null) { return "null"; } className = getClass.call(value); if (className == booleanClass) { return "" + value; } else if (className == numberClass) { return value > -1 / 0 && value < 1 / 0 ? "" + value : "null"; } else if (className == stringClass) { return quote("" + value); } if (typeof value == "object") { for (length = stack.length; length--;) { if (stack[length] === value) { throw TypeError(); } } stack.push(value); results = []; prefix = indentation; indentation += whitespace; if (className == arrayClass) { for (index = 0, length = value.length; index < length; index++) { element = serialize(index, value, callback, properties, whitespace, indentation, stack); results.push(element === undef ? "null" : element); } result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]"; } else { forEach(properties || value, function (property) { var element = serialize(property, value, callback, properties, whitespace, indentation, stack); if (element !== undef) { results.push(quote(property) + ":" + (whitespace ? " " : "") + element); } }); result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}"; } stack.pop(); return result; } }; exports.stringify = function (source, filter, width) { var whitespace, callback, properties, className; if (objectTypes[typeof filter] && filter) { if ((className = getClass.call(filter)) == functionClass) { callback = filter; } else if (className == arrayClass) { properties = {}; for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1)); } } if (width) { if ((className = getClass.call(width)) == numberClass) { if ((width -= width % 1) > 0) { for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " "); } } else if (className == stringClass) { whitespace = width.length <= 10 ? width : width.slice(0, 10); } } return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []); }; } if (!has("json-parse")) { var fromCharCode = String.fromCharCode; var Unescapes = { 92: "\\", 34: '"', 47: "/", 98: "\b", 116: "\t", 110: "\n", 102: "\f", 114: "\r" }; var Index, Source; var abort = function () { Index = Source = null; throw SyntaxError(); }; var lex = function () { var source = Source, length = source.length, value, begin, position, isSigned, charCode; while (Index < length) { charCode = source.charCodeAt(Index); switch (charCode) { case 9: case 10: case 13: case 32: Index++; break; case 123: case 125: case 91: case 93: case 58: case 44: value = charIndexBuggy ? source.charAt(Index) : source[Index]; Index++; return value; case 34: for (value = "@", Index++; Index < length;) { charCode = source.charCodeAt(Index); if (charCode < 32) { abort(); } else if (charCode == 92) { charCode = source.charCodeAt(++Index); switch (charCode) { case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114: value += Unescapes[charCode]; Index++; break; case 117: begin = ++Index; for (position = Index + 4; Index < position; Index++) { charCode = source.charCodeAt(Index); if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) { abort(); } } value += fromCharCode("0x" + source.slice(begin, Index)); break; default: abort(); } } else { if (charCode == 34) { break; } charCode = source.charCodeAt(Index); begin = Index; while (charCode >= 32 && charCode != 92 && charCode != 34) { charCode = source.charCodeAt(++Index); } value += source.slice(begin, Index); } } if (source.charCodeAt(Index) == 34) { Index++; return value; } abort(); default: begin = Index; if (charCode == 45) { isSigned = true; charCode = source.charCodeAt(++Index); } if (charCode >= 48 && charCode <= 57) { if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) { abort(); } isSigned = false; for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++); if (source.charCodeAt(Index) == 46) { position = ++Index; for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); if (position == Index) { abort(); } Index = position; } charCode = source.charCodeAt(Index); if (charCode == 101 || charCode == 69) { charCode = source.charCodeAt(++Index); if (charCode == 43 || charCode == 45) { Index++; } for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); if (position == Index) { abort(); } Index = position; } return +source.slice(begin, Index); } if (isSigned) { abort(); } if (source.slice(Index, Index + 4) == "true") { Index += 4; return true; } else if (source.slice(Index, Index + 5) == "false") { Index += 5; return false; } else if (source.slice(Index, Index + 4) == "null") { Index += 4; return null; } abort(); } } return "$"; }; var get = function (value) { var results, hasMembers; if (value == "$") { abort(); } if (typeof value == "string") { if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") { return value.slice(1); } if (value == "[") { results = []; for (;; hasMembers || (hasMembers = true)) { value = lex(); if (value == "]") { break; } if (hasMembers) { if (value == ",") { value = lex(); if (value == "]") { abort(); } } else { abort(); } } if (value == ",") { abort(); } results.push(get(value)); } return results; } else if (value == "{") { results = {}; for (;; hasMembers || (hasMembers = true)) { value = lex(); if (value == "}") { break; } if (hasMembers) { if (value == ",") { value = lex(); if (value == "}") { abort(); } } else { abort(); } } if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") { abort(); } results[value.slice(1)] = get(lex()); } return results; } abort(); } return value; }; var update = function (source, property, callback) { var element = walk(source, property, callback); if (element === undef) { delete source[property]; } else { source[property] = element; } }; var walk = function (source, property, callback) { var value = source[property], length; if (typeof value == "object" && value) { if (getClass.call(value) == arrayClass) { for (length = value.length; length--;) { update(value, length, callback); } } else { forEach(value, function (property) { update(value, property, callback); }); } } return callback.call(source, property, value); }; exports.parse = function (source, callback) { var result, value; Index = 0; Source = "" + source; result = get(lex()); if (lex() != "$") { abort(); } Index = Source = null; return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result; }; } } exports["runInContext"] = runInContext; return exports; } if (freeExports && !isLoader) { runInContext(root, freeExports); } else { var nativeJSON = root.JSON, previousJSON = root["JSON3"], isRestored = false; var JSON3 = runInContext(root, (root["JSON3"] = { "noConflict": function () { if (!isRestored) { isRestored = true; root.JSON = nativeJSON; root["JSON3"] = previousJSON; nativeJSON = previousJSON = null; } return JSON3; } })); root.JSON = { "parse": JSON3.parse, "stringify": JSON3.stringify }; } if (false) { (function(){ return JSON3; }); } }).call(this); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],4:[function(require,module,exports){ /** * Reduce `arr` with `fn`. * * @param {Array} arr * @param {Function} fn * @param {Mixed} initial * * TODO: combatible error handling? */ module.exports = function(arr, fn, initial){ var idx = 0; var len = arr.length; var curr = arguments.length == 3 ? initial : arr[idx++]; while (idx < len) { curr = fn.call(null, curr, arr[idx], ++idx, arr); } return curr; }; },{}],5:[function(require,module,exports){ /** * Copyright (c) 2011-2014 Felix Gnass * Licensed under the MIT license * http://spin.js.org/ * * Example: var opts = { lines: 12 , length: 7 , width: 5 , radius: 10 , scale: 1.0 , corners: 1 , color: '#000' , opacity: 1/4 , rotate: 0 , direction: 1 , speed: 1 , trail: 100 , fps: 20 , zIndex: 2e9 , className: 'spinner' , top: '50%' , left: '50%' , shadow: false , hwaccel: false , position: 'absolute' } var target = document.getElementById('foo') var spinner = new Spinner(opts).spin(target) */ ;(function (root, factory) { /* CommonJS */ if (typeof module == 'object' && module.exports) module.exports = factory() /* AMD module */ else if (typeof define == 'function' && define.amd) {} /* Browser global */ else root.Spinner = factory() }(this, function () { "use strict" var prefixes = ['webkit', 'Moz', 'ms', 'O'] /* Vendor prefixes */ , animations = {} /* Animation rules keyed by their name */ , useCssAnimations /* Whether to use CSS animations or setTimeout */ , sheet /* A stylesheet to hold the @keyframe or VML rules. */ /** * Utility function to create elements. If no tag name is given, * a DIV is created. Optionally properties can be passed. */ function createEl (tag, prop) { var el = document.createElement(tag || 'div') , n for (n in prop) el[n] = prop[n] return el } /** * Appends children and returns the parent. */ function ins (parent /* child1, child2, ...*/) { for (var i = 1, n = arguments.length; i < n; i++) { parent.appendChild(arguments[i]) } return parent } /** * Creates an opacity keyframe animation rule and returns its name. * Since most mobile Webkits have timing issues with animation-delay, * we create separate rules for each line/segment. */ function addAnimation (alpha, trail, i, lines) { var name = ['opacity', trail, ~~(alpha * 100), i, lines].join('-') , start = 0.01 + i/lines * 100 , z = Math.max(1 - (1-alpha) / trail * (100-start), alpha) , prefix = useCssAnimations.substring(0, useCssAnimations.indexOf('Animation')).toLowerCase() , pre = prefix && '-' + prefix + '-' || '' if (!animations[name]) { sheet.insertRule( '@' + pre + 'keyframes ' + name + '{' + '0%{opacity:' + z + '}' + start + '%{opacity:' + alpha + '}' + (start+0.01) + '%{opacity:1}' + (start+trail) % 100 + '%{opacity:' + alpha + '}' + '100%{opacity:' + z + '}' + '}', sheet.cssRules.length) animations[name] = 1 } return name } /** * Tries various vendor prefixes and returns the first supported property. */ function vendor (el, prop) { var s = el.style , pp , i prop = prop.charAt(0).toUpperCase() + prop.slice(1) if (s[prop] !== undefined) return prop for (i = 0; i < prefixes.length; i++) { pp = prefixes[i]+prop if (s[pp] !== undefined) return pp } } /** * Sets multiple style properties at once. */ function css (el, prop) { for (var n in prop) { el.style[vendor(el, n) || n] = prop[n] } return el } /** * Fills in default values. */ function merge (obj) { for (var i = 1; i < arguments.length; i++) { var def = arguments[i] for (var n in def) { if (obj[n] === undefined) obj[n] = def[n] } } return obj } /** * Returns the line color from the given string or array. */ function getColor (color, idx) { return typeof color == 'string' ? color : color[idx % color.length] } var defaults = { lines: 12 , length: 7 , width: 5 , radius: 10 , scale: 1.0 , corners: 1 , color: '#000' , opacity: 1/4 , rotate: 0 , direction: 1 , speed: 1 , trail: 100 , fps: 20 , zIndex: 2e9 , className: 'spinner' , top: '50%' , left: '50%' , shadow: false , hwaccel: false , position: 'absolute' } /** The constructor */ function Spinner (o) { this.opts = merge(o || {}, Spinner.defaults, defaults) } Spinner.defaults = {} merge(Spinner.prototype, { /** * Adds the spinner to the given target element. If this instance is already * spinning, it is automatically removed from its previous target b calling * stop() internally. */ spin: function (target) { this.stop() var self = this , o = self.opts , el = self.el = createEl(null, {className: o.className}) css(el, { position: o.position , width: 0 , zIndex: o.zIndex , left: o.left , top: o.top }) if (target) { target.insertBefore(el, target.firstChild || null) } el.setAttribute('role', 'progressbar') self.lines(el, self.opts) if (!useCssAnimations) { var i = 0 , start = (o.lines - 1) * (1 - o.direction) / 2 , alpha , fps = o.fps , f = fps / o.speed , ostep = (1 - o.opacity) / (f * o.trail / 100) , astep = f / o.lines ;(function anim () { i++ for (var j = 0; j < o.lines; j++) { alpha = Math.max(1 - (i + (o.lines - j) * astep) % f * ostep, o.opacity) self.opacity(el, j * o.direction + start, alpha, o) } self.timeout = self.el && setTimeout(anim, ~~(1000 / fps)) })() } return self } /** * Stops and removes the Spinner. */ , stop: function () { var el = this.el if (el) { clearTimeout(this.timeout) if (el.parentNode) el.parentNode.removeChild(el) this.el = undefined } return this } /** * Internal method that draws the individual lines. Will be overwritten * in VML fallback mode below. */ , lines: function (el, o) { var i = 0 , start = (o.lines - 1) * (1 - o.direction) / 2 , seg function fill (color, shadow) { return css(createEl(), { position: 'absolute' , width: o.scale * (o.length + o.width) + 'px' , height: o.scale * o.width + 'px' , background: color , boxShadow: shadow , transformOrigin: 'left' , transform: 'rotate(' + ~~(360/o.lines*i + o.rotate) + 'deg) translate(' + o.scale*o.radius + 'px' + ',0)' , borderRadius: (o.corners * o.scale * o.width >> 1) + 'px' }) } for (; i < o.lines; i++) { seg = css(createEl(), { position: 'absolute' , top: 1 + ~(o.scale * o.width / 2) + 'px' , transform: o.hwaccel ? 'translate3d(0,0,0)' : '' , opacity: o.opacity , animation: useCssAnimations && addAnimation(o.opacity, o.trail, start + i * o.direction, o.lines) + ' ' + 1 / o.speed + 's linear infinite' }) if (o.shadow) ins(seg, css(fill('#000', '0 0 4px #000'), {top: '2px'})) ins(el, ins(seg, fill(getColor(o.color, i), '0 0 1px rgba(0,0,0,.1)'))) } return el } /** * Internal method that adjusts the opacity of a single line. * Will be overwritten in VML fallback mode below. */ , opacity: function (el, i, val) { if (i < el.childNodes.length) el.childNodes[i].style.opacity = val } }) function initVML () { /* Utility function to create a VML tag */ function vml (tag, attr) { return createEl('<' + tag + ' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">', attr) } sheet.addRule('.spin-vml', 'behavior:url(#default#VML)') Spinner.prototype.lines = function (el, o) { var r = o.scale * (o.length + o.width) , s = o.scale * 2 * r function grp () { return css( vml('group', { coordsize: s + ' ' + s , coordorigin: -r + ' ' + -r }) , { width: s, height: s } ) } var margin = -(o.width + o.length) * o.scale * 2 + 'px' , g = css(grp(), {position: 'absolute', top: margin, left: margin}) , i function seg (i, dx, filter) { ins( g , ins( css(grp(), {rotation: 360 / o.lines * i + 'deg', left: ~~dx}) , ins( css( vml('roundrect', {arcsize: o.corners}) , { width: r , height: o.scale * o.width , left: o.scale * o.radius , top: -o.scale * o.width >> 1 , filter: filter } ) , vml('fill', {color: getColor(o.color, i), opacity: o.opacity}) , vml('stroke', {opacity: 0}) ) ) ) } if (o.shadow) for (i = 1; i <= o.lines; i++) { seg(i, -2, 'progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)') } for (i = 1; i <= o.lines; i++) seg(i) return ins(el, g) } Spinner.prototype.opacity = function (el, i, val, o) { var c = el.firstChild o = o.shadow && o.lines || 0 if (c && i + o < c.childNodes.length) { c = c.childNodes[i + o]; c = c && c.firstChild; c = c && c.firstChild if (c) c.opacity = val } } } if (typeof document !== 'undefined') { sheet = (function () { var el = createEl('style', {type : 'text/css'}) ins(document.getElementsByTagName('head')[0], el) return el.sheet || el.styleSheet }()) var probe = css(createEl('group'), {behavior: 'url(#default#VML)'}) if (!vendor(probe, 'transform') && probe.adj) initVML() else useCssAnimations = vendor(probe, 'animation') } return Spinner })); },{}],6:[function(require,module,exports){ /** * Module dependencies. */ var Emitter = require('emitter'); var reduce = require('reduce'); var requestBase = require('./request-base'); var isObject = require('./is-object'); /** * Root reference for iframes. */ var root; if (typeof window !== 'undefined') { root = window; } else if (typeof self !== 'undefined') { root = self; } else { root = this; } /** * Noop. */ function noop(){}; /** * Check if `obj` is a host object, * we don't want to serialize these :) * * TODO: future proof, move to compoent land * * @param {Object} obj * @return {Boolean} * @api private */ function isHost(obj) { var str = {}.toString.call(obj); switch (str) { case '[object File]': case '[object Blob]': case '[object FormData]': return true; default: return false; } } /** * Expose `request`. */ var request = module.exports = require('./request').bind(null, Request); /** * Determine XHR. */ request.getXHR = function () { if (root.XMLHttpRequest && (!root.location || 'file:' != root.location.protocol || !root.ActiveXObject)) { return new XMLHttpRequest; } else { try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {} try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {} try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {} try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {} } return false; }; /** * Removes leading and trailing whitespace, added to support IE. * * @param {String} s * @return {String} * @api private */ var trim = ''.trim ? function(s) { return s.trim(); } : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); }; /** * Serialize the given `obj`. * * @param {Object} obj * @return {String} * @api private */ function serialize(obj) { if (!isObject(obj)) return obj; var pairs = []; for (var key in obj) { if (null != obj[key]) { pushEncodedKeyValuePair(pairs, key, obj[key]); } } return pairs.join('&'); } /** * Helps 'serialize' with serializing arrays. * Mutates the pairs array. * * @param {Array} pairs * @param {String} key * @param {Mixed} val */ function pushEncodedKeyValuePair(pairs, key, val) { if (Array.isArray(val)) { return val.forEach(function(v) { pushEncodedKeyValuePair(pairs, key, v); }); } pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(val)); } /** * Expose serialization method. */ request.serializeObject = serialize; /** * Parse the given x-www-form-urlencoded `str`. * * @param {String} str * @return {Object} * @api private */ function parseString(str) { var obj = {}; var pairs = str.split('&'); var parts; var pair; for (var i = 0, len = pairs.length; i < len; ++i) { pair = pairs[i]; parts = pair.split('='); obj[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]); } return obj; } /** * Expose parser. */ request.parseString = parseString; /** * Default MIME type map. * * superagent.types.xml = 'application/xml'; * */ request.types = { html: 'text/html', json: 'application/json', xml: 'application/xml', urlencoded: 'application/x-www-form-urlencoded', 'form': 'application/x-www-form-urlencoded', 'form-data': 'application/x-www-form-urlencoded' }; /** * Default serialization map. * * superagent.serialize['application/xml'] = function(obj){ * return 'generated xml here'; * }; * */ request.serialize = { 'application/x-www-form-urlencoded': serialize, 'application/json': JSON.stringify }; /** * Default parsers. * * superagent.parse['application/xml'] = function(str){ * return { object parsed from str }; * }; * */ request.parse = { 'application/x-www-form-urlencoded': parseString, 'application/json': JSON.parse }; /** * Parse the given header `str` into * an object containing the mapped fields. * * @param {String} str * @return {Object} * @api private */ function parseHeader(str) { var lines = str.split(/\r?\n/); var fields = {}; var index; var line; var field; var val; lines.pop(); for (var i = 0, len = lines.length; i < len; ++i) { line = lines[i]; index = line.indexOf(':'); field = line.slice(0, index).toLowerCase(); val = trim(line.slice(index + 1)); fields[field] = val; } return fields; } /** * Check if `mime` is json or has +json structured syntax suffix. * * @param {String} mime * @return {Boolean} * @api private */ function isJSON(mime) { return /[\/+]json\b/.test(mime); } /** * Return the mime type for the given `str`. * * @param {String} str * @return {String} * @api private */ function type(str){ return str.split(/ *; */).shift(); }; /** * Return header field parameters. * * @param {String} str * @return {Object} * @api private */ function params(str){ return reduce(str.split(/ *; */), function(obj, str){ var parts = str.split(/ *= */) , key = parts.shift() , val = parts.shift(); if (key && val) obj[key] = val; return obj; }, {}); }; /** * Initialize a new `Response` with the given `xhr`. * * - set flags (.ok, .error, etc) * - parse header * * Examples: * * Aliasing `superagent` as `request` is nice: * * request = superagent; * * We can use the promise-like API, or pass callbacks: * * request.get('/').end(function(res){}); * request.get('/', function(res){}); * * Sending data can be chained: * * request * .post('/user') * .send({ name: 'tj' }) * .end(function(res){}); * * Or passed to `.send()`: * * request * .post('/user') * .send({ name: 'tj' }, function(res){}); * * Or passed to `.post()`: * * request * .post('/user', { name: 'tj' }) * .end(function(res){}); * * Or further reduced to a single call for simple cases: * * request * .post('/user', { name: 'tj' }, function(res){}); * * @param {XMLHTTPRequest} xhr * @param {Object} options * @api private */ function Response(req, options) { options = options || {}; this.req = req; this.xhr = this.req.xhr; this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined') ? this.xhr.responseText : null; this.statusText = this.req.xhr.statusText; this.setStatusProperties(this.xhr.status); this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders()); this.header['content-type'] = this.xhr.getResponseHeader('content-type'); this.setHeaderProperties(this.header); this.body = this.req.method != 'HEAD' ? this.parseBody(this.text ? this.text : this.xhr.response) : null; } /** * Get case-insensitive `field` value. * * @param {String} field * @return {String} * @api public */ Response.prototype.get = function(field){ return this.header[field.toLowerCase()]; }; /** * Set header related properties: * * - `.type` the content type without params * * A response of "Content-Type: text/plain; charset=utf-8" * will provide you with a `.type` of "text/plain". * * @param {Object} header * @api private */ Response.prototype.setHeaderProperties = function(header){ var ct = this.header['content-type'] || ''; this.type = type(ct); var obj = params(ct); for (var key in obj) this[key] = obj[key]; }; /** * Parse the given body `str`. * * Used for auto-parsing of bodies. Parsers * are defined on the `superagent.parse` object. * * @param {String} str * @return {Mixed} * @api private */ Response.prototype.parseBody = function(str){ var parse = request.parse[this.type]; if (!parse && isJSON(this.type)) { parse = request.parse['application/json']; } return parse && str && (str.length || str instanceof Object) ? parse(str) : null; }; /** * Set flags such as `.ok` based on `status`. * * For example a 2xx response will give you a `.ok` of __true__ * whereas 5xx will be __false__ and `.error` will be __true__. The * `.clientError` and `.serverError` are also available to be more * specific, and `.statusType` is the class of error ranging from 1..5 * sometimes useful for mapping respond colors etc. * * "sugar" properties are also defined for common cases. Currently providing: * * - .noContent * - .badRequest * - .unauthorized * - .notAcceptable * - .notFound * * @param {Number} status * @api private */ Response.prototype.setStatusProperties = function(status){ if (status === 1223) { status = 204; } var type = status / 100 | 0; this.status = this.statusCode = status; this.statusType = type; this.info = 1 == type; this.ok = 2 == type; this.clientError = 4 == type; this.serverError = 5 == type; this.error = (4 == type || 5 == type) ? this.toError() : false; this.accepted = 202 == status; this.noContent = 204 == status; this.badRequest = 400 == status; this.unauthorized = 401 == status; this.notAcceptable = 406 == status; this.notFound = 404 == status; this.forbidden = 403 == status; }; /** * Return an `Error` representative of this response. * * @return {Error} * @api public */ Response.prototype.toError = function(){ var req = this.req; var method = req.method; var url = req.url; var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')'; var err = new Error(msg); err.status = this.status; err.method = method; err.url = url; return err; }; /** * Expose `Response`. */ request.Response = Response; /** * Initialize a new `Request` with the given `method` and `url`. * * @param {String} method * @param {String} url * @api public */ function Request(method, url) { var self = this; this._query = this._query || []; this.method = method; this.url = url; this.header = {}; this._header = {}; this.on('end', function(){ var err = null; var res = null; try { res = new Response(self); } catch(e) { err = new Error('Parser is unable to parse the response'); err.parse = true; err.original = e; err.rawResponse = self.xhr && self.xhr.responseText ? self.xhr.responseText : null; err.statusCode = self.xhr && self.xhr.status ? self.xhr.status : null; return self.callback(err); } self.emit('response', res); if (err) { return self.callback(err, res); } if (res.status >= 200 && res.status < 300) { return self.callback(err, res); } var new_err = new Error(res.statusText || 'Unsuccessful HTTP response'); new_err.original = err; new_err.response = res; new_err.status = res.status; self.callback(new_err, res); }); } /** * Mixin `Emitter` and `requestBase`. */ Emitter(Request.prototype); for (var key in requestBase) { Request.prototype[key] = requestBase[key]; } /** * Abort the request, and clear potential timeout. * * @return {Request} * @api public */ Request.prototype.abort = function(){ if (this.aborted) return; this.aborted = true; this.xhr.abort(); this.clearTimeout(); this.emit('abort'); return this; }; /** * Set Content-Type to `type`, mapping values from `request.types`. * * Examples: * * superagent.types.xml = 'application/xml'; * * request.post('/') * .type('xml') * .send(xmlstring) * .end(callback); * * request.post('/') * .type('application/xml') * .send(xmlstring) * .end(callback); * * @param {String} type * @return {Request} for chaining * @api public */ Request.prototype.type = function(type){ this.set('Content-Type', request.types[type] || type); return this; }; /** * Set responseType to `val`. Presently valid responseTypes are 'blob' and * 'arraybuffer'. * * Examples: * * req.get('/') * .responseType('blob') * .end(callback); * * @param {String} val * @return {Request} for chaining * @api public */ Request.prototype.responseType = function(val){ this._responseType = val; return this; }; /** * Set Accept to `type`, mapping values from `request.types`. * * Examples: * * superagent.types.json = 'application/json'; * * request.get('/agent') * .accept('json') * .end(callback); * * request.get('/agent') * .accept('application/json') * .end(callback); * * @param {String} accept * @return {Request} for chaining * @api public */ Request.prototype.accept = function(type){ this.set('Accept', request.types[type] || type); return this; }; /** * Set Authorization field value with `user` and `pass`. * * @param {String} user * @param {String} pass * @param {Object} options with 'type' property 'auto' or 'basic' (default 'basic') * @return {Request} for chaining * @api public */ Request.prototype.auth = function(user, pass, options){ if (!options) { options = { type: 'basic' } } switch (options.type) { case 'basic': var str = btoa(user + ':' + pass); this.set('Authorization', 'Basic ' + str); break; case 'auto': this.username = user; this.password = pass; break; } return this; }; /** * Add query-string `val`. * * Examples: * * request.get('/shoes') * .query('size=10') * .query({ color: 'blue' }) * * @param {Object|String} val * @return {Request} for chaining * @api public */ Request.prototype.query = function(val){ if ('string' != typeof val) val = serialize(val); if (val) this._query.push(val); return this; }; /** * Queue the given `file` as an attachment to the specified `field`, * with optional `filename`. * * ``` js * request.post('/upload') * .attach(new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"})) * .end(callback); * ``` * * @param {String} field * @param {Blob|File} file * @param {String} filename * @return {Request} for chaining * @api public */ Request.prototype.attach = function(field, file, filename){ this._getFormData().append(field, file, filename || file.name); return this; }; Request.prototype._getFormData = function(){ if (!this._formData) { this._formData = new root.FormData(); } return this._formData; }; /** * Send `data` as the request body, defaulting the `.type()` to "json" when * an object is given. * * Examples: * * * request.post('/user') * .type('json') * .send('{"name":"tj"}') * .end(callback) * * * request.post('/user') * .send({ name: 'tj' }) * .end(callback) * * * request.post('/user') * .type('form') * .send('name=tj') * .end(callback) * * * request.post('/user') * .type('form') * .send({ name: 'tj' }) * .end(callback) * * * request.post('/user') * .send('name=tobi') * .send('species=ferret') * .end(callback) * * @param {String|Object} data * @return {Request} for chaining * @api public */ Request.prototype.send = function(data){ var obj = isObject(data); var type = this._header['content-type']; if (obj && isObject(this._data)) { for (var key in data) { this._data[key] = data[key]; } } else if ('string' == typeof data) { if (!type) this.type('form'); type = this._header['content-type']; if ('application/x-www-form-urlencoded' == type) { this._data = this._data ? this._data + '&' + data : data; } else { this._data = (this._data || '') + data; } } else { this._data = data; } if (!obj || isHost(data)) return this; if (!type) this.type('json'); return this; }; /** * @deprecated */ Response.prototype.parse = function serialize(fn){ if (root.console) { console.warn("Client-side parse() method has been renamed to serialize(). This method is not compatible with superagent v2.0"); } this.serialize(fn); return this; }; Response.prototype.serialize = function serialize(fn){ this._parser = fn; return this; }; /** * Invoke the callback with `err` and `res` * and handle arity check. * * @param {Error} err * @param {Response} res * @api private */ Request.prototype.callback = function(err, res){ var fn = this._callback; this.clearTimeout(); fn(err, res); }; /** * Invoke callback with x-domain error. * * @api private */ Request.prototype.crossDomainError = function(){ var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.'); err.crossDomain = true; err.status = this.status; err.method = this.method; err.url = this.url; this.callback(err); }; /** * Invoke callback with timeout error. * * @api private */ Request.prototype.timeoutError = function(){ var timeout = this._timeout; var err = new Error('timeout of ' + timeout + 'ms exceeded'); err.timeout = timeout; this.callback(err); }; /** * Enable transmission of cookies with x-domain requests. * * Note that for this to work the origin must not be * using "Access-Control-Allow-Origin" with a wildcard, * and also must set "Access-Control-Allow-Credentials" * to "true". * * @api public */ Request.prototype.withCredentials = function(){ this._withCredentials = true; return this; }; /** * Initiate request, invoking callback `fn(res)` * with an instanceof `Response`. * * @param {Function} fn * @return {Request} for chaining * @api public */ Request.prototype.end = function(fn){ var self = this; var xhr = this.xhr = request.getXHR(); var query = this._query.join('&'); var timeout = this._timeout; var data = this._formData || this._data; this._callback = fn || noop; xhr.onreadystatechange = function(){ if (4 != xhr.readyState) return; var status; try { status = xhr.status } catch(e) { status = 0; } if (0 == status) { if (self.timedout) return self.timeoutError(); if (self.aborted) return; return self.crossDomainError(); } self.emit('end'); }; var handleProgress = function(e){ if (e.total > 0) { e.percent = e.loaded / e.total * 100; } e.direction = 'download'; self.emit('progress', e); }; if (this.hasListeners('progress')) { xhr.onprogress = handleProgress; } try { if (xhr.upload && this.hasListeners('progress')) { xhr.upload.onprogress = handleProgress; } } catch(e) { } if (timeout && !this._timer) { this._timer = setTimeout(function(){ self.timedout = true; self.abort(); }, timeout); } if (query) { query = request.serializeObject(query); this.url += ~this.url.indexOf('?') ? '&' + query : '?' + query; } if (this.username && this.password) { xhr.open(this.method, this.url, true, this.username, this.password); } else { xhr.open(this.method, this.url, true); } if (this._withCredentials) xhr.withCredentials = true; if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !isHost(data)) { var contentType = this._header['content-type']; var serialize = this._parser || request.serialize[contentType ? contentType.split(';')[0] : '']; if (!serialize && isJSON(contentType)) serialize = request.serialize['application/json']; if (serialize) data = serialize(data); } for (var field in this.header) { if (null == this.header[field]) continue; xhr.setRequestHeader(field, this.header[field]); } if (this._responseType) { xhr.responseType = this._responseType; } this.emit('request', this); xhr.send(typeof data !== 'undefined' ? data : null); return this; }; /** * Expose `Request`. */ request.Request = Request; /** * GET `url` with optional callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} data or fn * @param {Function} fn * @return {Request} * @api public */ request.get = function(url, data, fn){ var req = request('GET', url); if ('function' == typeof data) fn = data, data = null; if (data) req.query(data); if (fn) req.end(fn); return req; }; /** * HEAD `url` with optional callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} data or fn * @param {Function} fn * @return {Request} * @api public */ request.head = function(url, data, fn){ var req = request('HEAD', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * DELETE `url` with optional callback `fn(res)`. * * @param {String} url * @param {Function} fn * @return {Request} * @api public */ function del(url, fn){ var req = request('DELETE', url); if (fn) req.end(fn); return req; }; request['del'] = del; request['delete'] = del; /** * PATCH `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed} data * @param {Function} fn * @return {Request} * @api public */ request.patch = function(url, data, fn){ var req = request('PATCH', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * POST `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed} data * @param {Function} fn * @return {Request} * @api public */ request.post = function(url, data, fn){ var req = request('POST', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * PUT `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} data or fn * @param {Function} fn * @return {Request} * @api public */ request.put = function(url, data, fn){ var req = request('PUT', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; },{"./is-object":7,"./request":9,"./request-base":8,"emitter":1,"reduce":4}],7:[function(require,module,exports){ /** * Check if `obj` is an object. * * @param {Object} obj * @return {Boolean} * @api private */ function isObject(obj) { return null != obj && 'object' == typeof obj; } module.exports = isObject; },{}],8:[function(require,module,exports){ /** * Module of mixed-in functions shared between node and client code */ var isObject = require('./is-object'); /** * Clear previous timeout. * * @return {Request} for chaining * @api public */ exports.clearTimeout = function _clearTimeout(){ this._timeout = 0; clearTimeout(this._timer); return this; }; /** * Force given parser * * Sets the body parser no matter type. * * @param {Function} * @api public */ exports.parse = function parse(fn){ this._parser = fn; return this; }; /** * Set timeout to `ms`. * * @param {Number} ms * @return {Request} for chaining * @api public */ exports.timeout = function timeout(ms){ this._timeout = ms; return this; }; /** * Faux promise support * * @param {Function} fulfill * @param {Function} reject * @return {Request} */ exports.then = function then(fulfill, reject) { return this.end(function(err, res) { err ? reject(err) : fulfill(res); }); } /** * Allow for extension */ exports.use = function use(fn) { fn(this); return this; } /** * Get request header `field`. * Case-insensitive. * * @param {String} field * @return {String} * @api public */ exports.get = function(field){ return this._header[field.toLowerCase()]; }; /** * Get case-insensitive header `field` value. * This is a deprecated internal API. Use `.get(field)` instead. * * (getHeader is no longer used internally by the superagent code base) * * @param {String} field * @return {String} * @api private * @deprecated */ exports.getHeader = exports.get; /** * Set header `field` to `val`, or multiple fields with one object. * Case-insensitive. * * Examples: * * req.get('/') * .set('Accept', 'application/json') * .set('X-API-Key', 'foobar') * .end(callback); * * req.get('/') * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) * .end(callback); * * @param {String|Object} field * @param {String} val * @return {Request} for chaining * @api public */ exports.set = function(field, val){ if (isObject(field)) { for (var key in field) { this.set(key, field[key]); } return this; } this._header[field.toLowerCase()] = val; this.header[field] = val; return this; }; /** * Remove header `field`. * Case-insensitive. * * Example: * * req.get('/') * .unset('User-Agent') * .end(callback); * * @param {String} field */ exports.unset = function(field){ delete this._header[field.toLowerCase()]; delete this.header[field]; return this; }; /** * Write the field `name` and `val` for "multipart/form-data" * request bodies. * * ``` js * request.post('/upload') * .field('foo', 'bar') * .end(callback); * ``` * * @param {String} name * @param {String|Blob|File|Buffer|fs.ReadStream} val * @return {Request} for chaining * @api public */ exports.field = function(name, val) { this._getFormData().append(name, val); return this; }; },{"./is-object":7}],9:[function(require,module,exports){ /** * Issue a request: * * Examples: * * request('GET', '/users').end(callback) * request('/users').end(callback) * request('/users', callback) * * @param {String} method * @param {String|Function} url or callback * @return {Request} * @api public */ function request(RequestConstructor, method, url) { if ('function' == typeof url) { return new RequestConstructor('GET', method).end(url); } if (2 == arguments.length) { return new RequestConstructor('GET', method); } return new RequestConstructor(method, url); } module.exports = request; },{}],10:[function(require,module,exports){ var Keen = require("./index"), each = require("./utils/each"); module.exports = function(){ var loaded = window['Keen'] || null, cached = window['_' + 'Keen'] || null, clients, ready; if (loaded && cached) { clients = cached['clients'] || {}, ready = cached['ready'] || []; each(clients, function(client, id){ each(Keen.prototype, function(method, key){ loaded.prototype[key] = method; }); each(["Query", "Request", "Dataset", "Dataviz"], function(name){ loaded[name] = (Keen[name]) ? Keen[name] : function(){}; }); if (client._config) { client.configure.call(client, client._config); } if (client._setGlobalProperties) { each(client._setGlobalProperties, function(fn){ client.setGlobalProperties.apply(client, fn); }); } if (client._addEvent) { each(client._addEvent, function(obj){ client.addEvent.apply(client, obj); }); } var callback = client._on || []; if (client._on) { each(client._on, function(obj){ client.on.apply(client, obj); }); client.trigger('ready'); } each(["_config", "_setGlobalProperties", "_addEvent", "_on"], function(name){ if (client[name]) { client[name] = undefined; try{ delete client[name]; } catch(e){} } }); }); each(ready, function(cb, i){ Keen.once("ready", cb); }); } window['_' + 'Keen'] = undefined; try { delete window['_' + 'Keen'] } catch(e) {} }; },{"./index":18,"./utils/each":31}],11:[function(require,module,exports){ module.exports = function(){ return "undefined" == typeof window ? "server" : "browser"; }; },{}],12:[function(require,module,exports){ var each = require('../utils/each'), json = require('../utils/json-shim'); module.exports = function(params){ var query = []; each(params, function(value, key){ if ('string' !== typeof value) { value = json.stringify(value); } query.push(key + '=' + encodeURIComponent(value)); }); return '?' + query.join('&'); }; },{"../utils/each":31,"../utils/json-shim":34}],13:[function(require,module,exports){ module.exports = function(){ return new Date().getTimezoneOffset() * -60; }; },{}],14:[function(require,module,exports){ module.exports = function(){ if ("undefined" !== typeof window) { if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) { return 2000; } } return 16000; }; },{}],15:[function(require,module,exports){ module.exports = function() { var root = "undefined" == typeof window ? this : window; if (root.XMLHttpRequest && ("file:" != root.location.protocol || !root.ActiveXObject)) { return new XMLHttpRequest; } else { try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} } return false; }; },{}],16:[function(require,module,exports){ module.exports = function(err, res, callback) { var cb = callback || function() {}; if (res && !res.ok) { var is_err = res.body && res.body.error_code; err = new Error(is_err ? res.body.message : 'Unknown error occurred'); err.code = is_err ? res.body.error_code : 'UnknownError'; } if (err) { cb(err, null); } else { cb(null, res.body); } return; }; },{}],17:[function(require,module,exports){ var superagent = require('superagent'); var each = require('../utils/each'), getXHR = require('./get-xhr-object'); module.exports = function(type, opts){ return function(request) { var __super__ = request.constructor.prototype.end; if ( typeof window === 'undefined' ) return; request.requestType = request.requestType || {}; request.requestType['type'] = type; request.requestType['options'] = request.requestType['options'] || { async: true, success: { responseText: '{ "created": true }', status: 201 }, error: { responseText: '{ "error_code": "ERROR", "message": "Request failed" }', status: 404 } }; if (opts) { if ( typeof opts.async === 'boolean' ) { request.requestType['options'].async = opts.async; } if ( opts.success ) { extend(request.requestType['options'].success, opts.success); } if ( opts.error ) { extend(request.requestType['options'].error, opts.error); } } request.end = function(fn){ var self = this, reqType = (this.requestType) ? this.requestType['type'] : 'xhr', query, timeout; if ( ('GET' !== self['method'] || reqType === 'xhr' ) && self.requestType['options'].async ) { __super__.call(self, fn); return; } query = self._query.join('&'); timeout = self._timeout; self._callback = fn || noop; if (timeout && !self._timer) { self._timer = setTimeout(function(){ abortRequest.call(self); }, timeout); } if (query) { query = superagent.serializeObject(query); self.url += ~self.url.indexOf('?') ? '&' + query : '?' + query; } self.emit('request', self); if ( !self.requestType['options'].async ) { sendXhrSync.call(self); } else if ( reqType === 'jsonp' ) { sendJsonp.call(self); } else if ( reqType === 'beacon' ) { sendBeacon.call(self); } return self; }; return request; }; }; function sendXhrSync(){ var xhr = getXHR(); if (xhr) { xhr.open('GET', this.url, false); xhr.send(null); } return this; } function sendJsonp(){ var self = this, timestamp = new Date().getTime(), script = document.createElement('script'), parent = document.getElementsByTagName('head')[0], callbackName = 'keenJSONPCallback', loaded = false; callbackName += timestamp; while (callbackName in window) { callbackName += 'a'; } window[callbackName] = function(response) { if (loaded === true) return; loaded = true; handleSuccess.call(self, response); cleanup(); }; script.src = self.url + '&jsonp=' + callbackName; parent.appendChild(script); script.onreadystatechange = function() { if (loaded === false && self.readyState === 'loaded') { loaded = true; handleError.call(self); cleanup(); } }; script.onerror = function() { if (loaded === false) { loaded = true; handleError.call(self); cleanup(); } }; function cleanup(){ window[callbackName] = undefined; try { delete window[callbackName]; } catch(e){} parent.removeChild(script); } } function sendBeacon(){ var self = this, img = document.createElement('img'), loaded = false; img.onload = function() { loaded = true; if ('naturalHeight' in this) { if (this.naturalHeight + this.naturalWidth === 0) { this.onerror(); return; } } else if (this.width + this.height === 0) { this.onerror(); return; } handleSuccess.call(self); }; img.onerror = function() { loaded = true; handleError.call(self); }; img.src = self.url + '&c=clv1'; } function handleSuccess(res){ var opts = this.requestType['options']['success'], response = ''; xhrShim.call(this, opts); if (res) { try { response = JSON.stringify(res); } catch(e) {} } else { response = opts['responseText']; } this.xhr.responseText = response; this.xhr.status = opts['status']; this.emit('end'); } function handleError(){ var opts = this.requestType['options']['error']; xhrShim.call(this, opts); this.xhr.responseText = opts['responseText']; this.xhr.status = opts['status']; this.emit('end'); } function abortRequest(){ this.aborted = true; this.clearTimeout(); this.emit('abort'); } function xhrShim(opts){ this.xhr = { getAllResponseHeaders: function(){ return ''; }, getResponseHeader: function(){ return 'application/json'; }, responseText: opts['responseText'], status: opts['status'] }; return this; } },{"../utils/each":31,"./get-xhr-object":15,"superagent":6}],18:[function(require,module,exports){ var root = 'undefined' !== typeof window ? window : this; var previous_Keen = root.Keen; var Emitter = require('./utils/emitter-shim'); function Keen(config) { this.configure(config || {}); Keen.trigger('client', this); } Keen.debug = false; Keen.enabled = true; Keen.loaded = true; Keen.version = '3.4.1'; Emitter(Keen); Emitter(Keen.prototype); Keen.prototype.configure = function(cfg){ var config = cfg || {}; if (config['host']) { config['host'].replace(/.*?:\/\//g, ''); } if (config.protocol && config.protocol === 'auto') { config['protocol'] = location.protocol.replace(/:/g, ''); } this.config = { projectId : config.projectId, writeKey : config.writeKey, readKey : config.readKey, masterKey : config.masterKey, requestType : config.requestType || 'jsonp', host : config['host'] || 'api.keen.io/3.0', protocol : config['protocol'] || 'https', globalProperties: null }; if (Keen.debug) { this.on('error', Keen.log); } this.trigger('ready'); }; Keen.prototype.projectId = function(str){ if (!arguments.length) return this.config.projectId; this.config.projectId = (str ? String(str) : null); return this; }; Keen.prototype.masterKey = function(str){ if (!arguments.length) return this.config.masterKey; this.config.masterKey = (str ? String(str) : null); return this; }; Keen.prototype.readKey = function(str){ if (!arguments.length) return this.config.readKey; this.config.readKey = (str ? String(str) : null); return this; }; Keen.prototype.writeKey = function(str){ if (!arguments.length) return this.config.writeKey; this.config.writeKey = (str ? String(str) : null); return this; }; Keen.prototype.url = function(path){ if (!this.projectId()) { this.trigger('error', 'Client is missing projectId property'); return; } return this.config.protocol + '://' + this.config.host + '/projects/' + this.projectId() + path; }; Keen.log = function(message) { if (Keen.debug && typeof console == 'object') { console.log('[Keen IO]', message); } }; Keen.noConflict = function(){ root.Keen = previous_Keen; return Keen; }; Keen.ready = function(fn){ if (Keen.loaded) { fn(); } else { Keen.once('ready', fn); } }; module.exports = Keen; },{"./utils/emitter-shim":32}],19:[function(require,module,exports){ var json = require('../utils/json-shim'); var request = require('superagent'); var Keen = require('../index'); var base64 = require('../utils/base64'), each = require('../utils/each'), getContext = require('../helpers/get-context'), getQueryString = require('../helpers/get-query-string'), getUrlMaxLength = require('../helpers/get-url-max-length'), getXHR = require('../helpers/get-xhr-object'), requestTypes = require('../helpers/superagent-request-types'), responseHandler = require('../helpers/superagent-handle-response'); module.exports = function(collection, payload, callback, async) { var self = this, urlBase = this.url('/events/' + encodeURIComponent(collection)), reqType = this.config.requestType, data = {}, cb = callback, isAsync, getUrl; isAsync = ('boolean' === typeof async) ? async : true; if (!Keen.enabled) { handleValidationError.call(self, 'Keen.enabled = false'); return; } if (!self.projectId()) { handleValidationError.call(self, 'Missing projectId property'); return; } if (!self.writeKey()) { handleValidationError.call(self, 'Missing writeKey property'); return; } if (!collection || typeof collection !== 'string') { handleValidationError.call(self, 'Collection name must be a string'); return; } if (self.config.globalProperties) { data = self.config.globalProperties(collection); } each(payload, function(value, key){ data[key] = value; }); if ( !getXHR() && 'xhr' === reqType ) { reqType = 'jsonp'; } if ( 'xhr' !== reqType || !isAsync ) { getUrl = prepareGetRequest.call(self, urlBase, data); } if ( getUrl && getContext() === 'browser' ) { request .get(getUrl) .use(requestTypes(reqType, { async: isAsync })) .end(handleResponse); } else if ( getXHR() || getContext() === 'server' ) { request .post(urlBase) .set('Content-Type', 'application/json') .set('Authorization', self.writeKey()) .send(data) .end(handleResponse); } else { self.trigger('error', 'Request not sent: URL length exceeds current browser limit, and XHR (POST) is not supported.'); } function handleResponse(err, res){ responseHandler(err, res, cb); cb = callback = null; } function handleValidationError(msg){ var err = 'Event not recorded: ' + msg; self.trigger('error', err); if (cb) { cb.call(self, err, null); cb = callback = null; } } return; }; function prepareGetRequest(url, data){ url += getQueryString({ api_key : this.writeKey(), data : base64.encode( json.stringify(data) ), modified : new Date().getTime() }); return ( url.length < getUrlMaxLength() ) ? url : false; } },{"../helpers/get-context":11,"../helpers/get-query-string":12,"../helpers/get-url-max-length":14,"../helpers/get-xhr-object":15,"../helpers/superagent-handle-response":16,"../helpers/superagent-request-types":17,"../index":18,"../utils/base64":29,"../utils/each":31,"../utils/json-shim":34,"superagent":6}],20:[function(require,module,exports){ var Keen = require('../index'); var request = require('superagent'); var each = require('../utils/each'), getContext = require('../helpers/get-context'), getXHR = require('../helpers/get-xhr-object'), requestTypes = require('../helpers/superagent-request-types'), responseHandler = require('../helpers/superagent-handle-response'); module.exports = function(payload, callback) { var self = this, urlBase = this.url('/events'), data = {}, cb = callback; if (!Keen.enabled) { handleValidationError.call(self, 'Keen.enabled = false'); return; } if (!self.projectId()) { handleValidationError.call(self, 'Missing projectId property'); return; } if (!self.writeKey()) { handleValidationError.call(self, 'Missing writeKey property'); return; } if (arguments.length > 2) { handleValidationError.call(self, 'Incorrect arguments provided to #addEvents method'); return; } if (typeof payload !== 'object' || payload instanceof Array) { handleValidationError.call(self, 'Request payload must be an object'); return; } if (self.config.globalProperties) { each(payload, function(events, collection){ each(events, function(body, index){ var base = self.config.globalProperties(collection); each(body, function(value, key){ base[key] = value; }); data[collection].push(base); }); }); } else { data = payload; } if ( getXHR() || getContext() === 'server' ) { request .post(urlBase) .set('Content-Type', 'application/json') .set('Authorization', self.writeKey()) .send(data) .end(function(err, res){ responseHandler(err, res, cb); cb = callback = null; }); } else { self.trigger('error', 'Events not recorded: XHR support is required for batch upload'); } function handleValidationError(msg){ var err = 'Events not recorded: ' + msg; self.trigger('error', err); if (cb) { cb.call(self, err, null); cb = callback = null; } } return; }; },{"../helpers/get-context":11,"../helpers/get-xhr-object":15,"../helpers/superagent-handle-response":16,"../helpers/superagent-request-types":17,"../index":18,"../utils/each":31,"superagent":6}],21:[function(require,module,exports){ var request = require('superagent'); var getQueryString = require('../helpers/get-query-string'), handleResponse = require('../helpers/superagent-handle-response'), requestTypes = require('../helpers/superagent-request-types'); module.exports = function(url, params, api_key, callback){ var reqType = this.config.requestType, data = params || {}; if (reqType === 'beacon') { reqType = 'jsonp'; } data['api_key'] = data['api_key'] || api_key; request .get(url+getQueryString(data)) .use(requestTypes(reqType)) .end(function(err, res){ handleResponse(err, res, callback); callback = null; }); }; },{"../helpers/get-query-string":12,"../helpers/superagent-handle-response":16,"../helpers/superagent-request-types":17,"superagent":6}],22:[function(require,module,exports){ var request = require('superagent'); var handleResponse = require('../helpers/superagent-handle-response'); module.exports = function(url, data, api_key, callback){ request .post(url) .set('Content-Type', 'application/json') .set('Authorization', api_key) .send(data || {}) .end(function(err, res) { handleResponse(err, res, callback); callback = null; }); }; },{"../helpers/superagent-handle-response":16,"superagent":6}],23:[function(require,module,exports){ var Request = require("../request"); module.exports = function(query, callback) { var queries = [], cb = callback, request; if (!this.config.projectId || !this.config.projectId.length) { handleConfigError.call(this, 'Missing projectId property'); } if (!this.config.readKey || !this.config.readKey.length) { handleConfigError.call(this, 'Missing readKey property'); } function handleConfigError(msg){ var err = 'Query not sent: ' + msg; this.trigger('error', err); if (cb) { cb.call(this, err, null); cb = callback = null; } } if (query instanceof Array) { queries = query; } else { queries.push(query); } request = new Request(this, queries, cb).refresh(); cb = callback = null; return request; }; },{"../request":27}],24:[function(require,module,exports){ module.exports = function(newGlobalProperties) { if (newGlobalProperties && typeof(newGlobalProperties) == "function") { this.config.globalProperties = newGlobalProperties; } else { this.trigger("error", "Invalid value for global properties: " + newGlobalProperties); } }; },{}],25:[function(require,module,exports){ var addEvent = require("./addEvent"); module.exports = function(jsEvent, eventCollection, payload, timeout, timeoutCallback){ var evt = jsEvent, target = (evt.currentTarget) ? evt.currentTarget : (evt.srcElement || evt.target), timer = timeout || 500, triggered = false, targetAttr = "", callback, win; if (target.getAttribute !== void 0) { targetAttr = target.getAttribute("target"); } else if (target.target) { targetAttr = target.target; } if ((targetAttr == "_blank" || targetAttr == "blank") && !evt.metaKey) { win = window.open("about:blank"); win.document.location = target.href; } if (target.nodeName === "A") { callback = function(){ if(!triggered && !evt.metaKey && (targetAttr !== "_blank" && targetAttr !== "blank")){ triggered = true; window.location = target.href; } }; } else if (target.nodeName === "FORM") { callback = function(){ if(!triggered){ triggered = true; target.submit(); } }; } else { this.trigger("error", "#trackExternalLink method not attached to an <a> or <form> DOM element"); } if (timeoutCallback) { callback = function(){ if(!triggered){ triggered = true; timeoutCallback(); } }; } addEvent.call(this, eventCollection, payload, callback); setTimeout(callback, timer); if (!evt.metaKey) { return false; } }; },{"./addEvent":19}],26:[function(require,module,exports){ var each = require("./utils/each"), extend = require("./utils/extend"), getTimezoneOffset = require("./helpers/get-timezone-offset"), getQueryString = require("./helpers/get-query-string"); var Emitter = require('./utils/emitter-shim'); function Query(){ this.configure.apply(this, arguments); }; Emitter(Query.prototype); Query.prototype.configure = function(analysisType, params) { this.analysis = analysisType; this.params = this.params || {}; this.set(params); if (this.params.timezone === void 0) { this.params.timezone = getTimezoneOffset(); } return this; }; Query.prototype.set = function(attributes) { var self = this; each(attributes, function(v, k){ var key = k, value = v; if (k.match(new RegExp("[A-Z]"))) { key = k.replace(/([A-Z])/g, function($1) { return "_"+$1.toLowerCase(); }); } self.params[key] = value; if (value instanceof Array) { each(value, function(dv, index){ if (dv instanceof Array == false && typeof dv === "object") { each(dv, function(deepValue, deepKey){ if (deepKey.match(new RegExp("[A-Z]"))) { var _deepKey = deepKey.replace(/([A-Z])/g, function($1) { return "_"+$1.toLowerCase(); }); delete self.params[key][index][deepKey]; self.params[key][index][_deepKey] = deepValue; } }); } }); } }); return self; }; Query.prototype.get = function(attribute) { var key = attribute; if (key.match(new RegExp("[A-Z]"))) { key = key.replace(/([A-Z])/g, function($1) { return "_"+$1.toLowerCase(); }); } if (this.params) { return this.params[key] || null; } }; Query.prototype.addFilter = function(property, operator, value) { this.params.filters = this.params.filters || []; this.params.filters.push({ "property_name": property, "operator": operator, "property_value": value }); return this; }; module.exports = Query; },{"./helpers/get-query-string":12,"./helpers/get-timezone-offset":13,"./utils/each":31,"./utils/emitter-shim":32,"./utils/extend":33}],27:[function(require,module,exports){ var each = require('./utils/each'), extend = require('./utils/extend'), sendQuery = require('./utils/sendQuery'), sendSavedQuery = require('./utils/sendSavedQuery'); var Emitter = require('./utils/emitter-shim'); var Keen = require('./'); var Query = require('./query'); function Request(client, queries, callback){ var cb = callback; this.config = { timeout: 300 * 1000 }; this.configure(client, queries, cb); cb = callback = null; }; Emitter(Request.prototype); Request.prototype.configure = function(client, queries, callback){ var cb = callback; extend(this, { 'client' : client, 'queries' : queries, 'data' : {}, 'callback' : cb }); cb = callback = null; return this; }; Request.prototype.timeout = function(ms){ if (!arguments.length) return this.config.timeout; this.config.timeout = (!isNaN(parseInt(ms)) ? parseInt(ms) : null); return this; }; Request.prototype.refresh = function(){ var self = this, completions = 0, response = [], errored = false; var handleResponse = function(err, res, index){ if (errored) { return; } if (err) { self.trigger('error', err); if (self.callback) { self.callback(err, null); } errored = true; return; } response[index] = res; completions++; if (completions == self.queries.length && !errored) { self.data = (self.queries.length == 1) ? response[0] : response; self.trigger('complete', null, self.data); if (self.callback) { self.callback(null, self.data); } } }; each(self.queries, function(query, index){ var cbSequencer = function(err, res){ handleResponse(err, res, index); }; var path = '/queries'; if (typeof query === 'string') { path += '/saved/' + query + '/result'; sendSavedQuery.call(self, path, {}, cbSequencer); } else if (query instanceof Query) { path += '/' + query.analysis; if (query.analysis === 'saved') { path += '/' + query.params.query_name + '/result'; sendSavedQuery.call(self, path, {}, cbSequencer); } else { sendQuery.call(self, path, query.params, cbSequencer); } } else { var res = { statusText: 'Bad Request', responseText: { message: 'Error: Query ' + (+index+1) + ' of ' + self.queries.length + ' for project ' + self.client.projectId() + ' is not a valid request' } }; self.trigger('error', res.responseText.message); if (self.callback) { self.callback(res.responseText.message, null); } } }); return this; }; module.exports = Request; },{"./":18,"./query":26,"./utils/each":31,"./utils/emitter-shim":32,"./utils/extend":33,"./utils/sendQuery":36,"./utils/sendSavedQuery":37}],28:[function(require,module,exports){ var request = require('superagent'); var responseHandler = require('./helpers/superagent-handle-response'); function savedQueries() { var _this = this; this.all = function(callback) { var url = _this.url('/queries/saved'); request .get(url) .set('Content-Type', 'application/json') .set('Authorization', _this.masterKey()) .end(handleResponse); function handleResponse(err, res){ responseHandler(err, res, callback); callback = null; } }; this.get = function(queryName, callback) { var url = _this.url('/queries/saved/' + queryName); request .get(url) .set('Content-Type', 'application/json') .set('Authorization', _this.masterKey()) .end(handleResponse); function handleResponse(err, res){ responseHandler(err, res, callback); callback = null; } }; this.update = function(queryName, body, callback) { var url = _this.url('/queries/saved/' + queryName); request .put(url) .set('Content-Type', 'application/json') .set('Authorization', _this.masterKey()) .send(body || {}) .end(handleResponse); function handleResponse(err, res){ responseHandler(err, res, callback); callback = null; } }; this.create = this.update; this.destroy = function(queryName, callback) { var url = _this.url('/queries/saved/' + queryName); request .del(url) .set('Content-Type', 'application/json') .set('Authorization', _this.masterKey()) .end(handleResponse); function handleResponse(err, res){ responseHandler(err, res, callback); callback = null; } }; return this; } module.exports = savedQueries; },{"./helpers/superagent-handle-response":16,"superagent":6}],29:[function(require,module,exports){ module.exports = { map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", encode: function (n) { "use strict"; var o = "", i = 0, m = this.map, i1, i2, i3, e1, e2, e3, e4; n = this.utf8.encode(n); while (i < n.length) { i1 = n.charCodeAt(i++); i2 = n.charCodeAt(i++); i3 = n.charCodeAt(i++); e1 = (i1 >> 2); e2 = (((i1 & 3) << 4) | (i2 >> 4)); e3 = (isNaN(i2) ? 64 : ((i2 & 15) << 2) | (i3 >> 6)); e4 = (isNaN(i2) || isNaN(i3)) ? 64 : i3 & 63; o = o + m.charAt(e1) + m.charAt(e2) + m.charAt(e3) + m.charAt(e4); } return o; }, decode: function (n) { "use strict"; var o = "", i = 0, m = this.map, cc = String.fromCharCode, e1, e2, e3, e4, c1, c2, c3; n = n.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < n.length) { e1 = m.indexOf(n.charAt(i++)); e2 = m.indexOf(n.charAt(i++)); e3 = m.indexOf(n.charAt(i++)); e4 = m.indexOf(n.charAt(i++)); c1 = (e1 << 2) | (e2 >> 4); c2 = ((e2 & 15) << 4) | (e3 >> 2); c3 = ((e3 & 3) << 6) | e4; o = o + (cc(c1) + ((e3 != 64) ? cc(c2) : "")) + (((e4 != 64) ? cc(c3) : "")); } return this.utf8.decode(o); }, utf8: { encode: function (n) { "use strict"; var o = "", i = 0, cc = String.fromCharCode, c; while (i < n.length) { c = n.charCodeAt(i++); o = o + ((c < 128) ? cc(c) : ((c > 127) && (c < 2048)) ? (cc((c >> 6) | 192) + cc((c & 63) | 128)) : (cc((c >> 12) | 224) + cc(((c >> 6) & 63) | 128) + cc((c & 63) | 128))); } return o; }, decode: function (n) { "use strict"; var o = "", i = 0, cc = String.fromCharCode, c2, c; while (i < n.length) { c = n.charCodeAt(i); o = o + ((c < 128) ? [cc(c), i++][0] : ((c > 191) && (c < 224)) ? [cc(((c & 31) << 6) | ((c2 = n.charCodeAt(i + 1)) & 63)), (i += 2)][0] : [cc(((c & 15) << 12) | (((c2 = n.charCodeAt(i + 1)) & 63) << 6) | ((c3 = n.charCodeAt(i + 2)) & 63)), (i += 3)][0]); } return o; } } }; },{}],30:[function(require,module,exports){ var json = require('./json-shim'); module.exports = function(target) { return json.parse( json.stringify( target ) ); }; },{"./json-shim":34}],31:[function(require,module,exports){ module.exports = function(o, cb, s){ var n; if (!o){ return 0; } s = !s ? o : s; if (o instanceof Array){ for (n=0; n<o.length; n++) { if (cb.call(s, o[n], n, o) === false){ return 0; } } } else { for (n in o){ if (o.hasOwnProperty(n)) { if (cb.call(s, o[n], n, o) === false){ return 0; } } } } return 1; }; },{}],32:[function(require,module,exports){ var Emitter = require('component-emitter'); Emitter.prototype.trigger = Emitter.prototype.emit; module.exports = Emitter; },{"component-emitter":1}],33:[function(require,module,exports){ module.exports = function(target){ for (var i = 1; i < arguments.length; i++) { for (var prop in arguments[i]){ target[prop] = arguments[i][prop]; } } return target; }; },{}],34:[function(require,module,exports){ module.exports = ('undefined' !== typeof window && window.JSON) ? window.JSON : require("json3"); },{"json3":3}],35:[function(require,module,exports){ function parseParams(str){ var urlParams = {}, match, pl = /\+/g, search = /([^&=]+)=?([^&]*)/g, decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); }, query = str.split("?")[1]; while (!!(match=search.exec(query))) { urlParams[decode(match[1])] = decode(match[2]); } return urlParams; }; module.exports = parseParams; },{}],36:[function(require,module,exports){ var request = require('superagent'); var getContext = require('../helpers/get-context'), getXHR = require('../helpers/get-xhr-object'), responseHandler = require('../helpers/superagent-handle-response'); module.exports = function(path, params, callback){ var url = this.client.url(path); if (!this.client.projectId()) { this.client.trigger('error', 'Query not sent: Missing projectId property'); return; } if (!this.client.readKey()) { this.client.trigger('error', 'Query not sent: Missing readKey property'); return; } if (getContext() === 'server' || getXHR()) { request .post(url) .set('Content-Type', 'application/json') .set('Authorization', this.client.readKey()) .timeout(this.timeout()) .send(params || {}) .end(handleResponse); } function handleResponse(err, res){ responseHandler(err, res, callback); callback = null; } return; } },{"../helpers/get-context":11,"../helpers/get-xhr-object":15,"../helpers/superagent-handle-response":16,"superagent":6}],37:[function(require,module,exports){ var request = require('superagent'); var responseHandler = require('../helpers/superagent-handle-response'); module.exports = function(path, params, callback){ var key; if (this.client.readKey()) { key = this.client.readKey(); } else if (this.client.masterKey()) { key = this.client.masterKey(); } request .get(this.client.url(path)) .set('Content-Type', 'application/json') .set('Authorization', key) .timeout(this.timeout()) .send() .end(function(err, res) { responseHandler(err, res, callback); callback = null; }); return; } },{"../helpers/superagent-handle-response":16,"superagent":6}],38:[function(require,module,exports){ var clone = require("../core/utils/clone"), each = require("../core/utils/each"), flatten = require("./utils/flatten"), parse = require("./utils/parse"); var Emitter = require('../core/utils/emitter-shim'); function Dataset(){ this.data = { input: {}, output: [['Index']] }; this.meta = { schema: {}, method: undefined }; this.parser = undefined; if (arguments.length > 0) { this.parse.apply(this, arguments); } } Dataset.defaults = { delimeter: " -> " }; Emitter(Dataset); Emitter(Dataset.prototype); Dataset.parser = require('./utils/parsers')(Dataset); Dataset.prototype.input = function(obj){ if (!arguments.length) return this["data"]["input"]; this["data"]["input"] = (obj ? clone(obj) : null); return this; }; Dataset.prototype.output = function(arr){ if (!arguments.length) return this["data"].output; this["data"].output = (arr instanceof Array ? arr : null); return this; } Dataset.prototype.method = function(str){ if (!arguments.length) return this.meta["method"]; this.meta["method"] = (str ? String(str) : null); return this; }; Dataset.prototype.schema = function(obj){ if (!arguments.length) return this.meta.schema; this.meta.schema = (obj ? obj : null); return this; }; Dataset.prototype.parse = function(raw, schema){ var options; if (raw) this.input(raw); if (schema) this.schema(schema); this.output([[]]); if (this.meta.schema.select) { this.method("select"); options = extend({ records: "", select: true }, this.schema()); _select.call(this, _optHash(options)); } else if (this.meta.schema.unpack) { this.method("unpack"); options = extend({ records: "", unpack: { index: false, value: false, label: false } }, this.schema()); _unpack.call(this, _optHash(options)); } return this; }; function _select(cfg){ var self = this, options = cfg || {}, target_set = [], unique_keys = []; var root, records_target; if (options.records === "" || !options.records) { root = [self.input()]; } else { records_target = options.records.split(Dataset.defaults.delimeter); root = parse.apply(self, [self.input()].concat(records_target))[0]; } each(options.select, function(prop){ target_set.push(prop.path.split(Dataset.defaults.delimeter)); }); if (target_set.length == 0) { each(root, function(record, interval){ var flat = flatten(record); for (var key in flat) { if (flat.hasOwnProperty(key) && unique_keys.indexOf(key) == -1) { unique_keys.push(key); target_set.push([key]); } } }); } var test = [[]]; each(target_set, function(props, i){ if (target_set.length == 1) { test[0].push('label', 'value'); } else { test[0].push(props.join(".")); } }); each(root, function(record, i){ var flat = flatten(record); if (target_set.length == 1) { test.push([target_set.join("."), flat[target_set.join(".")]]); } else { test.push([]); each(target_set, function(t, j){ var target = t.join("."); test[i+1].push(flat[target]); }); } }); self.output(test); self.format(options.select); return self; } function _unpack(options){ var self = this, discovered_labels = []; var value_set = (options.unpack.value) ? options.unpack.value.path.split(Dataset.defaults.delimeter) : false, label_set = (options.unpack.label) ? options.unpack.label.path.split(Dataset.defaults.delimeter) : false, index_set = (options.unpack.index) ? options.unpack.index.path.split(Dataset.defaults.delimeter) : false; var value_desc = (value_set[value_set.length-1] !== "") ? value_set[value_set.length-1] : "Value", label_desc = (label_set[label_set.length-1] !== "") ? label_set[label_set.length-1] : "Label", index_desc = (index_set[index_set.length-1] !== "") ? index_set[index_set.length-1] : "Index"; var root = (function(){ var root; if (options.records == "") { root = [self.input()]; } else { root = parse.apply(self, [self.input()].concat(options.records.split(Dataset.defaults.delimeter))); } return root[0]; })(); if (root instanceof Array == false) { root = [root]; } each(root, function(record, interval){ var labels = (label_set) ? parse.apply(self, [record].concat(label_set)) : []; if (labels) { discovered_labels = labels; } }); each(root, function(record, interval){ var plucked_value = (value_set) ? parse.apply(self, [record].concat(value_set)) : false, plucked_index = (index_set) ? parse.apply(self, [record].concat(index_set)) : false; if (plucked_index) { each(plucked_index, function(){ self.data.output.push([]); }); } else { self.data.output.push([]); } if (plucked_index) { if (interval == 0) { self.data.output[0].push(index_desc); if (discovered_labels.length > 0) { each(discovered_labels, function(value, i){ self.data.output[0].push(value); }); } else { self.data.output[0].push(value_desc); } } if (root.length < self.data.output.length-1) { if (interval == 0) { each(self.data.output, function(row, i){ if (i > 0) { self.data.output[i].push(plucked_index[i-1]); } }); } } else { self.data.output[interval+1].push(plucked_index[0]); } } if (!plucked_index && discovered_labels.length > 0) { if (interval == 0) { self.data.output[0].push(label_desc); self.data.output[0].push(value_desc); } self.data.output[interval+1].push(discovered_labels[0]); } if (!plucked_index && discovered_labels.length == 0) { self.data.output[0].push(''); } if (plucked_value) { if (root.length < self.data.output.length-1) { if (interval == 0) { each(self.data.output, function(row, i){ if (i > 0) { self.data.output[i].push(plucked_value[i-1]); } }); } } else { each(plucked_value, function(value){ self.data.output[interval+1].push(value); }); } } else { each(self.data.output[0], function(cell, i){ var offset = (plucked_index) ? 0 : -1; if (i > offset) { self.data.output[interval+1].push(null); } }) } }); self.format(options.unpack); return this; } function _optHash(options){ each(options.unpack, function(value, key, object){ if (value && is(value, 'string')) { options.unpack[key] = { path: options.unpack[key] }; } }); return options; } function is(o, t){ o = typeof(o); if (!t){ return o != 'undefined'; } return o == t; } function extend(o, e){ each(e, function(v, n){ if (is(o[n], 'object') && is(v, 'object')){ o[n] = extend(o[n], v); } else if (v !== null) { o[n] = v; } }); return o; } module.exports = Dataset; },{"../core/utils/clone":30,"../core/utils/each":31,"../core/utils/emitter-shim":32,"./utils/flatten":51,"./utils/parse":52,"./utils/parsers":53}],39:[function(require,module,exports){ var extend = require("../core/utils/extend"), Dataset = require("./dataset"); extend(Dataset.prototype, require("./lib/append")); extend(Dataset.prototype, require("./lib/delete")); extend(Dataset.prototype, require("./lib/filter")); extend(Dataset.prototype, require("./lib/insert")); extend(Dataset.prototype, require("./lib/select")); extend(Dataset.prototype, require("./lib/set")); extend(Dataset.prototype, require("./lib/sort")); extend(Dataset.prototype, require("./lib/update")); extend(Dataset.prototype, require("./lib/analyses")); extend(Dataset.prototype, { "format": require("./lib/format") }); module.exports = Dataset; },{"../core/utils/extend":33,"./dataset":38,"./lib/analyses":40,"./lib/append":41,"./lib/delete":42,"./lib/filter":43,"./lib/format":44,"./lib/insert":45,"./lib/select":46,"./lib/set":47,"./lib/sort":48,"./lib/update":49}],40:[function(require,module,exports){ var each = require("../../core/utils/each"), arr = ["Average", "Maximum", "Minimum", "Sum"], output = {}; output["average"] = function(arr, start, end){ var set = arr.slice(start||0, (end ? end+1 : arr.length)), sum = 0, avg = null; each(set, function(val, i){ if (typeof val === "number" && !isNaN(parseFloat(val))) { sum += parseFloat(val); } }); return sum / set.length; }; output["maximum"] = function(arr, start, end){ var set = arr.slice(start||0, (end ? end+1 : arr.length)), nums = []; each(set, function(val, i){ if (typeof val === "number" && !isNaN(parseFloat(val))) { nums.push(parseFloat(val)); } }); return Math.max.apply(Math, nums); }; output["minimum"] = function(arr, start, end){ var set = arr.slice(start||0, (end ? end+1 : arr.length)), nums = []; each(set, function(val, i){ if (typeof val === "number" && !isNaN(parseFloat(val))) { nums.push(parseFloat(val)); } }); return Math.min.apply(Math, nums); }; output["sum"] = function(arr, start, end){ var set = arr.slice(start||0, (end ? end+1 : arr.length)), sum = 0; each(set, function(val, i){ if (typeof val === "number" && !isNaN(parseFloat(val))) { sum += parseFloat(val); } }); return sum; }; each(arr, function(v,i){ output["getColumn"+v] = output["getRow"+v] = function(arr){ return this[v.toLowerCase()](arr, 1); }; }); output["getColumnLabel"] = output["getRowIndex"] = function(arr){ return arr[0]; }; module.exports = output; },{"../../core/utils/each":31}],41:[function(require,module,exports){ var each = require("../../core/utils/each"); var createNullList = require('../utils/create-null-list'); module.exports = { "appendColumn": appendColumn, "appendRow": appendRow }; function appendColumn(str, input){ var self = this, args = Array.prototype.slice.call(arguments, 2), label = (str !== undefined) ? str : null; if (typeof input === "function") { self.data.output[0].push(label); each(self.output(), function(row, i){ var cell; if (i > 0) { cell = input.call(self, row, i); if (typeof cell === "undefined") { cell = null; } self.data.output[i].push(cell); } }); } else if (!input || input instanceof Array) { input = input || []; if (input.length <= self.output().length - 1) { input = input.concat( createNullList(self.output().length - 1 - input.length) ); } else { each(input, function(value, i){ if (self.data.output.length -1 < input.length) { appendRow.call(self, String( self.data.output.length )); } }); } self.data.output[0].push(label); each(input, function(value, i){ self.data.output[i+1][self.data.output[0].length-1] = value; }); } return self; } function appendRow(str, input){ var self = this, args = Array.prototype.slice.call(arguments, 2), label = (str !== undefined) ? str : null, newRow = []; newRow.push(label); if (typeof input === "function") { each(self.data.output[0], function(label, i){ var col, cell; if (i > 0) { col = self.selectColumn(i); cell = input.call(self, col, i); if (typeof cell === "undefined") { cell = null; } newRow.push(cell); } }); self.data.output.push(newRow); } else if (!input || input instanceof Array) { input = input || []; if (input.length <= self.data.output[0].length - 1) { input = input.concat( createNullList( self.data.output[0].length - 1 - input.length ) ); } else { each(input, function(value, i){ if (self.data.output[0].length -1 < input.length) { appendColumn.call(self, String( self.data.output[0].length )); } }); } self.data.output.push( newRow.concat(input) ); } return self; } },{"../../core/utils/each":31,"../utils/create-null-list":50}],42:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = { "deleteColumn": deleteColumn, "deleteRow": deleteRow }; function deleteColumn(q){ var self = this, index = (typeof q === 'number') ? q : this.data.output[0].indexOf(q); if (index > -1) { each(self.data.output, function(row, i){ self.data.output[i].splice(index, 1); }); } return self; } function deleteRow(q){ var index = (typeof q === 'number') ? q : this.selectColumn(0).indexOf(q); if (index > -1) { this.data.output.splice(index, 1); } return this; } },{"../../core/utils/each":31}],43:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = { "filterColumns": filterColumns, "filterRows": filterRows }; function filterColumns(fn){ var self = this, clone = new Array(); each(self.data.output, function(row, i){ clone.push([]); }); each(self.data.output[0], function(col, i){ var selectedColumn = self.selectColumn(i); if (i == 0 || fn.call(self, selectedColumn, i)) { each(selectedColumn, function(cell, ri){ clone[ri].push(cell); }); } }); self.output(clone); return self; } function filterRows(fn){ var self = this, clone = []; each(self.output(), function(row, i){ if (i == 0 || fn.call(self, row, i)) { clone.push(row); } }); self.output(clone); return self; } },{"../../core/utils/each":31}],44:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = function(options){ var self = this; if (this.method() === 'select') { each(self.output(), function(row, i){ if (i == 0) { each(row, function(cell, j){ if (options[j] && options[j].label) { self.data.output[i][j] = options[j].label; } }); } else { each(row, function(cell, j){ self.data.output[i][j] = _applyFormat(self.data.output[i][j], options[j]); }); } }); } if (this.method() === 'unpack') { if (options.index) { each(self.output(), function(row, i){ if (i == 0) { if (options.index.label) { self.data.output[i][0] = options.index.label; } } else { self.data.output[i][0] = _applyFormat(self.data.output[i][0], options.index); } }); } if (options.label) { if (options.index) { each(self.output(), function(row, i){ each(row, function(cell, j){ if (i == 0 && j > 0) { self.data.output[i][j] = _applyFormat(self.data.output[i][j], options.label); } }); }); } else { each(self.output(), function(row, i){ if (i > 0) { self.data.output[i][0] = _applyFormat(self.data.output[i][0], options.label); } }); } } if (options.value) { if (options.index) { each(self.output(), function(row, i){ each(row, function(cell, j){ if (i > 0 && j > 0) { self.data.output[i][j] = _applyFormat(self.data.output[i][j], options.value); } }); }); } else { each(self.output(), function(row, i){ each(row, function(cell, j){ if (i > 0) { self.data.output[i][j] = _applyFormat(self.data.output[i][j], options.value); } }); }); } } } return self; }; function _applyFormat(value, opts){ var output = value, options = opts || {}; if (options.replace) { each(options.replace, function(val, key){ if (output == key || String(output) == String(key) || parseFloat(output) == parseFloat(key)) { output = val; } }); } if (options.type && options.type == 'date') { if (options.format && moment && moment(value).isValid()) { output = moment(output).format(options.format); } else { output = new Date(output); } } if (options.type && options.type == 'string') { output = String(output); } if (options.type && options.type == 'number' && !isNaN(parseFloat(output))) { output = parseFloat(output); } return output; } },{"../../core/utils/each":31}],45:[function(require,module,exports){ var each = require("../../core/utils/each"); var createNullList = require('../utils/create-null-list'); var append = require('./append'); var appendRow = append.appendRow, appendColumn = append.appendColumn; module.exports = { "insertColumn": insertColumn, "insertRow": insertRow }; function insertColumn(index, str, input){ var self = this, label; label = (str !== undefined) ? str : null; if (typeof input === "function") { self.data.output[0].splice(index, 0, label); each(self.output(), function(row, i){ var cell; if (i > 0) { cell = input.call(self, row, i); if (typeof cell === "undefined") { cell = null; } self.data.output[i].splice(index, 0, cell); } }); } else if (!input || input instanceof Array) { input = input || []; if (input.length <= self.output().length - 1) { input = input.concat( createNullList(self.output().length - 1 - input.length) ); } else { each(input, function(value, i){ if (self.data.output.length -1 < input.length) { appendRow.call(self, String( self.data.output.length )); } }); } self.data.output[0].splice(index, 0, label); each(input, function(value, i){ self.data.output[i+1].splice(index, 0, value); }); } return self; } function insertRow(index, str, input){ var self = this, label, newRow = []; label = (str !== undefined) ? str : null; newRow.push(label); if (typeof input === "function") { each(self.output()[0], function(label, i){ var col, cell; if (i > 0) { col = self.selectColumn(i); cell = input.call(self, col, i); if (typeof cell === "undefined") { cell = null; } newRow.push(cell); } }); self.data.output.splice(index, 0, newRow); } else if (!input || input instanceof Array) { input = input || []; if (input.length <= self.data.output[0].length - 1) { input = input.concat( createNullList( self.data.output[0].length - 1 - input.length ) ); } else { each(input, function(value, i){ if (self.data.output[0].length -1 < input.length) { appendColumn.call(self, String( self.data.output[0].length )); } }); } self.data.output.splice(index, 0, newRow.concat(input) ); } return self; } },{"../../core/utils/each":31,"../utils/create-null-list":50,"./append":41}],46:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = { "selectColumn": selectColumn, "selectRow": selectRow }; function selectColumn(q){ var result = new Array(), index = (typeof q === 'number') ? q : this.data.output[0].indexOf(q); if (index > -1 && 'undefined' !== typeof this.data.output[0][index]) { each(this.data.output, function(row, i){ result.push(row[index]); }); } return result; } function selectRow(q){ var result = new Array(), index = (typeof q === 'number') ? q : this.selectColumn(0).indexOf(q); if (index > -1 && 'undefined' !== typeof this.data.output[index]) { result = this.data.output[index]; } return result; } },{"../../core/utils/each":31}],47:[function(require,module,exports){ var each = require("../../core/utils/each"); var append = require('./append'); var select = require('./select'); module.exports = { "set": set }; function set(coords, value){ if (arguments.length < 2 || coords.length < 2) { throw Error('Incorrect arguments provided for #set method'); } var colIndex = 'number' === typeof coords[0] ? coords[0] : this.data.output[0].indexOf(coords[0]), rowIndex = 'number' === typeof coords[1] ? coords[1] : select.selectColumn.call(this, 0).indexOf(coords[1]); var colResult = select.selectColumn.call(this, coords[0]), rowResult = select.selectRow.call(this, coords[1]); if (colResult.length < 1) { append.appendColumn.call(this, coords[0]); colIndex = this.data.output[0].length-1; } if (rowResult.length < 1) { append.appendRow.call(this, coords[1]); rowIndex = this.data.output.length-1; } this.data.output[ rowIndex ][ colIndex ] = value; return this; } },{"../../core/utils/each":31,"./append":41,"./select":46}],48:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = { "sortColumns": sortColumns, "sortRows": sortRows }; function sortColumns(str, comp){ var self = this, head = this.output()[0].slice(1), cols = [], clone = [], fn = comp || this.getColumnLabel; each(head, function(cell, i){ cols.push(self.selectColumn(i+1).slice(0)); }); cols.sort(function(a,b){ var op = fn.call(self, a) > fn.call(self, b); if (op) { return (str === "asc" ? 1 : -1); } else if (!op) { return (str === "asc" ? -1 : 1); } else { return 0; } }); each(cols, function(col, i){ self .deleteColumn(i+1) .insertColumn(i+1, col[0], col.slice(1)); }); return self; } function sortRows(str, comp){ var self = this, head = this.output().slice(0,1), body = this.output().slice(1), fn = comp || this.getRowIndex; body.sort(function(a, b){ var op = fn.call(self, a) > fn.call(self, b); if (op) { return (str === "asc" ? 1 : -1); } else if (!op) { return (str === "asc" ? -1 : 1); } else { return 0; } }); self.output(head.concat(body)); return self; } },{"../../core/utils/each":31}],49:[function(require,module,exports){ var each = require("../../core/utils/each"); var createNullList = require('../utils/create-null-list'); var append = require('./append'); var appendRow = append.appendRow, appendColumn = append.appendColumn; module.exports = { "updateColumn": updateColumn, "updateRow": updateRow }; function updateColumn(q, input){ var self = this, index = (typeof q === 'number') ? q : this.data.output[0].indexOf(q); if (index > -1) { if (typeof input === "function") { each(self.output(), function(row, i){ var cell; if (i > 0) { cell = input.call(self, row[index], i, row); if (typeof cell !== "undefined") { self.data.output[i][index] = cell; } } }); } else if (!input || input instanceof Array) { input = input || []; if (input.length <= self.output().length - 1) { input = input.concat( createNullList(self.output().length - 1 - input.length) ); } else { each(input, function(value, i){ if (self.data.output.length -1 < input.length) { appendRow.call(self, String( self.data.output.length )); } }); } each(input, function(value, i){ self.data.output[i+1][index] = value; }); } } return self; } function updateRow(q, input){ var self = this, index = (typeof q === 'number') ? q : this.selectColumn(0).indexOf(q); if (index > -1) { if (typeof input === "function") { each(self.output()[index], function(value, i){ var col = self.selectColumn(i), cell = input.call(self, value, i, col); if (typeof cell !== "undefined") { self.data.output[index][i] = cell; } }); } else if (!input || input instanceof Array) { input = input || []; if (input.length <= self.data.output[0].length - 1) { input = input.concat( createNullList( self.data.output[0].length - 1 - input.length ) ); } else { each(input, function(value, i){ if (self.data.output[0].length -1 < input.length) { appendColumn.call(self, String( self.data.output[0].length )); } }); } each(input, function(value, i){ self.data.output[index][i+1] = value; }); } } return self; } },{"../../core/utils/each":31,"../utils/create-null-list":50,"./append":41}],50:[function(require,module,exports){ module.exports = function(len){ var list = new Array(); for (i = 0; i < len; i++) { list.push(null); } return list; }; },{}],51:[function(require,module,exports){ module.exports = flatten; function flatten(ob) { var toReturn = {}; for (var i in ob) { if (!ob.hasOwnProperty(i)) continue; if ((typeof ob[i]) == 'object' && ob[i] !== null) { var flatObject = flatten(ob[i]); for (var x in flatObject) { if (!flatObject.hasOwnProperty(x)) continue; toReturn[i + '.' + x] = flatObject[x]; } } else { toReturn[i] = ob[i]; } } return toReturn; } },{}],52:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = function() { var result = []; var loop = function() { var root = arguments[0]; var args = Array.prototype.slice.call(arguments, 1); var target = args.pop(); if (args.length === 0) { if (root instanceof Array) { args = root; } else if (typeof root === 'object') { args.push(root); } } each(args, function(el){ if (target == "") { if (typeof el == "number" || el == null) { return result.push(el); } } if (el[target] || el[target] === 0 || el[target] !== void 0) { if (el[target] === null) { return result.push(null); } else { return result.push(el[target]); } } else if (root[el]){ if (root[el] instanceof Array) { each(root[el], function(n, i) { var splinter = [root[el]].concat(root[el][i]).concat(args.slice(1)).concat(target); return loop.apply(this, splinter); }); } else { if (root[el][target]) { return result.push(root[el][target]); } else { return loop.apply(this, [root[el]].concat(args.splice(1)).concat(target)); } } } else if (typeof root === 'object' && root instanceof Array === false && !root[target]) { throw new Error("Target property does not exist", target); } else { return loop.apply(this, [el].concat(args.splice(1)).concat(target)); } return; }); if (result.length > 0) { return result; } }; return loop.apply(this, arguments); } },{"../../core/utils/each":31}],53:[function(require,module,exports){ var Dataset; /* injected */ var each = require('../../core/utils/each'), flatten = require('./flatten'); var parsers = { 'metric': parseMetric, 'interval': parseInterval, 'grouped-metric': parseGroupedMetric, 'grouped-interval': parseGroupedInterval, 'double-grouped-metric': parseDoubleGroupedMetric, 'double-grouped-interval': parseDoubleGroupedInterval, 'funnel': parseFunnel, 'list': parseList, 'extraction': parseExtraction }; module.exports = initialize; function initialize(lib){ Dataset = lib; return function(name){ var options = Array.prototype.slice.call(arguments, 1); if (!parsers[name]) { throw 'Requested parser does not exist'; } else { return parsers[name].apply(this, options); } }; } function parseMetric(){ return function(res){ var dataset = new Dataset(); dataset.data.input = res; dataset.parser = { name: 'metric' }; return dataset.set(['Value', 'Result'], res.result); } } function parseInterval(){ var options = Array.prototype.slice.call(arguments); return function(res){ var dataset = new Dataset(); each(res.result, function(record, i){ var index = options[0] && options[0] === 'timeframe.end' ? record.timeframe.end : record.timeframe.start; dataset.set(['Result', index], record.value); }); dataset.data.input = res; dataset.parser = 'interval'; dataset.parser = { name: 'interval', options: options }; return dataset; } } function parseGroupedMetric(){ return function(res){ var dataset = new Dataset(); each(res.result, function(record, i){ var label; each(record, function(value, key){ if (key !== 'result') { label = key; } }); dataset.set(['Result', String(record[label])], record.result); }); dataset.data.input = res; dataset.parser = { name: 'grouped-metric' }; return dataset; } } function parseGroupedInterval(){ var options = Array.prototype.slice.call(arguments); return function(res){ var dataset = new Dataset(); each(res.result, function(record, i){ var index = options[0] && options[0] === 'timeframe.end' ? record.timeframe.end : record.timeframe.start; if (record.value.length) { each(record.value, function(group, j){ var label; each(group, function(value, key){ if (key !== 'result') { label = key; } }); dataset.set([ String(group[label]) || '', index ], group.result); }); } else { dataset.appendRow(index); } }); dataset.data.input = res; dataset.parser = { name: 'grouped-interval', options: options }; return dataset; } } function parseDoubleGroupedMetric(){ var options = Array.prototype.slice.call(arguments); if (!options[0]) throw 'Requested parser requires a sequential list (array) of properties to target as a second argument'; return function(res){ var dataset = new Dataset(); each(res.result, function(record, i){ dataset.set([ 'Result', record[options[0][0]] + ' ' + record[options[0][1]] ], record.result); }); dataset.data.input = res; dataset.parser = { name: 'double-grouped-metric', options: options }; return dataset; } } function parseDoubleGroupedInterval(){ var options = Array.prototype.slice.call(arguments); if (!options[0]) throw 'Requested parser requires a sequential list (array) of properties to target as a second argument'; return function(res){ var dataset = new Dataset(); each(res.result, function(record, i){ var index = options[1] && options[1] === 'timeframe.end' ? record.timeframe.end : record.timeframe.start; each(record['value'], function(value, j){ var label = String(value[options[0][0]]) + ' ' + String(value[options[0][1]]); dataset.set([ label, index ], value.result); }); }); dataset.data.input = res; dataset.parser = { name: 'double-grouped-interval', options: options }; return dataset; } } function parseFunnel(){ return function(res){ var dataset = new Dataset(); dataset.appendColumn('Step Value'); each(res.result, function(value, i){ dataset.appendRow(res.steps[i].event_collection, [ value ]); }); dataset.data.input = res; dataset.parser = { name: 'funnel' }; return dataset; } } function parseList(){ return function(res){ var dataset = new Dataset(); each(res.result, function(value, i){ dataset.set( [ 'Value', i+1 ], value ); }); dataset.data.input = res; dataset.parser = { name: 'list' }; return dataset; } } function parseExtraction(){ return function(res){ var dataset = new Dataset(); each(res.result, function(record, i){ each(flatten(record), function(value, key){ dataset.set([key, i+1], value); }); }); dataset.deleteColumn(0); dataset.data.input = res; dataset.parser = { name: 'extraction' }; return dataset; } } },{"../../core/utils/each":31,"./flatten":51}],54:[function(require,module,exports){ /*! * ---------------------- * C3.js Adapter * ---------------------- */ var Dataviz = require('../dataviz'), each = require('../../core/utils/each'), extend = require('../../core/utils/extend'); getSetupTemplate = require('./c3/get-setup-template') module.exports = function(){ var dataTypes = { 'singular' : ['gauge'], 'categorical' : ['donut', 'pie'], 'cat-interval' : ['area-step', 'step', 'bar', 'area', 'area-spline', 'spline', 'line'], 'cat-ordinal' : ['bar', 'area', 'area-spline', 'spline', 'line', 'step', 'area-step'], 'chronological' : ['area', 'area-spline', 'spline', 'line', 'bar', 'step', 'area-step'], 'cat-chronological' : ['line', 'spline', 'area', 'area-spline', 'bar', 'step', 'area-step'] }; var charts = {}; each(['gauge', 'donut', 'pie', 'bar', 'area', 'area-spline', 'spline', 'line', 'step', 'area-step'], function(type, index){ charts[type] = { render: function(){ if (this.data()[0].length === 1 || this.data().length === 1) { this.error('No data to display'); return; } this.view._artifacts['c3'] = c3.generate(getSetupTemplate.call(this, type)); this.update(); }, update: function(){ var self = this, cols = []; if (type === 'gauge') { self.view._artifacts['c3'].load({ columns: [ [self.title(), self.data()[1][1]] ] }) } else if (type === 'pie' || type === 'donut') { self.view._artifacts['c3'].load({ columns: self.dataset.data.output.slice(1) }); } else { if (this.dataType().indexOf('chron') > -1) { cols.push(self.dataset.selectColumn(0)); cols[0][0] = 'x'; } each(self.data()[0], function(c, i){ if (i > 0) { cols.push(self.dataset.selectColumn(i)); } }); if (self.stacked()) { self.view._artifacts['c3'].groups([self.labels()]); } self.view._artifacts['c3'].load({ columns: cols }); } }, destroy: function(){ _selfDestruct.call(this); } }; }); function _selfDestruct(){ if (this.view._artifacts['c3']) { this.view._artifacts['c3'].destroy(); this.view._artifacts['c3'] = null; } } Dataviz.register('c3', charts, { capabilities: dataTypes }); }; },{"../../core/utils/each":31,"../../core/utils/extend":33,"../dataviz":59,"./c3/get-setup-template":55}],55:[function(require,module,exports){ var extend = require('../../../core/utils/extend'); var clone = require('../../../core/utils/clone'); module.exports = function (type) { var chartOptions = clone(this.chartOptions()); var setup = extend({ axis: {}, color: {}, data: {}, size: {} }, chartOptions); setup.bindto = this.el(); setup.color.pattern = this.colors(); setup.data.columns = []; setup.size.height = this.height(); setup.size.width = this.width(); setup['data']['type'] = type; if (type === 'gauge') {} else if (type === 'pie' || type === 'donut') { setup[type] = { title: this.title() }; } else { if (this.dataType().indexOf('chron') > -1) { setup['data']['x'] = 'x'; setup['axis']['x'] = setup['axis']['x'] || {}; setup['axis']['x']['type'] = 'timeseries'; setup['axis']['x']['tick'] = setup['axis']['x']['tick'] || { format: this.dateFormat() || getDateFormatDefault(this.data()[1][0], this.data()[2][0]) }; } else { if (this.dataType() === 'cat-ordinal') { setup['axis']['x'] = setup['axis']['x'] || {}; setup['axis']['x']['type'] = 'category'; setup['axis']['x']['categories'] = setup['axis']['x']['categories'] || this.labels() } } if (this.title()) { setup['axis']['y'] = { label: this.title() }; } } return setup; } function getDateFormatDefault(a, b){ var d = Math.abs(new Date(a).getTime() - new Date(b).getTime()); var months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec' ]; if (d >= 2419200000) { return function(ms){ var date = new Date(ms); return months[date.getMonth()] + ' ' + date.getFullYear(); }; } else if (d >= 86400000) { return function(ms){ var date = new Date(ms); return months[date.getMonth()] + ' ' + date.getDate(); }; } else if (d >= 3600000) { return '%I:%M %p'; } else { return '%I:%M:%S %p'; } } },{"../../../core/utils/clone":30,"../../../core/utils/extend":33}],56:[function(require,module,exports){ /*! * ---------------------- * Chart.js Adapter * ---------------------- */ var Dataviz = require("../dataviz"), each = require("../../core/utils/each"), extend = require("../../core/utils/extend"); module.exports = function(){ if (typeof Chart !== "undefined") { Chart.defaults.global.responsive = true; } var dataTypes = { "categorical" : ["doughnut", "pie", "polar-area", "radar"], "cat-interval" : ["bar", "line"], "cat-ordinal" : ["bar", "line"], "chronological" : ["line", "bar"], "cat-chronological" : ["line", "bar"] }; var ChartNameMap = { "radar": "Radar", "polar-area": "PolarArea", "pie": "Pie", "doughnut": "Doughnut", "line": "Line", "bar": "Bar" }; var dataTransformers = { 'doughnut': getCategoricalData, 'pie': getCategoricalData, 'polar-area': getCategoricalData, 'radar': getSeriesData, 'line': getSeriesData, 'bar': getSeriesData }; function getCategoricalData(){ var self = this, result = []; each(self.dataset.selectColumn(0).slice(1), function(label, i){ result.push({ value: self.dataset.selectColumn(1).slice(1)[i], color: self.colors()[+i], hightlight: self.colors()[+i+9], label: label }); }); return result; } function getSeriesData(){ var self = this, labels, result = { labels: [], datasets: [] }; labels = this.dataset.selectColumn(0).slice(1); each(labels, function(l,i){ if (l instanceof Date) { result.labels.push((l.getMonth()+1) + "-" + l.getDate() + "-" + l.getFullYear()); } else { result.labels.push(l); } }) each(self.dataset.selectRow(0).slice(1), function(label, i){ var hex = { r: hexToR(self.colors()[i]), g: hexToG(self.colors()[i]), b: hexToB(self.colors()[i]) }; result.datasets.push({ label: label, fillColor : "rgba(" + hex.r + "," + hex.g + "," + hex.b + ",0.2)", strokeColor : "rgba(" + hex.r + "," + hex.g + "," + hex.b + ",1)", pointColor : "rgba(" + hex.r + "," + hex.g + "," + hex.b + ",1)", pointStrokeColor: "#fff", pointHighlightFill: "#fff", pointHighlightStroke: "rgba(" + hex.r + "," + hex.g + "," + hex.b + ",1)", data: self.dataset.selectColumn(+i+1).slice(1) }); }); return result; } var charts = {}; each(["doughnut", "pie", "polar-area", "radar", "bar", "line"], function(type, index){ charts[type] = { initialize: function(){ if (this.data()[0].length === 1 || this.data().length === 1) { this.error('No data to display'); return; } if (this.el().nodeName.toLowerCase() !== "canvas") { var canvas = document.createElement('canvas'); this.el().innerHTML = ""; this.el().appendChild(canvas); this.view._artifacts["ctx"] = canvas.getContext("2d"); } else { this.view._artifacts["ctx"] = this.el().getContext("2d"); } if (this.height()) { this.view._artifacts["ctx"].canvas.height = this.height(); this.view._artifacts["ctx"].canvas.style.height = String(this.height() + "px"); } if (this.width()) { this.view._artifacts["ctx"].canvas.width = this.width(); this.view._artifacts["ctx"].canvas.style.width = String(this.width() + "px"); } return this; }, render: function(){ if(_isEmptyOutput(this.dataset)) { this.error("No data to display"); return; } var method = ChartNameMap[type], opts = extend({}, this.chartOptions()), data = dataTransformers[type].call(this); if (this.view._artifacts["chartjs"]) { this.view._artifacts["chartjs"].destroy(); } this.view._artifacts["chartjs"] = new Chart(this.view._artifacts["ctx"])[method](data, opts); return this; }, destroy: function(){ _selfDestruct.call(this); } }; }); function _selfDestruct(){ if (this.view._artifacts["chartjs"]) { this.view._artifacts["chartjs"].destroy(); this.view._artifacts["chartjs"] = null; } } function _isEmptyOutput(dataset) { var flattened = dataset.output().reduce(function(a, b) { return a.concat(b) }); return flattened.length === 0 } function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)} function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)} function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)} function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h} Dataviz.register("chartjs", charts, { capabilities: dataTypes }); }; },{"../../core/utils/each":31,"../../core/utils/extend":33,"../dataviz":59}],57:[function(require,module,exports){ /*! * ---------------------- * Google Charts Adapter * ---------------------- */ /* TODO: [ ] Build a more robust DataTable transformer [ ] ^Expose date parser for google charts tooltips (#70) [ ] ^Allow custom tooltips (#147) */ var Dataviz = require("../dataviz"), each = require("../../core/utils/each"), extend = require("../../core/utils/extend"), Keen = require("../../core"); module.exports = function(){ Keen.loaded = false; var errorMapping = { "Data column(s) for axis #0 cannot be of type string": "No results to visualize" }; var chartTypes = ['AreaChart', 'BarChart', 'ColumnChart', 'LineChart', 'PieChart', 'Table']; var chartMap = {}; var dataTypes = { 'categorical': ['piechart', 'barchart', 'columnchart', 'table'], 'cat-interval': ['columnchart', 'barchart', 'table'], 'cat-ordinal': ['barchart', 'columnchart', 'areachart', 'linechart', 'table'], 'chronological': ['areachart', 'linechart', 'table'], 'cat-chronological': ['linechart', 'columnchart', 'barchart', 'areachart'], 'nominal': ['table'], 'extraction': ['table'] }; each(chartTypes, function (type) { var name = type.toLowerCase(); chartMap[name] = { initialize: function(){ }, render: function(){ if(typeof google === "undefined") { this.error("The Google Charts library could not be loaded."); return; } var self = this; if (self.view._artifacts['googlechart']) { this.destroy(); } self.view._artifacts['googlechart'] = self.view._artifacts['googlechart'] || new google.visualization[type](self.el()); google.visualization.events.addListener(self.view._artifacts['googlechart'], 'error', function(stack){ _handleErrors.call(self, stack); }); this.update(); }, update: function(){ var options = _getDefaultAttributes.call(this, type); extend(options, this.chartOptions(), this.attributes()); options['isStacked'] = (this.stacked() || options['isStacked']); this.view._artifacts['datatable'] = google.visualization.arrayToDataTable(this.data()); if (options.dateFormat) { if (typeof options.dateFormat === 'function') { options.dateFormat(this.view._artifacts['datatable']); } else if (typeof options.dateFormat === 'string') { new google.visualization.DateFormat({ pattern: options.dateFormat }).format(this.view._artifacts['datatable'], 0); } } if (this.view._artifacts['googlechart']) { this.view._artifacts['googlechart'].draw(this.view._artifacts['datatable'], options); } }, destroy: function(){ if (this.view._artifacts['googlechart']) { google.visualization.events.removeAllListeners(this.view._artifacts['googlechart']); this.view._artifacts['googlechart'].clearChart(); this.view._artifacts['googlechart'] = null; this.view._artifacts['datatable'] = null; } } }; }); Dataviz.register('google', chartMap, { capabilities: dataTypes, dependencies: [{ type: 'script', url: 'https://www.google.com/jsapi', cb: function(done) { if (typeof google === 'undefined'){ this.trigger("error", "Problem loading Google Charts library. Please contact us!"); done(); } else { google.load('visualization', '1.1', { packages: ['corechart', 'table'], callback: function(){ done(); } }); } } }] }); function _handleErrors(stack){ var message = errorMapping[stack['message']] || stack['message'] || 'An error occurred'; this.error(message); } function _getDefaultAttributes(type){ var output = {}; switch (type.toLowerCase()) { case "areachart": output.lineWidth = 2; output.hAxis = { baselineColor: 'transparent', gridlines: { color: 'transparent' } }; output.vAxis = { viewWindow: { min: 0 } }; if (this.dataType() === "chronological" || this.dataType() === "cat-ordinal") { output.legend = "none"; output.chartArea = { width: "85%" }; } if (this.dateFormat() && typeof this.dateFormat() === 'string') { output.hAxis.format = this.dateFormat(); } break; case "barchart": output.hAxis = { viewWindow: { min: 0 } }; output.vAxis = { baselineColor: 'transparent', gridlines: { color: 'transparent' } }; if (this.dataType() === "chronological" || this.dataType() === "cat-ordinal") { output.legend = "none"; } if (this.dateFormat() && typeof this.dateFormat() === 'string') { output.vAxis.format = this.dateFormat(); } break; case "columnchart": output.hAxis = { baselineColor: 'transparent', gridlines: { color: 'transparent' } }; output.vAxis = { viewWindow: { min: 0 } }; if (this.dataType() === "chronological" || this.dataType() === "cat-ordinal") { output.legend = "none"; output.chartArea = { width: "85%" }; } if (this.dateFormat() && typeof this.dateFormat() === 'string') { output.hAxis.format = this.dateFormat(); } break; case "linechart": output.lineWidth = 2; output.hAxis = { baselineColor: 'transparent', gridlines: { color: 'transparent' } }; output.vAxis = { viewWindow: { min: 0 } }; if (this.dataType() === "chronological" || this.dataType() === "cat-ordinal") { output.legend = "none"; output.chartArea = { width: "85%" }; } if (this.dateFormat() && typeof this.dateFormat() === 'string') { output.hAxis.format = this.dateFormat(); } break; case "piechart": output.sliceVisibilityThreshold = 0.01; break; case "table": break; } return output; } }; },{"../../core":18,"../../core/utils/each":31,"../../core/utils/extend":33,"../dataviz":59}],58:[function(require,module,exports){ /*! * ---------------------- * Keen IO Adapter * ---------------------- */ var Keen = require("../../core"), Dataviz = require("../dataviz"); var clone = require("../../core/utils/clone"), each = require("../../core/utils/each"), extend = require("../../core/utils/extend"), prettyNumber = require("../utils/prettyNumber"); module.exports = function(){ var Metric, Error, Spinner; Keen.Error = { defaults: { backgroundColor : "", borderRadius : "4px", color : "#ccc", display : "block", fontFamily : "Helvetica Neue, Helvetica, Arial, sans-serif", fontSize : "21px", fontWeight : "light", textAlign : "center" } }; Keen.Spinner.defaults = { height: 138, lines: 10, length: 8, width: 3, radius: 10, corners: 1, rotate: 0, direction: 1, color: '#4d4d4d', speed: 1.67, trail: 60, shadow: false, hwaccel: false, className: 'keen-spinner', zIndex: 2e9, top: '50%', left: '50%' }; var dataTypes = { 'singular': ['metric'] }; Metric = { initialize: function(){ var css = document.createElement("style"), bgDefault = "#49c5b1"; css.id = "keen-widgets"; css.type = "text/css"; css.innerHTML = "\ .keen-metric { \n background: " + bgDefault + "; \n border-radius: 4px; \n color: #fff; \n font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; \n padding: 10px 0; \n text-align: center; \n} \ .keen-metric-value { \n display: block; \n font-size: 84px; \n font-weight: 700; \n line-height: 84px; \n} \ .keen-metric-title { \n display: block; \n font-size: 24px; \n font-weight: 200; \n}"; if (!document.getElementById(css.id)) { document.body.appendChild(css); } }, render: function(){ var bgColor = (this.colors().length == 1) ? this.colors()[0] : "#49c5b1", title = this.title() || "Result", value = (this.data()[1] && this.data()[1][1]) ? this.data()[1][1] : 0, width = this.width(), opts = this.chartOptions() || {}, prefix = "", suffix = ""; var styles = { 'width': (width) ? width + 'px' : 'auto' }; var formattedNum = value; if ( typeof opts.prettyNumber === 'undefined' || opts.prettyNumber == true ) { if ( !isNaN(parseInt(value)) ) { formattedNum = prettyNumber(value); } } if (opts['prefix']) { prefix = '<span class="keen-metric-prefix">' + opts['prefix'] + '</span>'; } if (opts['suffix']) { suffix = '<span class="keen-metric-suffix">' + opts['suffix'] + '</span>'; } this.el().innerHTML = '' + '<div class="keen-widget keen-metric" style="background-color: ' + bgColor + '; width:' + styles.width + ';" title="' + value + '">' + '<span class="keen-metric-value">' + prefix + formattedNum + suffix + '</span>' + '<span class="keen-metric-title">' + title + '</span>' + '</div>'; } }; Error = { initialize: function(){}, render: function(text, style){ var err, msg; var defaultStyle = clone(Keen.Error.defaults); var currentStyle = extend(defaultStyle, style); err = document.createElement("div"); err.className = "keen-error"; each(currentStyle, function(value, key){ err.style[key] = value; }); err.style.height = String(this.height() + "px"); err.style.paddingTop = (this.height() / 2 - 15) + "px"; err.style.width = String(this.width() + "px"); msg = document.createElement("span"); msg.innerHTML = text || "Yikes! An error occurred!"; err.appendChild(msg); this.el().innerHTML = ""; this.el().appendChild(err); }, destroy: function(){ this.el().innerHTML = ""; } }; Spinner = { initialize: function(){}, render: function(){ var spinner = document.createElement("div"); var height = this.height() || Keen.Spinner.defaults.height; spinner.className = "keen-loading"; spinner.style.height = String(height + "px"); spinner.style.position = "relative"; spinner.style.width = String(this.width() + "px"); this.el().innerHTML = ""; this.el().appendChild(spinner); this.view._artifacts.spinner = new Keen.Spinner(Keen.Spinner.defaults).spin(spinner); }, destroy: function(){ this.view._artifacts.spinner.stop(); this.view._artifacts.spinner = null; } }; Keen.Dataviz.register('keen-io', { 'metric': Metric, 'error': Error, 'spinner': Spinner }, { capabilities: dataTypes }); }; },{"../../core":18,"../../core/utils/clone":30,"../../core/utils/each":31,"../../core/utils/extend":33,"../dataviz":59,"../utils/prettyNumber":98}],59:[function(require,module,exports){ var clone = require('../core/utils/clone'), each = require('../core/utils/each'), extend = require('../core/utils/extend'), loadScript = require('./utils/loadScript'), loadStyle = require('./utils/loadStyle'); var Keen = require('../core'); var Emitter = require('../core/utils/emitter-shim'); var Dataset = require('../dataset'); function Dataviz(){ this.dataset = new Dataset(); this.view = { _prepared: false, _initialized: false, _rendered: false, _artifacts: { /* state bin */ }, adapter: { library: undefined, chartOptions: {}, chartType: undefined, defaultChartType: undefined, dataType: undefined }, attributes: clone(Dataviz.defaults), defaults: clone(Dataviz.defaults), el: undefined, loader: { library: 'keen-io', chartType: 'spinner' } }; Dataviz.visuals.push(this); }; extend(Dataviz, { dataTypeMap: { 'singular': { library: 'keen-io', chartType: 'metric' }, 'categorical': { library: 'google', chartType: 'piechart' }, 'cat-interval': { library: 'google', chartType: 'columnchart' }, 'cat-ordinal': { library: 'google', chartType: 'barchart' }, 'chronological': { library: 'google', chartType: 'areachart' }, 'cat-chronological': { library: 'google', chartType: 'linechart' }, 'extraction': { library: 'google', chartType: 'table' }, 'nominal': { library: 'google', chartType: 'table' } }, defaults: { colors: [ /* teal red yellow purple orange mint blue green lavender */ '#00bbde', '#fe6672', '#eeb058', '#8a8ad6', '#ff855c', '#00cfbb', '#5a9eed', '#73d483', '#c879bb', '#0099b6', '#d74d58', '#cb9141', '#6b6bb6', '#d86945', '#00aa99', '#4281c9', '#57b566', '#ac5c9e', '#27cceb', '#ff818b', '#f6bf71', '#9b9be1', '#ff9b79', '#26dfcd', '#73aff4', '#87e096', '#d88bcb' ], indexBy: 'timeframe.start', stacked: false }, dependencies: { loading: 0, loaded: 0, urls: {} }, libraries: {}, visuals: [] }); Emitter(Dataviz); Emitter(Dataviz.prototype); Dataviz.register = function(name, methods, config){ var self = this; var loadHandler = function(st) { st.loaded++; if(st.loaded === st.loading) { Keen.loaded = true; Keen.trigger('ready'); } }; Dataviz.libraries[name] = Dataviz.libraries[name] || {}; each(methods, function(method, key){ Dataviz.libraries[name][key] = method; }); if (config && config.capabilities) { Dataviz.libraries[name]._defaults = Dataviz.libraries[name]._defaults || {}; each(config.capabilities, function(typeSet, key){ Dataviz.libraries[name]._defaults[key] = typeSet; }); } if (config && config.dependencies) { each(config.dependencies, function (dependency, index, collection) { var status = Dataviz.dependencies; if(!status.urls[dependency.url]) { status.urls[dependency.url] = true; status.loading++; var method = dependency.type === 'script' ? loadScript : loadStyle; method(dependency.url, function() { if(dependency.cb) { dependency.cb.call(self, function() { loadHandler(status); }); } else { loadHandler(status); } }); } }); } }; Dataviz.find = function(target){ if (!arguments.length) return Dataviz.visuals; var el = target.nodeName ? target : document.querySelector(target), match; each(Dataviz.visuals, function(visual){ if (el == visual.el()){ match = visual; return false; } }); if (match) return match; }; module.exports = Dataviz; },{"../core":18,"../core/utils/clone":30,"../core/utils/each":31,"../core/utils/emitter-shim":32,"../core/utils/extend":33,"../dataset":39,"./utils/loadScript":96,"./utils/loadStyle":97}],60:[function(require,module,exports){ var clone = require("../../core/utils/clone"), extend = require("../../core/utils/extend"), Dataviz = require("../dataviz"), Request = require("../../core/request"); module.exports = function(query, el, cfg) { var DEFAULTS = clone(Dataviz.defaults), visual = new Dataviz(), request = new Request(this, [query]), config = cfg || {}; visual .attributes(extend(DEFAULTS, config)) .el(el) .prepare(); request.refresh(); request.on("complete", function(){ visual .parseRequest(this) .call(function(){ if (config.labels) { this.labels(config.labels); } }) .render(); }); request.on("error", function(res){ visual.error(res.message); }); return visual; }; },{"../../core/request":27,"../../core/utils/clone":30,"../../core/utils/extend":33,"../dataviz":59}],61:[function(require,module,exports){ var Dataviz = require("../dataviz"), extend = require("../../core/utils/extend") module.exports = function(){ var map = extend({}, Dataviz.dataTypeMap), dataType = this.dataType(), library = this.library(), chartType = this.chartType() || this.defaultChartType(); if (!library && map[dataType]) { library = map[dataType].library; } if (library && !chartType && dataType) { chartType = Dataviz.libraries[library]._defaults[dataType][0]; } if (library && !chartType && map[dataType]) { chartType = map[dataType].chartType; } if (library && chartType && Dataviz.libraries[library][chartType]) { return Dataviz.libraries[library][chartType]; } else { return {}; } }; },{"../../core/utils/extend":33,"../dataviz":59}],62:[function(require,module,exports){ module.exports = function(req){ var analysis = req.queries[0].analysis.replace("_", " "), collection = req.queries[0].get('event_collection'), output; output = analysis.replace( /\b./g, function(a){ return a.toUpperCase(); }); if (collection) { output += ' - ' + collection; } return output; }; },{}],63:[function(require,module,exports){ module.exports = function(query){ var isInterval = typeof query.params.interval === "string", isGroupBy = typeof query.params.group_by === "string", is2xGroupBy = query.params.group_by instanceof Array, dataType; if (!isGroupBy && !isInterval) { dataType = 'singular'; } if (isGroupBy && !isInterval) { dataType = 'categorical'; } if (isInterval && !isGroupBy) { dataType = 'chronological'; } if (isInterval && isGroupBy) { dataType = 'cat-chronological'; } if (!isInterval && is2xGroupBy) { dataType = 'categorical'; } if (isInterval && is2xGroupBy) { dataType = 'cat-chronological'; } if (query.analysis === "funnel") { dataType = 'cat-ordinal'; } if (query.analysis === "extraction") { dataType = 'extraction'; } if (query.analysis === "select_unique") { dataType = 'nominal'; } return dataType; }; },{}],64:[function(require,module,exports){ var extend = require('../core/utils/extend'), Dataviz = require('./dataviz'); extend(Dataviz.prototype, { 'adapter' : require('./lib/adapter'), 'attributes' : require('./lib/attributes'), 'call' : require('./lib/call'), 'chartOptions' : require('./lib/chartOptions'), 'chartType' : require('./lib/chartType'), 'colorMapping' : require('./lib/colorMapping'), 'colors' : require('./lib/colors'), 'data' : require('./lib/data'), 'dataType' : require('./lib/dataType'), 'dateFormat' : require('./lib/dateFormat'), 'defaultChartType' : require('./lib/defaultChartType'), 'el' : require('./lib/el'), 'height' : require('./lib/height'), 'indexBy' : require('./lib/indexBy'), 'labelMapping' : require('./lib/labelMapping'), 'labels' : require('./lib/labels'), 'library' : require('./lib/library'), 'parseRawData' : require('./lib/parseRawData'), 'parseRequest' : require('./lib/parseRequest'), 'prepare' : require('./lib/prepare'), 'sortGroups' : require('./lib/sortGroups'), 'sortIntervals' : require('./lib/sortIntervals'), 'stacked' : require('./lib/stacked'), 'title' : require('./lib/title'), 'width' : require('./lib/width') }); extend(Dataviz.prototype, { 'destroy' : require('./lib/actions/destroy'), 'error' : require('./lib/actions/error'), 'initialize' : require('./lib/actions/initialize'), 'render' : require('./lib/actions/render'), 'update' : require('./lib/actions/update') }); module.exports = Dataviz; },{"../core/utils/extend":33,"./dataviz":59,"./lib/actions/destroy":65,"./lib/actions/error":66,"./lib/actions/initialize":67,"./lib/actions/render":68,"./lib/actions/update":69,"./lib/adapter":70,"./lib/attributes":71,"./lib/call":72,"./lib/chartOptions":73,"./lib/chartType":74,"./lib/colorMapping":75,"./lib/colors":76,"./lib/data":77,"./lib/dataType":78,"./lib/dateFormat":79,"./lib/defaultChartType":80,"./lib/el":81,"./lib/height":82,"./lib/indexBy":83,"./lib/labelMapping":84,"./lib/labels":85,"./lib/library":86,"./lib/parseRawData":87,"./lib/parseRequest":88,"./lib/prepare":89,"./lib/sortGroups":90,"./lib/sortIntervals":91,"./lib/stacked":92,"./lib/title":93,"./lib/width":94}],65:[function(require,module,exports){ var getAdapterActions = require("../../helpers/getAdapterActions"); module.exports = function(){ var actions = getAdapterActions.call(this); if (actions.destroy) { actions.destroy.apply(this, arguments); } if (this.el()) { this.el().innerHTML = ""; } this.view._prepared = false; this.view._initialized = false; this.view._rendered = false; this.view._artifacts = {}; return this; }; },{"../../helpers/getAdapterActions":61}],66:[function(require,module,exports){ var getAdapterActions = require("../../helpers/getAdapterActions"), Dataviz = require("../../dataviz"); module.exports = function(){ var actions = getAdapterActions.call(this); if (this.el()) { if (actions['error']) { actions['error'].apply(this, arguments); } else { Dataviz.libraries['keen-io']['error'].render.apply(this, arguments); } } else { this.emit('error', 'No DOM element provided'); } return this; }; },{"../../dataviz":59,"../../helpers/getAdapterActions":61}],67:[function(require,module,exports){ var getAdapterActions = require("../../helpers/getAdapterActions"), Dataviz = require("../../dataviz"); module.exports = function(){ var actions = getAdapterActions.call(this); var loader = Dataviz.libraries[this.view.loader.library][this.view.loader.chartType]; if (this.view._prepared) { if (loader.destroy) loader.destroy.apply(this, arguments); } else { if (this.el()) this.el().innerHTML = ""; } if (actions.initialize) { actions.initialize.apply(this, arguments); } else { this.error('Incorrect chartType'); this.emit('error', 'Incorrect chartType'); } this.view._initialized = true; return this; }; },{"../../dataviz":59,"../../helpers/getAdapterActions":61}],68:[function(require,module,exports){ var getAdapterActions = require("../../helpers/getAdapterActions"), applyTransforms = require("../../utils/applyTransforms"); module.exports = function(){ var actions = getAdapterActions.call(this); applyTransforms.call(this); if (!this.view._initialized) { this.initialize(); } if (this.el() && actions.render) { actions.render.apply(this, arguments); this.view._rendered = true; } return this; }; },{"../../helpers/getAdapterActions":61,"../../utils/applyTransforms":95}],69:[function(require,module,exports){ var getAdapterActions = require("../../helpers/getAdapterActions"), applyTransforms = require("../../utils/applyTransforms"); module.exports = function(){ var actions = getAdapterActions.call(this); applyTransforms.call(this); if (actions.update) { actions.update.apply(this, arguments); } else if (actions.render) { this.render(); } return this; }; },{"../../helpers/getAdapterActions":61,"../../utils/applyTransforms":95}],70:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = function(obj){ if (!arguments.length) return this.view.adapter; var self = this; each(obj, function(prop, key){ self.view.adapter[key] = (prop ? prop : null); }); return this; }; },{"../../core/utils/each":31}],71:[function(require,module,exports){ var each = require("../../core/utils/each"); var chartOptions = require("./chartOptions") chartType = require("./chartType"), library = require("./library"); module.exports = function(obj){ if (!arguments.length) return this.view["attributes"]; var self = this; each(obj, function(prop, key){ if (key === "library") { library.call(self, prop); } else if (key === "chartType") { chartType.call(self, prop); } else if (key === "chartOptions") { chartOptions.call(self, prop); } else { self.view["attributes"][key] = prop; } }); return this; }; },{"../../core/utils/each":31,"./chartOptions":73,"./chartType":74,"./library":86}],72:[function(require,module,exports){ module.exports = function(fn){ fn.call(this); return this; }; },{}],73:[function(require,module,exports){ var extend = require('../../core/utils/extend'); module.exports = function(obj){ if (!arguments.length) return this.view.adapter.chartOptions; if (typeof obj === 'object' && obj !== null) { extend(this.view.adapter.chartOptions, obj); } else { this.view.adapter.chartOptions = {}; } return this; }; },{"../../core/utils/extend":33}],74:[function(require,module,exports){ module.exports = function(str){ if (!arguments.length) return this.view.adapter.chartType; this.view.adapter.chartType = (str ? String(str) : null); return this; }; },{}],75:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = function(obj){ if (!arguments.length) return this.view["attributes"].colorMapping; this.view["attributes"].colorMapping = (obj ? obj : null); colorMapping.call(this); return this; }; function colorMapping(){ var self = this, schema = this.dataset.schema, data = this.dataset.output(), colorSet = this.view.defaults.colors.slice(), colorMap = this.colorMapping(), dt = this.dataType() || ""; if (colorMap) { if (dt.indexOf("chronological") > -1 || (schema.unpack && data[0].length > 2)) { each(data[0].slice(1), function(label, i){ var color = colorMap[label]; if (color && colorSet[i] !== color) { colorSet.splice(i, 0, color); } }); } else { each(self.dataset.selectColumn(0).slice(1), function(label, i){ var color = colorMap[label]; if (color && colorSet[i] !== color) { colorSet.splice(i, 0, color); } }); } self.view.attributes.colors = colorSet; } } },{"../../core/utils/each":31}],76:[function(require,module,exports){ module.exports = function(arr){ if (!arguments.length) return this.view["attributes"].colors; this.view["attributes"].colors = (arr instanceof Array ? arr : null); this.view.defaults.colors = (arr instanceof Array ? arr : null); return this; }; },{}],77:[function(require,module,exports){ var Dataset = require("../../dataset"), Request = require("../../core/request"); module.exports = function(data){ if (!arguments.length) return this.dataset.output(); if (data instanceof Dataset) { this.dataset = data; } else if (data instanceof Request) { this.parseRequest(data); } else { this.parseRawData(data); } return this; }; },{"../../core/request":27,"../../dataset":39}],78:[function(require,module,exports){ module.exports = function(str){ if (!arguments.length) return this.view.adapter.dataType; this.view.adapter.dataType = (str ? String(str) : null); return this; }; },{}],79:[function(require,module,exports){ module.exports = function(val){ if (!arguments.length) return this.view.attributes.dateFormat; if (typeof val === 'string' || typeof val === 'function') { this.view.attributes.dateFormat = val; } else { this.view.attributes.dateFormat = undefined; } return this; }; },{}],80:[function(require,module,exports){ module.exports = function(str){ if (!arguments.length) return this.view.adapter.defaultChartType; this.view.adapter.defaultChartType = (str ? String(str) : null); return this; }; },{}],81:[function(require,module,exports){ module.exports = function(el){ if (!arguments.length) return this.view.el; this.view.el = el; return this; }; },{}],82:[function(require,module,exports){ module.exports = function(num){ if (!arguments.length) return this.view["attributes"]["height"]; this.view["attributes"]["height"] = (!isNaN(parseInt(num)) ? parseInt(num) : null); return this; }; },{}],83:[function(require,module,exports){ var Dataset = require('../../dataset'), Dataviz = require('../dataviz'), each = require('../../core/utils/each'); module.exports = function(str){ if (!arguments.length) return this.view['attributes'].indexBy; this.view['attributes'].indexBy = (str ? String(str) : Dataviz.defaults.indexBy); indexBy.call(this); return this; }; function indexBy(){ var parser, options; if (this.dataset.output().length > 1 && !isNaN(new Date(this.dataset.output()[1][0]).getTime())) { if (this.dataset.parser && this.dataset.parser.name && this.dataset.parser.options) { if (this.dataset.parser.options.length === 1) { parser = Dataset.parser(this.dataset.parser.name, this.indexBy()); this.dataset.parser.options[0] = this.indexBy(); } else { parser = Dataset.parser(this.dataset.parser.name, this.dataset.parser.options[0], this.indexBy()); this.dataset.parser.options[1] = this.indexBy(); } } else if (this.dataset.output()[0].length === 2) { parser = Dataset.parser('interval', this.indexBy()); this.dataset.parser = { name: 'interval', options: [this.indexBy()] }; } else { parser = Dataset.parser('grouped-interval', this.indexBy()); this.dataset.parser = { name: 'grouped-interval', options: [this.indexBy()] }; } this.dataset = parser(this.dataset.input()); this.dataset.updateColumn(0, function(value){ return (typeof value === 'string') ? new Date(value) : value; }); } } },{"../../core/utils/each":31,"../../dataset":39,"../dataviz":59}],84:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = function(obj){ if (!arguments.length) return this.view["attributes"].labelMapping; this.view["attributes"].labelMapping = (obj ? obj : null); applyLabelMapping.call(this); return this; }; function applyLabelMapping(){ var self = this, labelMap = this.labelMapping(), dt = this.dataType() || ""; if (labelMap) { if (dt.indexOf("chronological") > -1 || (self.dataset.output()[0].length > 2)) { each(self.dataset.output()[0], function(c, i){ if (i > 0) { self.dataset.data.output[0][i] = labelMap[c] || c; } }); } else if (self.dataset.output()[0].length === 2) { self.dataset.updateColumn(0, function(c, i){ return labelMap[c] || c; }); } } } },{"../../core/utils/each":31}],85:[function(require,module,exports){ var each = require('../../core/utils/each'); module.exports = function(arr){ if (!arguments.length) { if (!this.view['attributes'].labels || !this.view['attributes'].labels.length) { return getLabels.call(this); } else { return this.view['attributes'].labels; } } else { this.view['attributes'].labels = (arr instanceof Array ? arr : null); setLabels.call(this); return this; } }; function setLabels(){ var self = this, labelSet = this.labels() || null, data = this.dataset.output(), dt = this.dataType() || ''; if (labelSet) { if (dt.indexOf('chronological') > -1 || (data[0].length > 2)) { each(data[0], function(cell,i){ if (i > 0 && labelSet[i-1]) { self.dataset.data.output[0][i] = labelSet[i-1]; } }); } else { each(data, function(row,i){ if (i > 0 && labelSet[i-1]) { self.dataset.data.output[i][0] = labelSet[i-1]; } }); } } } function getLabels(){ var data = this.dataset.output(), dt = this.dataType() || '', labels; if (dt.indexOf('chron') > -1 || (data[0].length > 2)) { labels = this.dataset.selectRow(0).slice(1); } else { labels = this.dataset.selectColumn(0).slice(1); } return labels; } },{"../../core/utils/each":31}],86:[function(require,module,exports){ module.exports = function(str){ if (!arguments.length) return this.view.adapter.library; this.view.adapter.library = (str ? String(str) : null); return this; }; },{}],87:[function(require,module,exports){ var Dataset = require('../../dataset'); var extend = require('../../core/utils/extend'); module.exports = function(response){ var dataType, indexBy = this.indexBy() ? this.indexBy() : 'timestamp.start', parser, parserArgs = [], query = (typeof response.query !== 'undefined') ? response.query : {}; query = extend({ analysis_type: null, event_collection: null, filters: [], group_by: null, interval: null, timeframe: null, timezone: null }, query); if (query.analysis_type === 'funnel') { dataType = 'cat-ordinal'; parser = 'funnel'; } else if (query.analysis_type === 'extraction'){ dataType = 'extraction'; parser = 'extraction'; } else if (query.analysis_type === 'select_unique') { if (!query.group_by && !query.interval) { dataType = 'nominal'; parser = 'list'; } } else if (query.analysis_type) { if (!query.group_by && !query.interval) { dataType = 'singular'; parser = 'metric'; } else if (query.group_by && !query.interval) { if (query.group_by instanceof Array && query.group_by.length > 1) { dataType = 'categorical'; parser = 'double-grouped-metric'; parserArgs.push(query.group_by); } else { dataType = 'categorical'; parser = 'grouped-metric'; } } else if (query.interval && !query.group_by) { dataType = 'chronological'; parser = 'interval'; parserArgs.push(indexBy); } else if (query.group_by && query.interval) { if (query.group_by instanceof Array && query.group_by.length > 1) { dataType = 'cat-chronological'; parser = 'double-grouped-interval'; parserArgs.push(query.group_by); parserArgs.push(indexBy); } else { dataType = 'cat-chronological'; parser = 'grouped-interval'; parserArgs.push(indexBy); } } } if (!parser) { if (typeof response.result === 'number'){ dataType = 'singular'; parser = 'metric'; } if (response.result instanceof Array && response.result.length > 0){ if (response.result[0].timeframe && (typeof response.result[0].value == 'number' || response.result[0].value == null)) { dataType = 'chronological'; parser = 'interval'; parserArgs.push(indexBy) } if (typeof response.result[0].result == 'number'){ dataType = 'categorical'; parser = 'grouped-metric'; } if (response.result[0].value instanceof Array){ dataType = 'cat-chronological'; parser = 'grouped-interval'; parserArgs.push(indexBy) } if (typeof response.result[0] == 'number' && typeof response.steps !== "undefined"){ dataType = 'cat-ordinal'; parser = 'funnel'; } if ((typeof response.result[0] == 'string' || typeof response.result[0] == 'number') && typeof response.steps === "undefined"){ dataType = 'nominal'; parser = 'list'; } if (dataType === void 0) { dataType = 'extraction'; parser = 'extraction'; } } } if (dataType) { this.dataType(dataType); } this.dataset = Dataset.parser.apply(this, [parser].concat(parserArgs))(response); if (parser.indexOf('interval') > -1) { this.dataset.updateColumn(0, function(value, i){ return new Date(value); }); } return this; }; },{"../../core/utils/extend":33,"../../dataset":39}],88:[function(require,module,exports){ var Query = require('../../core/query'); var dataType = require('./dataType'), extend = require('../../core/utils/extend'), getDefaultTitle = require('../helpers/getDefaultTitle'), getQueryDataType = require('../helpers/getQueryDataType'), parseRawData = require('./parseRawData'), title = require('./title'); module.exports = function(req){ var response = req.data instanceof Array ? req.data[0] : req.data; if (req.queries[0] instanceof Query) { response.query = extend({ analysis_type: req.queries[0].analysis }, req.queries[0].params); dataType.call(this, getQueryDataType(req.queries[0])); this.view.defaults.title = getDefaultTitle.call(this, req); if (!title.call(this)) { title.call(this, this.view.defaults.title); } } parseRawData.call(this, response); return this; }; },{"../../core/query":26,"../../core/utils/extend":33,"../helpers/getDefaultTitle":62,"../helpers/getQueryDataType":63,"./dataType":78,"./parseRawData":87,"./title":93}],89:[function(require,module,exports){ var Dataviz = require("../dataviz"); module.exports = function(){ var loader; if (this.view._rendered) { this.destroy(); } if (this.el()) { this.el().innerHTML = ""; loader = Dataviz.libraries[this.view.loader.library][this.view.loader.chartType]; if (loader.initialize) { loader.initialize.apply(this, arguments); } if (loader.render) { loader.render.apply(this, arguments); } this.view._prepared = true; } return this; }; },{"../dataviz":59}],90:[function(require,module,exports){ module.exports = function(str){ if (!arguments.length) return this.view["attributes"].sortGroups; this.view["attributes"].sortGroups = (str ? String(str) : null); runSortGroups.call(this); return this; }; function runSortGroups(){ var dt = this.dataType(); if (!this.sortGroups()) return; if ((dt && dt.indexOf("chronological") > -1) || this.data()[0].length > 2) { this.dataset.sortColumns(this.sortGroups(), this.dataset.getColumnSum); } else if (dt && (dt.indexOf("cat-") > -1 || dt.indexOf("categorical") > -1)) { this.dataset.sortRows(this.sortGroups(), this.dataset.getRowSum); } return; } },{}],91:[function(require,module,exports){ module.exports = function(str){ if (!arguments.length) return this.view["attributes"].sortIntervals; this.view["attributes"].sortIntervals = (str ? String(str) : null); runSortIntervals.call(this); return this; }; function runSortIntervals(){ if (!this.sortIntervals()) return; this.dataset.sortRows(this.sortIntervals()); return; } },{}],92:[function(require,module,exports){ module.exports = function(bool){ if (!arguments.length) return this.view['attributes']['stacked']; this.view['attributes']['stacked'] = bool ? true : false; return this; }; },{}],93:[function(require,module,exports){ module.exports = function(str){ if (!arguments.length) return this.view["attributes"]["title"]; this.view["attributes"]["title"] = (str ? String(str) : null); return this; }; },{}],94:[function(require,module,exports){ module.exports = function(num){ if (!arguments.length) return this.view["attributes"]["width"]; this.view["attributes"]["width"] = (!isNaN(parseInt(num)) ? parseInt(num) : null); return this; }; },{}],95:[function(require,module,exports){ module.exports = function(){ if (this.labelMapping()) { this.labelMapping(this.labelMapping()); } if (this.colorMapping()) { this.colorMapping(this.colorMapping()); } if (this.sortGroups()) { this.sortGroups(this.sortGroups()); } if (this.sortIntervals()) { this.sortIntervals(this.sortIntervals()); } }; },{}],96:[function(require,module,exports){ module.exports = function(url, cb) { var doc = document; var handler; var head = doc.head || doc.getElementsByTagName("head"); setTimeout(function () { if ('item' in head) { if (!head[0]) { setTimeout(arguments.callee, 25); return; } head = head[0]; } var script = doc.createElement("script"), scriptdone = false; script.onload = script.onreadystatechange = function () { if ((script.readyState && script.readyState !== "complete" && script.readyState !== "loaded") || scriptdone) { return false; } script.onload = script.onreadystatechange = null; scriptdone = true; cb(); }; script.src = url; head.insertBefore(script, head.firstChild); }, 0); if (doc.readyState === null && doc.addEventListener) { doc.readyState = "loading"; doc.addEventListener("DOMContentLoaded", handler = function () { doc.removeEventListener("DOMContentLoaded", handler, false); doc.readyState = "complete"; }, false); } }; },{}],97:[function(require,module,exports){ module.exports = function(url, cb) { var link = document.createElement('link'); link.setAttribute('rel', 'stylesheet'); link.type = 'text/css'; link.href = url; cb(); document.head.appendChild(link); }; },{}],98:[function(require,module,exports){ module.exports = function(_input) { var input = Number(_input), sciNo = input.toPrecision(3), prefix = "", suffixes = ["", "k", "M", "B", "T"]; if (Number(sciNo) == input && String(input).length <= 4) { return String(input); } if(input >= 1 || input <= -1) { if(input < 0){ input = -input; prefix = "-"; } return prefix + recurse(input, 0); } else { return input.toPrecision(3); } function recurse(input, iteration) { var input = String(input); var split = input.split("."); if(split.length > 1) { input = split[0]; var rhs = split[1]; if (input.length == 2 && rhs.length > 0) { if (rhs.length > 0) { input = input + "." + rhs.charAt(0); } else { input += "0"; } } else if (input.length == 1 && rhs.length > 0) { input = input + "." + rhs.charAt(0); if(rhs.length > 1) { input += rhs.charAt(1); } else { input += "0"; } } } var numNumerals = input.length; if (input.split(".").length > 1) { numNumerals--; } if(numNumerals <= 3) { return String(input) + suffixes[iteration]; } else { return recurse(Number(input) / 1000, iteration + 1); } } }; },{}],99:[function(require,module,exports){ (function (global){ ;(function (f) { if (typeof define === "function" && define.amd) { define("keen", [], function(){ return f(); }); } if (typeof exports === "object" && typeof module !== "undefined") { module.exports = f(); } var g = null; if (typeof window !== "undefined") { g = window; } else if (typeof global !== "undefined") { g = global; } else if (typeof self !== "undefined") { g = self; } if (g) { g.Keen = f(); } })(function() { "use strict"; var Keen = require("./core"), extend = require("./core/utils/extend"); extend(Keen.prototype, { "addEvent" : require("./core/lib/addEvent"), "addEvents" : require("./core/lib/addEvents"), "setGlobalProperties" : require("./core/lib/setGlobalProperties"), "trackExternalLink" : require("./core/lib/trackExternalLink"), "get" : require("./core/lib/get"), "post" : require("./core/lib/post"), "put" : require("./core/lib/post"), "run" : require("./core/lib/run"), "savedQueries" : require("./core/saved-queries"), "draw" : require("./dataviz/extensions/draw") }); Keen.Query = require("./core/query"); Keen.Request = require("./core/request"); Keen.Dataset = require("./dataset"); Keen.Dataviz = require("./dataviz"); Keen.Base64 = require("./core/utils/base64"); Keen.Spinner = require("spin.js"); Keen.utils = { "domready" : require("domready"), "each" : require("./core/utils/each"), "extend" : extend, "parseParams" : require("./core/utils/parseParams"), "prettyNumber" : require("./dataviz/utils/prettyNumber") }; require("./dataviz/adapters/keen-io")(); require("./dataviz/adapters/google")(); require("./dataviz/adapters/c3")(); require("./dataviz/adapters/chartjs")(); if (Keen.loaded) { setTimeout(function(){ Keen.utils.domready(function(){ Keen.emit("ready"); }); }, 0); } require("./core/async")(); module.exports = Keen; return Keen; }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./core":18,"./core/async":10,"./core/lib/addEvent":19,"./core/lib/addEvents":20,"./core/lib/get":21,"./core/lib/post":22,"./core/lib/run":23,"./core/lib/setGlobalProperties":24,"./core/lib/trackExternalLink":25,"./core/query":26,"./core/request":27,"./core/saved-queries":28,"./core/utils/base64":29,"./core/utils/each":31,"./core/utils/extend":33,"./core/utils/parseParams":35,"./dataset":39,"./dataviz":64,"./dataviz/adapters/c3":54,"./dataviz/adapters/chartjs":56,"./dataviz/adapters/google":57,"./dataviz/adapters/keen-io":58,"./dataviz/extensions/draw":60,"./dataviz/utils/prettyNumber":98,"domready":2,"spin.js":5}]},{},[99]);
VectorCanvas.prototype.createPath = function (config) { var node; if (this.mode === 'svg') { node = this.createSvgNode('path'); node.setAttribute('d', config.path); if (this.params.borderColor !== null) { node.setAttribute('stroke', this.params.borderColor); } if (this.params.borderWidth > 0) { node.setAttribute('stroke-width', this.params.borderWidth); node.setAttribute('stroke-linecap', 'round'); node.setAttribute('stroke-linejoin', 'round'); } if (this.params.borderOpacity > 0) { node.setAttribute('stroke-opacity', this.params.borderOpacity); } node.setFill = function (color) { this.setAttribute('fill', color); if (this.getAttribute('original') === null) { this.setAttribute('original', color); } }; node.getFill = function () { return this.getAttribute('fill'); }; node.getOriginalFill = function () { return this.getAttribute('original'); }; node.setOpacity = function (opacity) { this.setAttribute('fill-opacity', opacity); }; } else { node = this.createVmlNode('shape'); node.coordorigin = '0 0'; node.coordsize = this.width + ' ' + this.height; node.style.width = this.width + 'px'; node.style.height = this.height + 'px'; node.fillcolor = JQVMap.defaultFillColor; node.stroked = false; node.path = VectorCanvas.pathSvgToVml(config.path); var scale = this.createVmlNode('skew'); scale.on = true; scale.matrix = '0.01,0,0,0.01,0,0'; scale.offset = '0,0'; node.appendChild(scale); var fill = this.createVmlNode('fill'); node.appendChild(fill); node.setFill = function (color) { this.getElementsByTagName('fill')[0].color = color; if (this.getAttribute('original') === null) { this.setAttribute('original', color); } }; node.getFill = function () { return this.getElementsByTagName('fill')[0].color; }; node.getOriginalFill = function () { return this.getAttribute('original'); }; node.setOpacity = function (opacity) { this.getElementsByTagName('fill')[0].opacity = parseInt(opacity * 100, 10) + '%'; }; } return node; };
/** * jQuery plugin wrapper for TinySort * Does not use the first argument in tinysort.js since that is handled internally by the jQuery selector. * Sub-selections (option.selector) do not use the jQuery selector syntax but regular CSS3 selector syntax. * @summary jQuery plugin wrapper for TinySort * @version 2.2.2 * @requires tinysort * @license MIT/GPL * @author Ron Valstar (http://www.sjeiti.com/) * @copyright Ron Valstar <[email protected]> */ !function(a){"use strict";"function"==typeof define&&define.amd?define(["jquery","tinysort"],a):jQuery&&!jQuery.fn.tsort&&a(jQuery,tinysort)}(function(a,b){"use strict";a.tinysort={defaults:b.defaults},a.fn.extend({tinysort:function(){var a,c,d=Array.prototype.slice.call(arguments);d.unshift(this),a=b.apply(null,d),c=a.length;for(var e=0,f=this.length;f>e;e++)c>e?this[e]=a[e]:delete this[e];return this.length=c,this}}),a.fn.tsort=a.fn.tinysort});
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. goog.provide('goog.ui.SubMenuTest'); goog.setTestOnly('goog.ui.SubMenuTest'); goog.require('goog.a11y.aria'); goog.require('goog.a11y.aria.State'); goog.require('goog.dom'); goog.require('goog.dom.classlist'); goog.require('goog.events'); goog.require('goog.events.Event'); goog.require('goog.events.KeyCodes'); goog.require('goog.events.KeyHandler'); goog.require('goog.functions'); goog.require('goog.positioning'); goog.require('goog.positioning.Overflow'); goog.require('goog.style'); goog.require('goog.testing.MockClock'); goog.require('goog.testing.events'); goog.require('goog.testing.jsunit'); goog.require('goog.ui.Component'); goog.require('goog.ui.Menu'); goog.require('goog.ui.MenuItem'); goog.require('goog.ui.SubMenu'); goog.require('goog.ui.SubMenuRenderer'); var menu; var clonedMenuDom; var mockClock; // mock out goog.positioning.positionAtCoordinate so that // the menu always fits. (we don't care about testing the // dynamic menu positioning if the menu doesn't fit in the window.) var oldPositionFn = goog.positioning.positionAtCoordinate; goog.positioning.positionAtCoordinate = function( absolutePos, movableElement, movableElementCorner, opt_margin, opt_overflow) { return oldPositionFn.call( null, absolutePos, movableElement, movableElementCorner, opt_margin, goog.positioning.Overflow.IGNORE); }; function setUp() { clonedMenuDom = goog.dom.getElement('demoMenu').cloneNode(true); menu = new goog.ui.Menu(); } function tearDown() { document.body.style.direction = 'ltr'; menu.dispose(); var element = goog.dom.getElement('demoMenu'); element.parentNode.replaceChild(clonedMenuDom, element); goog.dom.removeChildren(goog.dom.getElement('sandbox')); if (mockClock) { mockClock.uninstall(); mockClock = null; } } function assertKeyHandlingIsCorrect(keyToOpenSubMenu, keyToCloseSubMenu) { menu.setFocusable(true); menu.decorate(goog.dom.getElement('demoMenu')); var KeyCodes = goog.events.KeyCodes; var plainItem = menu.getChildAt(0); plainItem.setMnemonic(KeyCodes.F); var subMenuItem1 = menu.getChildAt(1); subMenuItem1.setMnemonic(KeyCodes.S); var subMenuItem1Menu = subMenuItem1.getMenu(); menu.setHighlighted(plainItem); var fireKeySequence = goog.testing.events.fireKeySequence; assertTrue( 'Expected OpenSubMenu key to not be handled', fireKeySequence(plainItem.getElement(), keyToOpenSubMenu)); assertFalse(subMenuItem1Menu.isVisible()); assertFalse( 'Expected F key to be handled', fireKeySequence(plainItem.getElement(), KeyCodes.F)); assertFalse( 'Expected DOWN key to be handled', fireKeySequence(plainItem.getElement(), KeyCodes.DOWN)); assertEquals(subMenuItem1, menu.getChildAt(1)); assertFalse( 'Expected OpenSubMenu key to be handled', fireKeySequence(subMenuItem1.getElement(), keyToOpenSubMenu)); assertTrue(subMenuItem1Menu.isVisible()); assertFalse( 'Expected CloseSubMenu key to be handled', fireKeySequence(subMenuItem1.getElement(), keyToCloseSubMenu)); assertFalse(subMenuItem1Menu.isVisible()); assertFalse( 'Expected UP key to be handled', fireKeySequence(subMenuItem1.getElement(), KeyCodes.UP)); assertFalse( 'Expected S key to be handled', fireKeySequence(plainItem.getElement(), KeyCodes.S)); assertTrue(subMenuItem1Menu.isVisible()); } function testKeyHandling_ltr() { assertKeyHandlingIsCorrect( goog.events.KeyCodes.RIGHT, goog.events.KeyCodes.LEFT); } function testKeyHandling_rtl() { document.body.style.direction = 'rtl'; assertKeyHandlingIsCorrect( goog.events.KeyCodes.LEFT, goog.events.KeyCodes.RIGHT); } function testNormalLtrSubMenu() { menu.decorate(goog.dom.getElement('demoMenu')); var subMenu = menu.getChildAt(1); assertArrowDirection(subMenu, false); assertRenderDirection(subMenu, false); assertArrowPosition(subMenu, false); } function testNormalRtlSubMenu() { document.body.style.direction = 'rtl'; menu.decorate(goog.dom.getElement('demoMenu')); var subMenu = menu.getChildAt(1); assertArrowDirection(subMenu, true); assertRenderDirection(subMenu, true); assertArrowPosition(subMenu, true); } function testLtrSubMenuAlignedToStart() { menu.decorate(goog.dom.getElement('demoMenu')); var subMenu = menu.getChildAt(1); subMenu.setAlignToEnd(false); assertArrowDirection(subMenu, true); assertRenderDirection(subMenu, true); assertArrowPosition(subMenu, false); } function testNullContentElement() { var subMenu = new goog.ui.SubMenu(); subMenu.setContent('demo'); } function testRtlSubMenuAlignedToStart() { document.body.style.direction = 'rtl'; menu.decorate(goog.dom.getElement('demoMenu')); var subMenu = menu.getChildAt(1); subMenu.setAlignToEnd(false); assertArrowDirection(subMenu, false); assertRenderDirection(subMenu, false); assertArrowPosition(subMenu, true); } function testSetContentKeepsArrow_ltr() { document.body.style.direction = 'ltr'; menu.decorate(goog.dom.getElement('demoMenu')); var subMenu = menu.getChildAt(1); subMenu.setAlignToEnd(false); subMenu.setContent('test'); assertArrowDirection(subMenu, true); assertRenderDirection(subMenu, true); assertArrowPosition(subMenu, false); } function testSetContentKeepsArrow_rtl() { document.body.style.direction = 'rtl'; menu.decorate(goog.dom.getElement('demoMenu')); var subMenu = menu.getChildAt(1); subMenu.setAlignToEnd(false); subMenu.setContent('test'); assertArrowDirection(subMenu, false); assertRenderDirection(subMenu, false); assertArrowPosition(subMenu, true); } function testExitDocument() { menu.decorate(goog.dom.getElement('demoMenu')); var subMenu = menu.getChildAt(1); var innerMenu = subMenu.getMenu(); assertTrue('Top-level menu was not in document', menu.isInDocument()); assertTrue('Submenu was not in document', subMenu.isInDocument()); assertTrue('Inner menu was not in document', innerMenu.isInDocument()); menu.exitDocument(); assertFalse('Top-level menu was in document', menu.isInDocument()); assertFalse('Submenu was in document', subMenu.isInDocument()); assertFalse('Inner menu was in document', innerMenu.isInDocument()); } function testDisposal() { menu.decorate(goog.dom.getElement('demoMenu')); var subMenu = menu.getChildAt(1); var innerMenu = subMenu.getMenu(); menu.dispose(); assert('Top-level menu was not disposed', menu.getDisposed()); assert('Submenu was not disposed', subMenu.getDisposed()); assert('Inner menu was not disposed', innerMenu.getDisposed()); } function testShowAndDismissSubMenu() { var openEventDispatched = false; var closeEventDispatched = false; function handleEvent(e) { switch (e.type) { case goog.ui.Component.EventType.OPEN: openEventDispatched = true; break; case goog.ui.Component.EventType.CLOSE: closeEventDispatched = true; break; default: fail('Invalid event type: ' + e.type); } } menu.decorate(goog.dom.getElement('demoMenu')); var subMenu = menu.getChildAt(1); subMenu.setHighlighted(true); goog.events.listen( subMenu, [goog.ui.Component.EventType.OPEN, goog.ui.Component.EventType.CLOSE], handleEvent); assertFalse( 'Submenu must not have "-open" CSS class', goog.dom.classlist.contains(subMenu.getElement(), 'goog-submenu-open')); assertFalse('Popup menu must not be visible', subMenu.getMenu().isVisible()); assertFalse('No OPEN event must have been dispatched', openEventDispatched); assertFalse('No CLOSE event must have been dispatched', closeEventDispatched); subMenu.showSubMenu(); assertTrue( 'Submenu must have "-open" CSS class', goog.dom.classlist.contains(subMenu.getElement(), 'goog-submenu-open')); assertTrue('Popup menu must be visible', subMenu.getMenu().isVisible()); assertTrue('OPEN event must have been dispatched', openEventDispatched); assertFalse('No CLOSE event must have been dispatched', closeEventDispatched); subMenu.dismissSubMenu(); assertFalse( 'Submenu must not have "-open" CSS class', goog.dom.classlist.contains(subMenu.getElement(), 'goog-submenu-open')); assertFalse('Popup menu must not be visible', subMenu.getMenu().isVisible()); assertTrue('CLOSE event must have been dispatched', closeEventDispatched); goog.events.unlisten( subMenu, [goog.ui.Component.EventType.OPEN, goog.ui.Component.EventType.CLOSE], handleEvent); } function testDismissWhenSubMenuNotVisible() { var openEventDispatched = false; var closeEventDispatched = false; function handleEvent(e) { switch (e.type) { case goog.ui.Component.EventType.OPEN: openEventDispatched = true; break; case goog.ui.Component.EventType.CLOSE: closeEventDispatched = true; break; default: fail('Invalid event type: ' + e.type); } } menu.decorate(goog.dom.getElement('demoMenu')); var subMenu = menu.getChildAt(1); subMenu.setHighlighted(true); goog.events.listen( subMenu, [goog.ui.Component.EventType.OPEN, goog.ui.Component.EventType.CLOSE], handleEvent); assertFalse( 'Submenu must not have "-open" CSS class', goog.dom.classlist.contains(subMenu.getElement(), 'goog-submenu-open')); assertFalse('Popup menu must not be visible', subMenu.getMenu().isVisible()); assertFalse('No OPEN event must have been dispatched', openEventDispatched); assertFalse('No CLOSE event must have been dispatched', closeEventDispatched); subMenu.showSubMenu(); subMenu.getMenu().setVisible(false); subMenu.dismissSubMenu(); assertFalse( 'Submenu must not have "-open" CSS class', goog.dom.classlist.contains(subMenu.getElement(), 'goog-submenu-open')); assertFalse(subMenu.menuIsVisible_); assertFalse('Popup menu must not be visible', subMenu.getMenu().isVisible()); assertTrue('CLOSE event must have been dispatched', closeEventDispatched); goog.events.unlisten( subMenu, [goog.ui.Component.EventType.OPEN, goog.ui.Component.EventType.CLOSE], handleEvent); } function testCloseSubMenuBehavior() { menu.decorate(goog.dom.getElement('demoMenu')); var subMenu = menu.getChildAt(1); subMenu.getElement().id = 'subMenu'; var innerMenu = subMenu.getMenu(); innerMenu.getChildAt(0).getElement().id = 'child1'; subMenu.setHighlighted(true); subMenu.showSubMenu(); function MyFakeEvent(keyCode, opt_eventType) { this.type = opt_eventType || goog.events.KeyHandler.EventType.KEY; this.keyCode = keyCode; this.propagationStopped = false; this.preventDefault = goog.nullFunction; this.stopPropagation = function() { this.propagationStopped = true; }; } // Focus on the first item in the submenu and verify the activedescendant is // set correctly. subMenu.handleKeyEvent(new MyFakeEvent(goog.events.KeyCodes.DOWN)); assertEquals( 'First item in submenu must be the aria-activedescendant', 'child1', goog.a11y.aria.getState( menu.getElement(), goog.a11y.aria.State.ACTIVEDESCENDANT)); // Dismiss the submenu and verify the activedescendant is updated correctly. subMenu.handleKeyEvent(new MyFakeEvent(goog.events.KeyCodes.LEFT)); assertEquals( 'Submenu must be the aria-activedescendant', 'subMenu', goog.a11y.aria.getState( menu.getElement(), goog.a11y.aria.State.ACTIVEDESCENDANT)); } function testLazyInstantiateSubMenu() { menu.decorate(goog.dom.getElement('demoMenu')); var subMenu = menu.getChildAt(1); subMenu.setHighlighted(true); var lazyMenu; var key = goog.events.listen( subMenu, goog.ui.Component.EventType.OPEN, function(e) { lazyMenu = new goog.ui.Menu(); lazyMenu.addItem(new goog.ui.MenuItem('foo')); lazyMenu.addItem(new goog.ui.MenuItem('bar')); subMenu.setMenu(lazyMenu, /* opt_internal */ false); }); subMenu.showSubMenu(); assertNotNull('Popup menu must have been created', lazyMenu); assertEquals( 'Popup menu must be a child of the submenu', subMenu, lazyMenu.getParent()); assertTrue('Popup menu must have been rendered', lazyMenu.isInDocument()); assertTrue('Popup menu must be visible', lazyMenu.isVisible()); menu.dispose(); assertTrue('Submenu must have been disposed of', subMenu.isDisposed()); assertFalse( 'Popup menu must not have been disposed of', lazyMenu.isDisposed()); lazyMenu.dispose(); goog.events.unlistenByKey(key); } function testReusableMenu() { var subMenuOne = new goog.ui.SubMenu('SubMenu One'); var subMenuTwo = new goog.ui.SubMenu('SubMenu Two'); menu.addItem(subMenuOne); menu.addItem(subMenuTwo); menu.render(goog.dom.getElement('sandbox')); // It is possible for the same popup menu to be shared between different // submenus. var sharedMenu = new goog.ui.Menu(); sharedMenu.addItem(new goog.ui.MenuItem('Hello')); sharedMenu.addItem(new goog.ui.MenuItem('World')); assertNull('Shared menu must not have a parent', sharedMenu.getParent()); subMenuOne.setMenu(sharedMenu); assertEquals( 'SubMenuOne must point to the shared menu', sharedMenu, subMenuOne.getMenu()); assertEquals( 'SubMenuOne must be the shared menu\'s parent', subMenuOne, sharedMenu.getParent()); subMenuTwo.setMenu(sharedMenu); assertEquals( 'SubMenuTwo must point to the shared menu', sharedMenu, subMenuTwo.getMenu()); assertEquals( 'SubMenuTwo must be the shared menu\'s parent', subMenuTwo, sharedMenu.getParent()); assertEquals( 'SubMenuOne must still point to the shared menu', sharedMenu, subMenuOne.getMenu()); menu.setHighlighted(subMenuOne); subMenuOne.showSubMenu(); assertEquals( 'SubMenuOne must point to the shared menu', sharedMenu, subMenuOne.getMenu()); assertEquals( 'SubMenuOne must be the shared menu\'s parent', subMenuOne, sharedMenu.getParent()); assertEquals( 'SubMenuTwo must still point to the shared menu', sharedMenu, subMenuTwo.getMenu()); assertTrue('Shared menu must be visible', sharedMenu.isVisible()); menu.setHighlighted(subMenuTwo); subMenuTwo.showSubMenu(); assertEquals( 'SubMenuTwo must point to the shared menu', sharedMenu, subMenuTwo.getMenu()); assertEquals( 'SubMenuTwo must be the shared menu\'s parent', subMenuTwo, sharedMenu.getParent()); assertEquals( 'SubMenuOne must still point to the shared menu', sharedMenu, subMenuOne.getMenu()); assertTrue('Shared menu must be visible', sharedMenu.isVisible()); } /** * If you remove a submenu in the interval between when a mouseover event * is fired on it, and showSubMenu() is called, showSubMenu causes a null * value to be dereferenced. This test validates that the fix for this works. * (See bug 1823144). */ function testDeleteItemDuringSubmenuDisplayInterval() { mockClock = new goog.testing.MockClock(true); var submenu = new goog.ui.SubMenu('submenu'); submenu.addItem(new goog.ui.MenuItem('submenu item 1')); menu.addItem(submenu); // Trigger mouseover, and remove item before showSubMenu can be called. var e = new goog.events.Event(); submenu.handleMouseOver(e); menu.removeItem(submenu); mockClock.tick(goog.ui.SubMenu.MENU_DELAY_MS); // (No JS error should occur.) } function testShowSubMenuAfterRemoval() { var submenu = new goog.ui.SubMenu('submenu'); menu.addItem(submenu); menu.removeItem(submenu); submenu.showSubMenu(); // (No JS error should occur.) } /** * Tests that if a sub menu is selectable, then it can handle actions. */ function testSubmenuSelectable() { var submenu = new goog.ui.SubMenu('submenu'); submenu.addItem(new goog.ui.MenuItem('submenu item 1')); menu.addItem(submenu); submenu.setSelectable(true); var numClicks = 0; var menuClickedFn = function(e) { numClicks++; }; goog.events.listen( submenu, goog.ui.Component.EventType.ACTION, menuClickedFn); submenu.performActionInternal(null); submenu.performActionInternal(null); assertEquals('The submenu should have fired an event', 2, numClicks); submenu.setSelectable(false); submenu.performActionInternal(null); assertEquals( 'The submenu should not have fired any further events', 2, numClicks); } /** * Tests that if a sub menu is checkable, then it can handle actions. */ function testSubmenuCheckable() { var submenu = new goog.ui.SubMenu('submenu'); submenu.addItem(new goog.ui.MenuItem('submenu item 1')); menu.addItem(submenu); submenu.setCheckable(true); var numClicks = 0; var menuClickedFn = function(e) { numClicks++; }; goog.events.listen( submenu, goog.ui.Component.EventType.ACTION, menuClickedFn); submenu.performActionInternal(null); submenu.performActionInternal(null); assertEquals('The submenu should have fired an event', 2, numClicks); submenu.setCheckable(false); submenu.performActionInternal(null); assertEquals( 'The submenu should not have fired any further events', 2, numClicks); } /** * Tests that entering a child menu cancels the dismiss timer for the submenu. */ function testEnteringChildCancelsDismiss() { var submenu = new goog.ui.SubMenu('submenu'); submenu.isInDocument = goog.functions.TRUE; submenu.addItem(new goog.ui.MenuItem('submenu item 1')); menu.addItem(submenu); mockClock = new goog.testing.MockClock(true); submenu.getMenu().setVisible(true); // This starts the dismiss timer. submenu.setHighlighted(false); // This should cancel the dismiss timer. submenu.getMenu().dispatchEvent(goog.ui.Component.EventType.ENTER); // Tick the length of the dismiss timer. mockClock.tick(goog.ui.SubMenu.MENU_DELAY_MS); // Check that the menu is now highlighted and still visible. assertTrue(submenu.getMenu().isVisible()); assertTrue(submenu.isHighlighted()); } /** * Asserts that this sub menu renders in the right direction relative to * the parent menu. * @param {goog.ui.SubMenu} subMenu The sub menu. * @param {boolean} left True for left-pointing, false for right-pointing. */ function assertRenderDirection(subMenu, left) { subMenu.getParent().setHighlighted(subMenu); subMenu.showSubMenu(); var menuItemPosition = goog.style.getPageOffset(subMenu.getElement()); var menuPosition = goog.style.getPageOffset(subMenu.getMenu().getElement()); assert(Math.abs(menuItemPosition.y - menuPosition.y) < 5); assertEquals( 'Menu at: ' + menuPosition.x + ', submenu item at: ' + menuItemPosition.x, left, menuPosition.x < menuItemPosition.x); } /** * Asserts that this sub menu has a properly-oriented arrow. * @param {goog.ui.SubMenu} subMenu The sub menu. * @param {boolean} left True for left-pointing, false for right-pointing. */ function assertArrowDirection(subMenu, left) { assertEquals( left ? goog.ui.SubMenuRenderer.LEFT_ARROW_ : goog.ui.SubMenuRenderer.RIGHT_ARROW_, getArrowElement(subMenu).innerHTML); } /** * Asserts that the arrow position is correct. * @param {goog.ui.SubMenu} subMenu The sub menu. * @param {boolean} leftAlign True for left-aligned, false for right-aligned. */ function assertArrowPosition(subMenu, left) { var arrow = getArrowElement(subMenu); var expectedLeft = left ? 0 : arrow.offsetParent.offsetWidth - arrow.offsetWidth; var actualLeft = arrow.offsetLeft; assertTrue( 'Expected left offset: ' + expectedLeft + '\n' + 'Actual left offset: ' + actualLeft + '\n', Math.abs(expectedLeft - actualLeft) < 5); } /** * Gets the arrow element of a sub menu. * @param {goog.ui.SubMenu} subMenu The sub menu. * @return {Element} The arrow. */ function getArrowElement(subMenu) { return subMenu.getContentElement().lastChild; }
MessageFormat.locale.es = function ( n ) { if ( n === 1 ) { return "one"; } return "other"; };
/** * Require unassigned functions to be named inline * * Types: `Boolean` or `Object` * * Values: * - `true` * - `Object`: * - `allExcept`: array of quoted identifiers * * #### Example * * ```js * "requireNamedUnassignedFunctions": { "allExcept": ["describe", "it"] } * ``` * * ##### Valid * * ```js * [].forEach(function x() {}); * var y = function() {}; * function z() {} * it(function () {}); * ``` * * ##### Invalid * * ```js * [].forEach(function () {}); * before(function () {}); * ``` */ var assert = require('assert'); var pathval = require('pathval'); function getNodeName(node) { if (node.type === 'Identifier') { return node.name; } else { return node.value; } } module.exports = function() {}; module.exports.prototype = { configure: function(options) { assert( options === true || typeof options === 'object', this.getOptionName() + ' option requires true value ' + 'or an object with String[] `allExcept` property' ); // verify first item in `allExcept` property in object (if it's an object) assert( typeof options !== 'object' || Array.isArray(options.allExcept) && typeof options.allExcept[0] === 'string', 'Property `allExcept` in ' + this.getOptionName() + ' should be an array of strings' ); if (options.allExcept) { this._allExceptItems = options.allExcept.map(function(item) { var parts = pathval.parse(item).map(function extractPart(part) { return part.i !== undefined ? part.i : part.p; }); return JSON.stringify(parts); }); } }, getOptionName: function() { return 'requireNamedUnassignedFunctions'; }, check: function(file, errors) { var _this = this; file.iterateNodesByType('FunctionExpression', function(node) { var parentElement = node.parentElement; // If the function has been named via left hand assignment, skip it // e.g. `var hello = function() {`, `foo.bar = function() {` if (parentElement.type.match(/VariableDeclarator|Property|AssignmentExpression/)) { return; } // If the function has been named, skip it // e.g. `[].forEach(function hello() {` if (node.id !== null) { return; } // If we have exceptions and the function is being invoked, detect whether we excepted it if (_this._allExceptItems && parentElement.type === 'CallExpression') { // Determine the path that resolves to our call expression // We must cover both direct calls (e.g. `it(function() {`) and // member expressions (e.g. `foo.bar(function() {`) var memberNode = parentElement.callee; var canBeRepresented = true; var fullpathParts = []; while (memberNode) { if (memberNode.type.match(/Identifier|Literal/)) { fullpathParts.unshift(getNodeName(memberNode)); } else if (memberNode.type === 'MemberExpression') { fullpathParts.unshift(getNodeName(memberNode.property)); } else { canBeRepresented = false; break; } memberNode = memberNode.object; } // If the path is not-dynamic (i.e. can be represented by static parts), // then check it against our exceptions if (canBeRepresented) { var fullpath = JSON.stringify(fullpathParts); for (var i = 0, l = _this._allExceptItems.length; i < l; i++) { if (fullpath === _this._allExceptItems[i]) { return; } } } } // Complain that this function must be named errors.add('Inline functions need to be named', node); }); } };
function X2JS(_1){ "use strict"; var _2="1.1.2"; _1=_1||{}; _3(); function _3(){ if(_1.escapeMode===undefined){ _1.escapeMode=true; } if(_1.attributePrefix===undefined){ _1.attributePrefix="_"; } if(_1.arrayAccessForm===undefined){ _1.arrayAccessForm="none"; } if(_1.emptyNodeForm===undefined){ _1.emptyNodeForm="text"; } }; var _4={ELEMENT_NODE:1,TEXT_NODE:3,CDATA_SECTION_NODE:4,DOCUMENT_NODE:9}; function _5(_6){ var _7=_6.localName; if(_7==null){ _7=_6.baseName; } if(_7==null||_7==""){ _7=_6.nodeName; } return _7; }; function _8(_9){ return _9.prefix; }; function _a(_b){ if(typeof (_b)=="string"){ return _b.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;").replace(/\//g,"&#x2F;"); }else{ return _b; } }; function _c(_d){ return _d.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,"\"").replace(/&#x27;/g,"'").replace(/&#x2F;/g,"/"); }; function _e(_f,_10){ switch(_1.arrayAccessForm){ case "property": if(!(_f[_10] instanceof Array)){ _f[_10+"_asArray"]=[_f[_10]]; }else{ _f[_10+"_asArray"]=_f[_10]; } break; } }; function _11(_12){ if(_12.nodeType==_4.DOCUMENT_NODE){ var _13=new Object; var _14=_12.firstChild; var _15=_5(_14); _13[_15]=_11(_14); return _13; }else{ if(_12.nodeType==_4.ELEMENT_NODE){ var _13=new Object; _13.__cnt=0; var _16=_12.childNodes; for(var _17=0;_17<_16.length;_17++){ var _14=_16.item(_17); var _15=_5(_14); _13.__cnt++; if(_13[_15]==null){ _13[_15]=_11(_14); _e(_13,_15); }else{ if(_13[_15]!=null){ if(!(_13[_15] instanceof Array)){ _13[_15]=[_13[_15]]; _e(_13,_15); } } var _18=0; while(_13[_15][_18]!=null){ _18++; } (_13[_15])[_18]=_11(_14); } } for(var _19=0;_19<_12.attributes.length;_19++){ var _1a=_12.attributes.item(_19); _13.__cnt++; _13[_1.attributePrefix+_1a.name]=_1a.value; } var _1b=_8(_12); if(_1b!=null&&_1b!=""){ _13.__cnt++; _13.__prefix=_1b; } if(_13["#text"]!=null){ _13.__text=_13["#text"]; if(_13.__text instanceof Array){ _13.__text=_13.__text.join("\n"); } if(_1.escapeMode){ _13.__text=_c(_13.__text); } delete _13["#text"]; if(_1.arrayAccessForm=="property"){ delete _13["#text_asArray"]; } } if(_13["#cdata-section"]!=null){ _13.__cdata=_13["#cdata-section"]; delete _13["#cdata-section"]; if(_1.arrayAccessForm=="property"){ delete _13["#cdata-section_asArray"]; } } if(_13.__cnt==1&&_13.__text!=null){ _13=_13.__text; }else{ if(_13.__cnt==0&&_1.emptyNodeForm=="text"){ _13=""; } } delete _13.__cnt; if(_13.__text!=null||_13.__cdata!=null){ _13.toString=function(){ return (this.__text!=null?this.__text:"")+(this.__cdata!=null?this.__cdata:""); }; } return _13; }else{ if(_12.nodeType==_4.TEXT_NODE||_12.nodeType==_4.CDATA_SECTION_NODE){ return _12.nodeValue; } } } }; function _1c(_1d,_1e,_1f,_20){ var _21="<"+((_1d!=null&&_1d.__prefix!=null)?(_1d.__prefix+":"):"")+_1e; if(_1f!=null){ for(var _22=0;_22<_1f.length;_22++){ var _23=_1f[_22]; var _24=_1d[_23]; _21+=" "+_23.substr(_1.attributePrefix.length)+"='"+_24+"'"; } } if(!_20){ _21+=">"; }else{ _21+="/>"; } return _21; }; function _25(_26,_27){ return "</"+(_26.__prefix!=null?(_26.__prefix+":"):"")+_27+">"; }; function _28(str,_29){ return str.indexOf(_29,str.length-_29.length)!==-1; }; function _2a(_2b,_2c){ if((_1.arrayAccessForm=="property"&&_28(_2c.toString(),("_asArray")))||_2c.toString().indexOf(_1.attributePrefix)==0||_2c.toString().indexOf("__")==0||(_2b[_2c] instanceof Function)){ return true; }else{ return false; } }; function _2d(_2e){ var _2f=0; if(_2e instanceof Object){ for(var it in _2e){ if(_2a(_2e,it)){ continue; } _2f++; } } return _2f; }; function _30(_31){ var _32=[]; if(_31 instanceof Object){ for(var ait in _31){ if(ait.toString().indexOf("__")==-1&&ait.toString().indexOf(_1.attributePrefix)==0){ _32.push(ait); } } } return _32; }; function _33(_34){ var _35=""; if(_34.__cdata!=null){ _35+="<![CDATA["+_34.__cdata+"]]>"; } if(_34.__text!=null){ if(_1.escapeMode){ _35+=_a(_34.__text); }else{ _35+=_34.__text; } } return _35; }; function _36(_37){ var _38=""; if(_37 instanceof Object){ _38+=_33(_37); }else{ if(_37!=null){ if(_1.escapeMode){ _38+=_a(_37); }else{ _38+=_37; } } } return _38; }; function _39(_3a,_3b,_3c){ var _3d=""; if(_3a.length==0){ _3d+=_1c(_3a,_3b,_3c,true); }else{ for(var _3e=0;_3e<_3a.length;_3e++){ _3d+=_1c(_3a[_3e],_3b,_30(_3a[_3e]),false); _3d+=_3f(_3a[_3e]); _3d+=_25(_3a[_3e],_3b); } } return _3d; }; function _3f(_40){ var _41=""; var _42=_2d(_40); if(_42>0){ for(var it in _40){ if(_2a(_40,it)){ continue; } var _43=_40[it]; var _44=_30(_43); if(_43==null||_43==undefined){ _41+=_1c(_43,it,_44,true); }else{ if(_43 instanceof Object){ if(_43 instanceof Array){ _41+=_39(_43,it,_44); }else{ var _45=_2d(_43); if(_45>0||_43.__text!=null||_43.__cdata!=null){ _41+=_1c(_43,it,_44,false); _41+=_3f(_43); _41+=_25(_43,it); }else{ _41+=_1c(_43,it,_44,true); } } }else{ _41+=_1c(_43,it,_44,false); _41+=_36(_43); _41+=_25(_43,it); } } } } _41+=_36(_40); return _41; }; this.parseXmlString=function(_46){ if(_46===undefined){ return null; } var _47; if(window.DOMParser){ var _48=new window.DOMParser(); _47=_48.parseFromString(_46,"text/xml"); }else{ if(_46.indexOf("<?")==0){ _46=_46.substr(_46.indexOf("?>")+2); } _47=new ActiveXObject("Microsoft.XMLDOM"); _47.async="false"; _47.loadXML(_46); } return _47; }; this.asArray=function(_49){ if(_49 instanceof Array){ return _49; }else{ return [_49]; } }; this.xml2json=function(_4a){ return _11(_4a); }; this.xml_str2json=function(_4b){ var _4c=this.parseXmlString(_4b); return this.xml2json(_4c); }; this.json2xml_str=function(_4d){ return _3f(_4d); }; this.json2xml=function(_4e){ var _4f=this.json2xml_str(_4e); return this.parseXmlString(_4f); }; this.getVersion=function(){ return _2; }; };
'use strict'; var path = require('path'); exports.name = 'cssmin'; // // Output a config for the furnished block // The context variable is used both to take the files to be treated // (inFiles) and to output the one(s) created (outFiles). // It aslo conveys whether or not the current process is the last of the pipe // exports.createConfig = function(context, block) { var cfg = {files: []}; // FIXME: check context has all the needed info var outfile = path.join(context.outDir, block.dest); // Depending whether or not we're the last of the step we're not going to output the same thing var files = {}; files.dest = outfile; files.src = []; context.inFiles.forEach(function(f) { files.src.push(path.join(context.inDir, f));} ); cfg.files.push(files); context.outFiles = [block.dest]; return cfg; };
/* * jquery.inputmask.numeric.extensions.js * http://github.com/RobinHerbots/jquery.inputmask * Copyright (c) 2010 - 2014 Robin Herbots * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) * Version: 3.1.26 */ (function (factory) {if (typeof define === 'function' && define.amd) {define(["jquery","./jquery.inputmask"], factory);} else {factory(jQuery);}}/* Input Mask plugin extensions http://github.com/RobinHerbots/jquery.inputmask Copyright (c) 2010 - 2014 Robin Herbots Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) Version: 0.0.0 Optional extensions on the jquery.inputmask base */ (function ($) { //number aliases $.extend($.inputmask.defaults.aliases, { 'numeric': { mask: function (opts) { if (opts.repeat !== 0 && isNaN(opts.integerDigits)) { opts.integerDigits = opts.repeat; } opts.repeat = 0; if (opts.groupSeparator == opts.radixPoint) { //treat equal separator and radixpoint if (opts.radixPoint == ".") opts.groupSeparator = ","; else if (opts.radixPoint == ",") opts.groupSeparator = "."; else opts.groupSeparator = ""; } if (opts.groupSeparator === " ") { //prevent conflict with default skipOptionalPartCharacter opts.skipOptionalPartCharacter = undefined; } opts.autoGroup = opts.autoGroup && opts.groupSeparator != ""; if (opts.autoGroup && isFinite(opts.integerDigits)) { var seps = Math.floor(opts.integerDigits / opts.groupSize); var mod = opts.integerDigits % opts.groupSize; opts.integerDigits += mod == 0 ? seps - 1 : seps; } opts.definitions[";"] = opts.definitions["~"]; //clone integer def for decimals var mask = opts.prefix; mask += "[+]"; mask += "~{1," + opts.integerDigits + "}"; if (opts.digits != undefined && (isNaN(opts.digits) || parseInt(opts.digits) > 0)) { if (opts.digitsOptional) mask += "[" + (opts.decimalProtect ? ":" : opts.radixPoint) + ";{" + opts.digits + "}]"; else mask += (opts.decimalProtect ? ":" : opts.radixPoint) + ";{" + opts.digits + "}"; } mask += opts.suffix; return mask; }, placeholder: "", greedy: false, digits: "*", //number of fractionalDigits digitsOptional: true, groupSeparator: "",//",", // | "." radixPoint: ".", groupSize: 3, autoGroup: false, allowPlus: true, allowMinus: true, integerDigits: "+", //number of integerDigits prefix: "", suffix: "", rightAlign: true, decimalProtect: true, //do not allow assumption of decimals input without entering the radixpoint postFormat: function (buffer, pos, reformatOnly, opts) { //this needs to be removed // this is crap var needsRefresh = false, charAtPos = buffer[pos]; if (opts.groupSeparator == "" || ($.inArray(opts.radixPoint, buffer) != -1 && pos >= $.inArray(opts.radixPoint, buffer)) || new RegExp('[-\+]').test(charAtPos) ) return { pos: pos }; var cbuf = buffer.slice(); if (charAtPos == opts.groupSeparator) { cbuf.splice(pos--, 1); charAtPos = cbuf[pos]; } if (reformatOnly) cbuf[pos] = "?"; else cbuf.splice(pos, 0, "?"); //set position indicator var bufVal = cbuf.join(''); if (opts.autoGroup || (reformatOnly && bufVal.indexOf(opts.groupSeparator) != -1)) { var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator); needsRefresh = bufVal.indexOf(opts.groupSeparator) == 0; bufVal = bufVal.replace(new RegExp(escapedGroupSeparator, "g"), ''); var radixSplit = bufVal.split(opts.radixPoint); bufVal = radixSplit[0]; if (bufVal != (opts.prefix + "?0") && bufVal.length >= (opts.groupSize + opts.prefix.length)) { needsRefresh = true; var reg = new RegExp('([-\+]?[\\d\?]+)([\\d\?]{' + opts.groupSize + '})'); while (reg.test(bufVal)) { bufVal = bufVal.replace(reg, '$1' + opts.groupSeparator + '$2'); bufVal = bufVal.replace(opts.groupSeparator + opts.groupSeparator, opts.groupSeparator); } } if (radixSplit.length > 1) bufVal += opts.radixPoint + radixSplit[1]; } buffer.length = bufVal.length; //align the length for (var i = 0, l = bufVal.length; i < l; i++) { buffer[i] = bufVal.charAt(i); } var newPos = $.inArray("?", buffer); if (reformatOnly) buffer[newPos] = charAtPos; else buffer.splice(newPos, 1); return { pos: newPos, "refreshFromBuffer": needsRefresh }; }, onKeyDown: function (e, buffer, caretPos, opts) { if (e.keyCode == $.inputmask.keyCode.TAB && opts.placeholder.charAt(0) != "0") { var radixPosition = $.inArray(opts.radixPoint, buffer); if (radixPosition != -1 && isFinite(opts.digits)) { for (var i = 1; i <= opts.digits; i++) { if (buffer[radixPosition + i] == undefined || buffer[radixPosition + i] == opts.placeholder.charAt(0)) buffer[radixPosition + i] = "0"; } return { "refreshFromBuffer": { start: ++radixPosition, end: radixPosition + opts.digits } }; } } else if (opts.autoGroup && (e.keyCode == $.inputmask.keyCode.DELETE || e.keyCode == $.inputmask.keyCode.BACKSPACE)) { var rslt = opts.postFormat(buffer, caretPos - 1, true, opts); rslt.caret = rslt.pos + 1; return rslt; } }, onKeyPress: function (e, buffer, caretPos, opts) { if (opts.autoGroup /*&& String.fromCharCode(k) == opts.radixPoint*/) { var rslt = opts.postFormat(buffer, caretPos - 1, true, opts); rslt.caret = rslt.pos + 1; return rslt; } }, regex: { integerPart: function (opts) { return new RegExp('[-\+]?\\d+'); } }, negationhandler: function (chrs, buffer, pos, strict, opts) { if (!strict && opts.allowMinus && chrs === "-") { var matchRslt = buffer.join('').match(opts.regex.integerPart(opts)); if (matchRslt.length > 0) { if (buffer[matchRslt.index] == "+") { return { "pos": matchRslt.index, "c": "-", "remove": matchRslt.index, "caret": pos }; } else if (buffer[matchRslt.index] == "-") { return { "remove": matchRslt.index, "caret": pos - 1 }; } else { return { "pos": matchRslt.index, "c": "-", "caret": pos + 1 }; } } } return false; }, radixhandler: function (chrs, maskset, pos, strict, opts) { if (!strict && chrs === opts.radixPoint) { var radixPos = $.inArray(opts.radixPoint, maskset.buffer), integerValue = maskset.buffer.join('').match(opts.regex.integerPart(opts)); if (radixPos != -1) { if (maskset["validPositions"][radixPos - 1]) return { "caret": radixPos + 1 }; else return { "pos": integerValue.index, c: integerValue[0], "caret": radixPos + 1 }; } } return false; }, leadingZeroHandler: function (chrs, maskset, pos, strict, opts) { var matchRslt = maskset.buffer.join('').match(opts.regex.integerPart(opts)), radixPosition = $.inArray(opts.radixPoint, maskset.buffer); if (matchRslt && !strict && (radixPosition == -1 || matchRslt.index < radixPosition)) { if (matchRslt["0"].indexOf("0") == 0 && pos >= opts.prefix.length) { if (radixPosition == -1 || (pos <= radixPosition && maskset["validPositions"][radixPosition] == undefined)) { maskset.buffer.splice(matchRslt.index, 1); pos = pos > matchRslt.index ? pos - 1 : matchRslt.index; return { "pos": pos, "remove": matchRslt.index }; } else if (pos > matchRslt.index && pos <= radixPosition) { maskset.buffer.splice(matchRslt.index, 1); pos = pos > matchRslt.index ? pos - 1 : matchRslt.index; return { "pos": pos, "remove": matchRslt.index }; } } else if (chrs == "0" && pos <= matchRslt.index) { return false; } } return true; }, definitions: { '~': { validator: function (chrs, maskset, pos, strict, opts) { var isValid = opts.negationhandler(chrs, maskset.buffer, pos, strict, opts); if (!isValid) { isValid = opts.radixhandler(chrs, maskset, pos, strict, opts); if (!isValid) { isValid = strict ? new RegExp("[0-9" + $.inputmask.escapeRegex.call(this, opts.groupSeparator) + "]").test(chrs) : new RegExp("[0-9]").test(chrs); if (isValid === true) { isValid = opts.leadingZeroHandler(chrs, maskset, pos, strict, opts); if (isValid === true) { //handle overwrite when fixed precision var radixPosition = $.inArray(opts.radixPoint, maskset.buffer); if (opts.digitsOptional === false && pos > radixPosition && !strict) { return { "pos": pos, "remove": pos }; } else return { pos: pos }; } } } } return isValid; }, cardinality: 1, prevalidator: null }, '+': { validator: function (chrs, maskset, pos, strict, opts) { var signed = "["; if (opts.allowMinus === true) signed += "-"; if (opts.allowPlus === true) signed += "\+"; signed += "]"; return new RegExp(signed).test(chrs); }, cardinality: 1, prevalidator: null, placeholder: '' }, ':': { validator: function (chrs, maskset, pos, strict, opts) { var isValid = opts.negationhandler(chrs, maskset.buffer, pos, strict, opts); if (!isValid) { var radix = "[" + $.inputmask.escapeRegex.call(this, opts.radixPoint) + "]"; isValid = new RegExp(radix).test(chrs); if (isValid && maskset["validPositions"][pos] && maskset["validPositions"][pos]["match"].placeholder == opts.radixPoint) { isValid = { "pos": pos, "remove": pos }; } } return isValid; }, cardinality: 1, prevalidator: null, placeholder: function (opts) { return opts.radixPoint; } } }, insertMode: true, autoUnmask: false, onUnMask: function (maskedValue, unmaskedValue, opts) { var processValue = maskedValue.replace(opts.prefix, ""); processValue = processValue.replace(opts.suffix, ""); processValue = processValue.replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), ""); //processValue = processValue.replace($.inputmask.escapeRegex.call(this, opts.radixPoint), "."); return processValue; }, isComplete: function (buffer, opts) { var maskedValue = buffer.join(''), bufClone = buffer.slice(); //verify separator positions opts.postFormat(bufClone, 0, true, opts); if (bufClone.join('') != maskedValue) return false; var processValue = maskedValue.replace(opts.prefix, ""); processValue = processValue.replace(opts.suffix, ""); processValue = processValue.replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), ""); processValue = processValue.replace($.inputmask.escapeRegex.call(this, opts.radixPoint), "."); return isFinite(processValue); }, onBeforeMask: function (initialValue, opts) { if (isFinite(initialValue)) { return initialValue.toString().replace(".", opts.radixPoint); } else { var kommaMatches = initialValue.match(/,/g); var dotMatches = initialValue.match(/\./g); if (dotMatches && kommaMatches) { if (dotMatches.length > kommaMatches.length) { initialValue = initialValue.replace(/\./g, ""); initialValue = initialValue.replace(",", opts.radixPoint); } else if (kommaMatches.length > dotMatches.length) { initialValue = initialValue.replace(/,/g, ""); initialValue = initialValue.replace(".", opts.radixPoint); } } else { initialValue = initialValue.replace(new RegExp($.inputmask.escapeRegex.call(this, opts.groupSeparator), "g"), ""); } return initialValue; } } }, 'currency': { prefix: "$ ", groupSeparator: ",", radixPoint: ".", alias: "numeric", placeholder: "0", autoGroup: true, digits: 2, digitsOptional: false, clearMaskOnLostFocus: false, decimalProtect: true, }, 'decimal': { alias: "numeric" }, 'integer': { alias: "numeric", digits: "0" } }); return $.fn.inputmask; }));
/*! (C) WebReflection Mit Style License */ (function(e,t,n){if(n in e)return;var r=0,i=e.clearTimeout,s=e.setTimeout,o=Element.prototype,u=t.getOwnPropertyDescriptor,a=t.defineProperty,f=function(){document.dispatchEvent(new CustomEvent("readystatechange"))},l=function(e,t){i(r),r=s(f,10)},c=function(e){var t=u(o,e),n={configurable:t.configurable,enumerable:t.enumerable,get:function(){return t.get.call(this)},set:function(r){delete o[e],this[e]=r,a(o,e,n),l(this)}};a(o,e,n)},h=function(e){var t=u(o,e),n=t.value;t.value=function(){var e=n.apply(this,arguments);return l(this),e},a(o,e,t)};c("innerHTML"),c("innerText"),c("outerHTML"),c("outerText"),c("textContent"),h("appendChild"),h("applyElement"),h("insertAdjacentElement"),h("insertAdjacentHTML"),h("insertAdjacentText"),h("insertBefore"),h("insertData"),h("replaceAdjacentText"),h("replaceChild"),h("removeChild"),e[n]=Element})(window,Object,"HTMLElement");
tinymce.addI18n('fi',{ "Cut": "Leikkaa", "Header 2": "Otsikko 2", "Your browser doesn't support direct access to the clipboard. Please use the Ctrl+X\/C\/V keyboard shortcuts instead.": "Selaimesi ei tue leikekirjan suoraa k\u00e4ytt\u00e4mist\u00e4. Ole hyv\u00e4 ja k\u00e4yt\u00e4 n\u00e4pp\u00e4imist\u00f6n Ctrl+X ja Ctrl+V n\u00e4pp\u00e4inyhdistelmi\u00e4.", "Div": "Div", "Paste": "Liit\u00e4", "Close": "Sulje", "Font Family": "Fontti", "Pre": "Esimuotoiltu", "Align right": "Tasaa oikealle", "New document": "Uusi dokumentti", "Blockquote": "Lainauslohko", "Numbered list": "J\u00e4rjestetty lista", "Increase indent": "Loitonna", "Formats": "Muotoilut", "Headers": "Otsikot", "Select all": "Valitse kaikki", "Header 3": "Otsikko 3", "Blocks": "Lohkot", "Undo": "Peru", "Strikethrough": "Yliviivaus", "Bullet list": "J\u00e4rjest\u00e4m\u00e4t\u00f6n lista", "Header 1": "Otsikko 1", "Superscript": "Yl\u00e4indeksi", "Clear formatting": "Poista muotoilu", "Font Sizes": "Fonttikoko", "Subscript": "Alaindeksi", "Header 6": "Otsikko 6", "Redo": "Tee uudelleen", "Paragraph": "Kappale", "Ok": "Ok", "Bold": "Lihavointi", "Code": "Koodi", "Italic": "Kursivointi", "Align center": "Keskit\u00e4", "Header 5": "Otsikko 5", "Decrease indent": "Sisenn\u00e4", "Header 4": "Otsikko 4", "Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off.": "Liitt\u00e4minen on nyt pelk\u00e4n tekstin -tilassa. Sis\u00e4ll\u00f6t liitet\u00e4\u00e4n nyt pelkk\u00e4n\u00e4 tekstin\u00e4, kunnes otat vaihtoehdon pois k\u00e4yt\u00f6st\u00e4.", "Underline": "Alleviivaus", "Cancel": "Peruuta", "Justify": "Tasaa", "Inline": "Samalla rivill\u00e4", "Copy": "Kopioi", "Align left": "Tasaa vasemmalle", "Visual aids": "Visuaaliset neuvot", "Lower Greek": "pienet kirjaimet: \u03b1, \u03b2, \u03b3", "Square": "Neli\u00f6", "Default": "Oletus", "Lower Alpha": "pienet kirjaimet: a, b, c", "Circle": "Pallo", "Disc": "Ympyr\u00e4", "Upper Alpha": "isot kirjaimet: A, B, C", "Upper Roman": "isot kirjaimet: I, II, III", "Lower Roman": "pienet kirjaimet: i, ii, iii", "Name": "Nimi", "Anchor": "Ankkuri", "You have unsaved changes are you sure you want to navigate away?": "Sinulla on tallentamattomia muutoksia, haluatko varmasti siirty\u00e4 toiselle sivulle?", "Restore last draft": "Palauta aiempi luonnos", "Special character": "Erikoismerkki", "Source code": "L\u00e4hdekoodi", "Right to left": "Oikealta vasemmalle", "Left to right": "Vasemmalta oikealle", "Emoticons": "Hymi\u00f6t", "Robots": "Robotit", "Document properties": "Dokumentin ominaisuudet", "Title": "Otsikko", "Keywords": "Avainsanat", "Encoding": "Merkist\u00f6", "Description": "Kuvaus", "Author": "Tekij\u00e4", "Fullscreen": "Koko ruutu", "Horizontal line": "Vaakasuora viiva", "Horizontal space": "Horisontaalinen tila", "Insert\/edit image": "Lis\u00e4\u00e4\/muokkaa kuva", "General": "Yleiset", "Advanced": "Lis\u00e4asetukset", "Source": "L\u00e4hde", "Border": "Reunus", "Constrain proportions": "S\u00e4ilyt\u00e4 mittasuhteet", "Vertical space": "Vertikaalinen tila", "Image description": "Kuvaus", "Style": "Tyyli", "Dimensions": "Mittasuhteet", "Insert image": "Lis\u00e4\u00e4 kuva", "Insert date\/time": "Lis\u00e4\u00e4 p\u00e4iv\u00e4m\u00e4\u00e4r\u00e4 tai aika", "Remove link": "Poista linkki", "Url": "Osoite", "Text to display": "N\u00e4ytett\u00e4v\u00e4 teksti", "Anchors": "Ankkurit", "Insert link": "Lis\u00e4\u00e4 linkki", "New window": "Uusi ikkuna", "None": "Ei mit\u00e4\u00e4n", "Target": "Kohde", "Insert\/edit link": "Lis\u00e4\u00e4 tai muokkaa linkki", "Insert\/edit video": "Lis\u00e4\u00e4 tai muokkaa video", "Poster": "L\u00e4hett\u00e4j\u00e4", "Alternative source": "Vaihtoehtoinen l\u00e4hde", "Paste your embed code below:": "Liit\u00e4 upotuskoodisi alapuolelle:", "Insert video": "Lis\u00e4\u00e4 video", "Embed": "Upota", "Nonbreaking space": "Tyhj\u00e4 merkki (nbsp)", "Page break": "Sivunvaihto", "Paste as text": "Liit\u00e4 tekstin\u00e4", "Preview": "Esikatselu", "Print": "Tulosta", "Save": "Tallenna", "Could not find the specified string.": "Haettua merkkijonoa ei l\u00f6ytynyt.", "Replace": "Korvaa", "Next": "Seur.", "Whole words": "Koko sanat", "Find and replace": "Etsi ja korvaa", "Replace with": "Korvaa", "Find": "Etsi", "Replace all": "Korvaa kaikki", "Match case": "Erota isot ja pienet kirjaimet", "Prev": "Edel.", "Spellcheck": "Oikolue", "Finish": "Lopeta", "Ignore all": "\u00c4l\u00e4 huomioi mit\u00e4\u00e4n", "Ignore": "\u00c4l\u00e4 huomioi", "Insert row before": "Lis\u00e4\u00e4 rivi ennen", "Rows": "Rivit", "Height": "Korkeus", "Paste row after": "Liit\u00e4 rivi j\u00e4lkeen", "Alignment": "Tasaus", "Column group": "Sarakeryhm\u00e4", "Row": "Rivi", "Insert column before": "Lis\u00e4\u00e4 rivi ennen", "Split cell": "Jaa solu", "Cell padding": "Solun tyhj\u00e4 tila", "Cell spacing": "Solun v\u00e4li", "Row type": "Rivityyppi", "Insert table": "Lis\u00e4\u00e4 taulukko", "Body": "Runko", "Caption": "Seloste", "Footer": "Alaosa", "Delete row": "Poista rivi", "Paste row before": "Liit\u00e4 rivi ennen", "Scope": "Laajuus", "Delete table": "Poista taulukko", "Header cell": "Otsikkosolu", "Column": "Sarake", "Cell": "Solu", "Header": "Otsikko", "Cell type": "Solun tyyppi", "Copy row": "Kopioi rivi", "Row properties": "Rivin ominaisuudet", "Table properties": "Taulukon ominaisuudet", "Row group": "Riviryhm\u00e4", "Right": "Oikea", "Insert column after": "Lis\u00e4\u00e4 rivi j\u00e4lkeen", "Cols": "Sarakkeet", "Insert row after": "Lis\u00e4\u00e4 rivi j\u00e4lkeen", "Width": "Leveys", "Cell properties": "Solun ominaisuudet", "Left": "Vasen", "Cut row": "Leikkaa rivi", "Delete column": "Poista sarake", "Center": "Keskell\u00e4", "Merge cells": "Yhdist\u00e4 solut", "Insert template": "Lis\u00e4\u00e4 pohja", "Templates": "Pohjat", "Background color": "Taustan v\u00e4ri", "Text color": "Tekstin v\u00e4ri", "Show blocks": "N\u00e4yt\u00e4 lohkot", "Show invisible characters": "N\u00e4yt\u00e4 n\u00e4kym\u00e4tt\u00f6m\u00e4t merkit", "Words: {0}": "Sanat: {0}", "Insert": "Lis\u00e4\u00e4", "File": "Tiedosto", "Edit": "Muokkaa", "Rich Text Area. Press ALT-F9 for menu. Press ALT-F10 for toolbar. Press ALT-0 for help": "Rikastetun tekstin alue. Paina ALT-F9 valikkoon. Paina ALT-F10 ty\u00f6kaluriviin. Paina ALT-0 ohjeeseen.", "Tools": "Ty\u00f6kalut", "View": "N\u00e4yt\u00e4", "Table": "Taulukko", "Format": "Muotoilu" });
/** @module ember @submodule ember-htmlbars */ import Ember from 'ember-metal/core'; import EmberStringUtils from 'ember-runtime/system/string'; import { SafeString, escapeExpression } from 'htmlbars-util'; /** Mark a string as safe for unescaped output with Ember templates. If you return HTML from a helper, use this function to ensure Ember's rendering layer does not escape the HTML. ```javascript Ember.String.htmlSafe('<div>someString</div>') ``` @method htmlSafe @for Ember.String @static @return {Handlebars.SafeString} a string that will not be html escaped by Handlebars @public */ function htmlSafe(str) { if (str === null || str === undefined) { return ''; } if (typeof str !== 'string') { str = '' + str; } return new SafeString(str); } EmberStringUtils.htmlSafe = htmlSafe; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { String.prototype.htmlSafe = function() { return htmlSafe(this); }; } export { SafeString, htmlSafe, escapeExpression };
/** * @license Highmaps JS v5.0.1 (2016-10-26) * * (c) 2011-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; (function(root, factory) { if (typeof module === 'object' && module.exports) { module.exports = root.document ? factory(root) : factory; } else { root.Highcharts = factory(root); } }(typeof window !== 'undefined' ? window : this, function(win) { var Highcharts = (function() { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; /* global window */ var win = window, doc = win.document; var SVG_NS = 'http://www.w3.org/2000/svg', userAgent = (win.navigator && win.navigator.userAgent) || '', svg = doc && doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect, isMS = /(edge|msie|trident)/i.test(userAgent) && !window.opera, vml = !svg, isFirefox = /Firefox/.test(userAgent), hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4; // issue #38 var Highcharts = win.Highcharts ? win.Highcharts.error(16, true) : { product: 'Highmaps', version: '5.0.1', deg2rad: Math.PI * 2 / 360, doc: doc, hasBidiBug: hasBidiBug, hasTouch: doc && doc.documentElement.ontouchstart !== undefined, isMS: isMS, isWebKit: /AppleWebKit/.test(userAgent), isFirefox: isFirefox, isTouchDevice: /(Mobile|Android|Windows Phone)/.test(userAgent), SVG_NS: SVG_NS, idCounter: 0, chartCount: 0, seriesTypes: {}, symbolSizes: {}, svg: svg, vml: vml, win: win, charts: [], marginNames: ['plotTop', 'marginRight', 'marginBottom', 'plotLeft'], noop: function() { return undefined; } }; return Highcharts; }()); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var timers = []; var charts = H.charts, doc = H.doc, win = H.win; /** * Provide error messages for debugging, with links to online explanation */ H.error = function(code, stop) { var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code; if (stop) { throw new Error(msg); } // else ... if (win.console) { console.log(msg); // eslint-disable-line no-console } }; /** * An animator object. One instance applies to one property (attribute or style prop) * on one element. * * @param {object} elem The element to animate. May be a DOM element or a Highcharts SVGElement wrapper. * @param {object} options Animation options, including duration, easing, step and complete. * @param {object} prop The property to animate. */ H.Fx = function(elem, options, prop) { this.options = options; this.elem = elem; this.prop = prop; }; H.Fx.prototype = { /** * Animating a path definition on SVGElement * @returns {undefined} */ dSetter: function() { var start = this.paths[0], end = this.paths[1], ret = [], now = this.now, i = start.length, startVal; if (now === 1) { // land on the final path without adjustment points appended in the ends ret = this.toD; } else if (i === end.length && now < 1) { while (i--) { startVal = parseFloat(start[i]); ret[i] = isNaN(startVal) ? // a letter instruction like M or L start[i] : now * (parseFloat(end[i] - startVal)) + startVal; } } else { // if animation is finished or length not matching, land on right value ret = end; } this.elem.attr('d', ret); }, /** * Update the element with the current animation step * @returns {undefined} */ update: function() { var elem = this.elem, prop = this.prop, // if destroyed, it is null now = this.now, step = this.options.step; // Animation setter defined from outside if (this[prop + 'Setter']) { this[prop + 'Setter'](); // Other animations on SVGElement } else if (elem.attr) { if (elem.element) { elem.attr(prop, now); } // HTML styles, raw HTML content like container size } else { elem.style[prop] = now + this.unit; } if (step) { step.call(elem, now, this); } }, /** * Run an animation */ run: function(from, to, unit) { var self = this, timer = function(gotoEnd) { return timer.stopped ? false : self.step(gotoEnd); }, i; this.startTime = +new Date(); this.start = from; this.end = to; this.unit = unit; this.now = this.start; this.pos = 0; timer.elem = this.elem; if (timer() && timers.push(timer) === 1) { timer.timerId = setInterval(function() { for (i = 0; i < timers.length; i++) { if (!timers[i]()) { timers.splice(i--, 1); } } if (!timers.length) { clearInterval(timer.timerId); } }, 13); } }, /** * Run a single step in the animation * @param {Boolean} gotoEnd Whether to go to then endpoint of the animation after abort * @returns {Boolean} True if animation continues */ step: function(gotoEnd) { var t = +new Date(), ret, done, options = this.options, elem = this.elem, complete = options.complete, duration = options.duration, curAnim = options.curAnim, i; if (elem.attr && !elem.element) { // #2616, element including flag is destroyed ret = false; } else if (gotoEnd || t >= duration + this.startTime) { this.now = this.end; this.pos = 1; this.update(); curAnim[this.prop] = true; done = true; for (i in curAnim) { if (curAnim[i] !== true) { done = false; } } if (done && complete) { complete.call(elem); } ret = false; } else { this.pos = options.easing((t - this.startTime) / duration); this.now = this.start + ((this.end - this.start) * this.pos); this.update(); ret = true; } return ret; }, /** * Prepare start and end values so that the path can be animated one to one */ initPath: function(elem, fromD, toD) { fromD = fromD || ''; var shift, startX = elem.startX, endX = elem.endX, bezier = fromD.indexOf('C') > -1, numParams = bezier ? 7 : 3, fullLength, slice, i, start = fromD.split(' '), end = toD.slice(), // copy isArea = elem.isArea, positionFactor = isArea ? 2 : 1, reverse; /** * In splines make move points have six parameters like bezier curves */ function sixify(arr) { i = arr.length; while (i--) { if (arr[i] === 'M' || arr[i] === 'L') { arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]); } } } /** * Insert an array at the given position of another array */ function insertSlice(arr, subArr, index) { [].splice.apply( arr, [index, 0].concat(subArr) ); } /** * If shifting points, prepend a dummy point to the end path. */ function prepend(arr, other) { while (arr.length < fullLength) { // Move to, line to or curve to? arr[0] = other[fullLength - arr.length]; // Prepend a copy of the first point insertSlice(arr, arr.slice(0, numParams), 0); // For areas, the bottom path goes back again to the left, so we need // to append a copy of the last point. if (isArea) { insertSlice(arr, arr.slice(arr.length - numParams), arr.length); i--; } } arr[0] = 'M'; } /** * Copy and append last point until the length matches the end length */ function append(arr, other) { var i = (fullLength - arr.length) / numParams; while (i > 0 && i--) { // Pull out the slice that is going to be appended or inserted. In a line graph, // the positionFactor is 1, and the last point is sliced out. In an area graph, // the positionFactor is 2, causing the middle two points to be sliced out, since // an area path starts at left, follows the upper path then turns and follows the // bottom back. slice = arr.slice().splice( (arr.length / positionFactor) - numParams, numParams * positionFactor ); // Move to, line to or curve to? slice[0] = other[fullLength - numParams - (i * numParams)]; // Disable first control point if (bezier) { slice[numParams - 6] = slice[numParams - 2]; slice[numParams - 5] = slice[numParams - 1]; } // Now insert the slice, either in the middle (for areas) or at the end (for lines) insertSlice(arr, slice, arr.length / positionFactor); if (isArea) { i--; } } } if (bezier) { sixify(start); sixify(end); } // For sideways animation, find out how much we need to shift to get the start path Xs // to match the end path Xs. if (startX && endX) { for (i = 0; i < startX.length; i++) { if (startX[i] === endX[0]) { // Moving left, new points coming in on right shift = i; break; } else if (startX[0] === endX[endX.length - startX.length + i]) { // Moving right shift = i; reverse = true; break; } } if (shift === undefined) { start = []; } } if (start.length && H.isNumber(shift)) { // The common target length for the start and end array, where both // arrays are padded in opposite ends fullLength = end.length + shift * positionFactor * numParams; if (!reverse) { prepend(end, start); append(start, end); } else { prepend(start, end); append(end, start); } } return [start, end]; } }; // End of Fx prototype /** * Extend an object with the members of another * @param {Object} a The object to be extended * @param {Object} b The object to add to the first one */ H.extend = function(a, b) { var n; if (!a) { a = {}; } for (n in b) { a[n] = b[n]; } return a; }; /** * Deep merge two or more objects and return a third object. If the first argument is * true, the contents of the second object is copied into the first object. * Previously this function redirected to jQuery.extend(true), but this had two limitations. * First, it deep merged arrays, which lead to workarounds in Highcharts. Second, * it copied properties from extended prototypes. */ H.merge = function() { var i, args = arguments, len, ret = {}, doCopy = function(copy, original) { var value, key; // An object is replacing a primitive if (typeof copy !== 'object') { copy = {}; } for (key in original) { if (original.hasOwnProperty(key)) { value = original[key]; // Copy the contents of objects, but not arrays or DOM nodes if (H.isObject(value, true) && key !== 'renderTo' && typeof value.nodeType !== 'number') { copy[key] = doCopy(copy[key] || {}, value); // Primitives and arrays are copied over directly } else { copy[key] = original[key]; } } } return copy; }; // If first argument is true, copy into the existing object. Used in setOptions. if (args[0] === true) { ret = args[1]; args = Array.prototype.slice.call(args, 2); } // For each argument, extend the return len = args.length; for (i = 0; i < len; i++) { ret = doCopy(ret, args[i]); } return ret; }; /** * Shortcut for parseInt * @param {Object} s * @param {Number} mag Magnitude */ H.pInt = function(s, mag) { return parseInt(s, mag || 10); }; /** * Check for string * @param {Object} s */ H.isString = function(s) { return typeof s === 'string'; }; /** * Check for object * @param {Object} obj * @param {Boolean} strict Also checks that the object is not an array */ H.isArray = function(obj) { var str = Object.prototype.toString.call(obj); return str === '[object Array]' || str === '[object Array Iterator]'; }; /** * Check for array * @param {Object} obj */ H.isObject = function(obj, strict) { return obj && typeof obj === 'object' && (!strict || !H.isArray(obj)); }; /** * Check for number * @param {Object} n */ H.isNumber = function(n) { return typeof n === 'number' && !isNaN(n); }; /** * Remove last occurence of an item from an array * @param {Array} arr * @param {Mixed} item */ H.erase = function(arr, item) { var i = arr.length; while (i--) { if (arr[i] === item) { arr.splice(i, 1); break; } } //return arr; }; /** * Returns true if the object is not null or undefined. * @param {Object} obj */ H.defined = function(obj) { return obj !== undefined && obj !== null; }; /** * Set or get an attribute or an object of attributes. Can't use jQuery attr because * it attempts to set expando properties on the SVG element, which is not allowed. * * @param {Object} elem The DOM element to receive the attribute(s) * @param {String|Object} prop The property or an abject of key-value pairs * @param {String} value The value if a single property is set */ H.attr = function(elem, prop, value) { var key, ret; // if the prop is a string if (H.isString(prop)) { // set the value if (H.defined(value)) { elem.setAttribute(prop, value); // get the value } else if (elem && elem.getAttribute) { // elem not defined when printing pie demo... ret = elem.getAttribute(prop); } // else if prop is defined, it is a hash of key/value pairs } else if (H.defined(prop) && H.isObject(prop)) { for (key in prop) { elem.setAttribute(key, prop[key]); } } return ret; }; /** * Check if an element is an array, and if not, make it into an array. */ H.splat = function(obj) { return H.isArray(obj) ? obj : [obj]; }; /** * Set a timeout if the delay is given, otherwise perform the function synchronously * @param {Function} fn The function to perform * @param {Number} delay Delay in milliseconds * @param {Ojbect} context The context * @returns {Nubmer} An identifier for the timeout */ H.syncTimeout = function(fn, delay, context) { if (delay) { return setTimeout(fn, delay, context); } fn.call(0, context); }; /** * Return the first value that is defined. */ H.pick = function() { var args = arguments, i, arg, length = args.length; for (i = 0; i < length; i++) { arg = args[i]; if (arg !== undefined && arg !== null) { return arg; } } }; /** * Set CSS on a given element * @param {Object} el * @param {Object} styles Style object with camel case property names */ H.css = function(el, styles) { if (H.isMS && !H.svg) { // #2686 if (styles && styles.opacity !== undefined) { styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')'; } } H.extend(el.style, styles); }; /** * Utility function to create element with attributes and styles * @param {Object} tag * @param {Object} attribs * @param {Object} styles * @param {Object} parent * @param {Object} nopad */ H.createElement = function(tag, attribs, styles, parent, nopad) { var el = doc.createElement(tag), css = H.css; if (attribs) { H.extend(el, attribs); } if (nopad) { css(el, { padding: 0, border: 'none', margin: 0 }); } if (styles) { css(el, styles); } if (parent) { parent.appendChild(el); } return el; }; /** * Extend a prototyped class by new members * @param {Object} parent * @param {Object} members */ H.extendClass = function(Parent, members) { var object = function() {}; object.prototype = new Parent(); H.extend(object.prototype, members); return object; }; /** * Pad a string to a given length by adding 0 to the beginning * @param {Number} number * @param {Number} length */ H.pad = function(number, length, padder) { return new Array((length || 2) + 1 - String(number).length).join(padder || 0) + number; }; /** * Return a length based on either the integer value, or a percentage of a base. */ H.relativeLength = function(value, base) { return (/%$/).test(value) ? base * parseFloat(value) / 100 : parseFloat(value); }; /** * Wrap a method with extended functionality, preserving the original function * @param {Object} obj The context object that the method belongs to * @param {String} method The name of the method to extend * @param {Function} func A wrapper function callback. This function is called with the same arguments * as the original function, except that the original function is unshifted and passed as the first * argument. */ H.wrap = function(obj, method, func) { var proceed = obj[method]; obj[method] = function() { var args = Array.prototype.slice.call(arguments); args.unshift(proceed); return func.apply(this, args); }; }; H.getTZOffset = function(timestamp) { var d = H.Date; return ((d.hcGetTimezoneOffset && d.hcGetTimezoneOffset(timestamp)) || d.hcTimezoneOffset || 0) * 60000; }; /** * Based on http://www.php.net/manual/en/function.strftime.php * @param {String} format * @param {Number} timestamp * @param {Boolean} capitalize */ H.dateFormat = function(format, timestamp, capitalize) { if (!H.defined(timestamp) || isNaN(timestamp)) { return H.defaultOptions.lang.invalidDate || ''; } format = H.pick(format, '%Y-%m-%d %H:%M:%S'); var D = H.Date, date = new D(timestamp - H.getTZOffset(timestamp)), key, // used in for constuct below // get the basic time values hours = date[D.hcGetHours](), day = date[D.hcGetDay](), dayOfMonth = date[D.hcGetDate](), month = date[D.hcGetMonth](), fullYear = date[D.hcGetFullYear](), lang = H.defaultOptions.lang, langWeekdays = lang.weekdays, shortWeekdays = lang.shortWeekdays, pad = H.pad, // List all format keys. Custom formats can be added from the outside. replacements = H.extend({ // Day 'a': shortWeekdays ? shortWeekdays[day] : langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon' 'A': langWeekdays[day], // Long weekday, like 'Monday' 'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31 'e': pad(dayOfMonth, 2, ' '), // Day of the month, 1 through 31 'w': day, // Week (none implemented) //'W': weekNumber(), // Month 'b': lang.shortMonths[month], // Short month, like 'Jan' 'B': lang.months[month], // Long month, like 'January' 'm': pad(month + 1), // Two digit month number, 01 through 12 // Year 'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009 'Y': fullYear, // Four digits year, like 2009 // Time 'H': pad(hours), // Two digits hours in 24h format, 00 through 23 'k': hours, // Hours in 24h format, 0 through 23 'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11 'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12 'M': pad(date[D.hcGetMinutes]()), // Two digits minutes, 00 through 59 'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM 'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM 'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59 'L': pad(Math.round(timestamp % 1000), 3) // Milliseconds (naming from Ruby) }, H.dateFormats); // do the replaces for (key in replacements) { while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster format = format.replace( '%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key] ); } } // Optionally capitalize the string and return return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format; }; /** * Format a single variable. Similar to sprintf, without the % prefix. */ H.formatSingle = function(format, val) { var floatRegex = /f$/, decRegex = /\.([0-9])/, lang = H.defaultOptions.lang, decimals; if (floatRegex.test(format)) { // float decimals = format.match(decRegex); decimals = decimals ? decimals[1] : -1; if (val !== null) { val = H.numberFormat( val, decimals, lang.decimalPoint, format.indexOf(',') > -1 ? lang.thousandsSep : '' ); } } else { val = H.dateFormat(format, val); } return val; }; /** * Format a string according to a subset of the rules of Python's String.format method. */ H.format = function(str, ctx) { var splitter = '{', isInside = false, segment, valueAndFormat, path, i, len, ret = [], val, index; while (str) { index = str.indexOf(splitter); if (index === -1) { break; } segment = str.slice(0, index); if (isInside) { // we're on the closing bracket looking back valueAndFormat = segment.split(':'); path = valueAndFormat.shift().split('.'); // get first and leave format len = path.length; val = ctx; // Assign deeper paths for (i = 0; i < len; i++) { val = val[path[i]]; } // Format the replacement if (valueAndFormat.length) { val = H.formatSingle(valueAndFormat.join(':'), val); } // Push the result and advance the cursor ret.push(val); } else { ret.push(segment); } str = str.slice(index + 1); // the rest isInside = !isInside; // toggle splitter = isInside ? '}' : '{'; // now look for next matching bracket } ret.push(str); return ret.join(''); }; /** * Get the magnitude of a number */ H.getMagnitude = function(num) { return Math.pow(10, Math.floor(Math.log(num) / Math.LN10)); }; /** * Take an interval and normalize it to multiples of 1, 2, 2.5 and 5 * @param {Number} interval * @param {Array} multiples * @param {Number} magnitude * @param {Object} options */ H.normalizeTickInterval = function(interval, multiples, magnitude, allowDecimals, preventExceed) { var normalized, i, retInterval = interval; // round to a tenfold of 1, 2, 2.5 or 5 magnitude = H.pick(magnitude, 1); normalized = interval / magnitude; // multiples for a linear scale if (!multiples) { multiples = [1, 2, 2.5, 5, 10]; // the allowDecimals option if (allowDecimals === false) { if (magnitude === 1) { multiples = [1, 2, 5, 10]; } else if (magnitude <= 0.1) { multiples = [1 / magnitude]; } } } // normalize the interval to the nearest multiple for (i = 0; i < multiples.length; i++) { retInterval = multiples[i]; if ((preventExceed && retInterval * magnitude >= interval) || // only allow tick amounts smaller than natural (!preventExceed && (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2))) { break; } } // multiply back to the correct magnitude retInterval *= magnitude; return retInterval; }; /** * Utility method that sorts an object array and keeping the order of equal items. * ECMA script standard does not specify the behaviour when items are equal. */ H.stableSort = function(arr, sortFunction) { var length = arr.length, sortValue, i; // Add index to each item for (i = 0; i < length; i++) { arr[i].safeI = i; // stable sort index } arr.sort(function(a, b) { sortValue = sortFunction(a, b); return sortValue === 0 ? a.safeI - b.safeI : sortValue; }); // Remove index from items for (i = 0; i < length; i++) { delete arr[i].safeI; // stable sort index } }; /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ H.arrayMin = function(data) { var i = data.length, min = data[0]; while (i--) { if (data[i] < min) { min = data[i]; } } return min; }; /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ H.arrayMax = function(data) { var i = data.length, max = data[0]; while (i--) { if (data[i] > max) { max = data[i]; } } return max; }; /** * Utility method that destroys any SVGElement or VMLElement that are properties on the given object. * It loops all properties and invokes destroy if there is a destroy method. The property is * then delete'ed. * @param {Object} The object to destroy properties on * @param {Object} Exception, do not destroy this property, only delete it. */ H.destroyObjectProperties = function(obj, except) { var n; for (n in obj) { // If the object is non-null and destroy is defined if (obj[n] && obj[n] !== except && obj[n].destroy) { // Invoke the destroy obj[n].destroy(); } // Delete the property from the object. delete obj[n]; } }; /** * Discard an element by moving it to the bin and delete * @param {Object} The HTML node to discard */ H.discardElement = function(element) { var garbageBin = H.garbageBin; // create a garbage bin element, not part of the DOM if (!garbageBin) { garbageBin = H.createElement('div'); } // move the node and empty bin if (element) { garbageBin.appendChild(element); } garbageBin.innerHTML = ''; }; /** * Fix JS round off float errors * @param {Number} num */ H.correctFloat = function(num, prec) { return parseFloat( num.toPrecision(prec || 14) ); }; /** * Set the global animation to either a given value, or fall back to the * given chart's animation option * @param {Object} animation * @param {Object} chart */ H.setAnimation = function(animation, chart) { chart.renderer.globalAnimation = H.pick(animation, chart.options.chart.animation, true); }; /** * Get the animation in object form, where a disabled animation is always * returned with duration: 0 */ H.animObject = function(animation) { return H.isObject(animation) ? H.merge(animation) : { duration: animation ? 500 : 0 }; }; /** * The time unit lookup */ H.timeUnits = { millisecond: 1, second: 1000, minute: 60000, hour: 3600000, day: 24 * 3600000, week: 7 * 24 * 3600000, month: 28 * 24 * 3600000, year: 364 * 24 * 3600000 }; /** * Format a number and return a string based on input settings * @param {Number} number The input number to format * @param {Number} decimals The amount of decimals * @param {String} decimalPoint The decimal point, defaults to the one given in the lang options * @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options */ H.numberFormat = function(number, decimals, decimalPoint, thousandsSep) { number = +number || 0; decimals = +decimals; var lang = H.defaultOptions.lang, origDec = (number.toString().split('.')[1] || '').length, decimalComponent, strinteger, thousands, absNumber = Math.abs(number), ret; if (decimals === -1) { decimals = Math.min(origDec, 20); // Preserve decimals. Not huge numbers (#3793). } else if (!H.isNumber(decimals)) { decimals = 2; } // A string containing the positive integer component of the number strinteger = String(H.pInt(absNumber.toFixed(decimals))); // Leftover after grouping into thousands. Can be 0, 1 or 3. thousands = strinteger.length > 3 ? strinteger.length % 3 : 0; // Language decimalPoint = H.pick(decimalPoint, lang.decimalPoint); thousandsSep = H.pick(thousandsSep, lang.thousandsSep); // Start building the return ret = number < 0 ? '-' : ''; // Add the leftover after grouping into thousands. For example, in the number 42 000 000, // this line adds 42. ret += thousands ? strinteger.substr(0, thousands) + thousandsSep : ''; // Add the remaining thousands groups, joined by the thousands separator ret += strinteger.substr(thousands).replace(/(\d{3})(?=\d)/g, '$1' + thousandsSep); // Add the decimal point and the decimal component if (decimals) { // Get the decimal component, and add power to avoid rounding errors with float numbers (#4573) decimalComponent = Math.abs(absNumber - strinteger + Math.pow(10, -Math.max(decimals, origDec) - 1)); ret += decimalPoint + decimalComponent.toFixed(decimals).slice(2); } return ret; }; /** * Easing definition * @param {Number} pos Current position, ranging from 0 to 1 */ Math.easeInOutSine = function(pos) { return -0.5 * (Math.cos(Math.PI * pos) - 1); }; /** * Internal method to return CSS value for given element and property */ H.getStyle = function(el, prop) { var style; // For width and height, return the actual inner pixel size (#4913) if (prop === 'width') { return Math.min(el.offsetWidth, el.scrollWidth) - H.getStyle(el, 'padding-left') - H.getStyle(el, 'padding-right'); } else if (prop === 'height') { return Math.min(el.offsetHeight, el.scrollHeight) - H.getStyle(el, 'padding-top') - H.getStyle(el, 'padding-bottom'); } // Otherwise, get the computed style style = win.getComputedStyle(el, undefined); return style && H.pInt(style.getPropertyValue(prop)); }; /** * Return the index of an item in an array, or -1 if not found */ H.inArray = function(item, arr) { return arr.indexOf ? arr.indexOf(item) : [].indexOf.call(arr, item); }; /** * Filter an array */ H.grep = function(elements, callback) { return [].filter.call(elements, callback); }; /** * Map an array */ H.map = function(arr, fn) { var results = [], i = 0, len = arr.length; for (; i < len; i++) { results[i] = fn.call(arr[i], arr[i], i, arr); } return results; }; /** * Get the element's offset position, corrected by overflow:auto. */ H.offset = function(el) { var docElem = doc.documentElement, box = el.getBoundingClientRect(); return { top: box.top + (win.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0), left: box.left + (win.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0) }; }; /** * Stop running animation. * A possible extension to this would be to stop a single property, when * we want to continue animating others. Then assign the prop to the timer * in the Fx.run method, and check for the prop here. This would be an improvement * in all cases where we stop the animation from .attr. Instead of stopping * everything, we can just stop the actual attributes we're setting. */ H.stop = function(el) { var i = timers.length; // Remove timers related to this element (#4519) while (i--) { if (timers[i].elem === el) { timers[i].stopped = true; // #4667 } } }; /** * Utility for iterating over an array. * @param {Array} arr * @param {Function} fn */ H.each = function(arr, fn, ctx) { // modern browsers return Array.prototype.forEach.call(arr, fn, ctx); }; /** * Add an event listener */ H.addEvent = function(el, type, fn) { var events = el.hcEvents = el.hcEvents || {}; function wrappedFn(e) { e.target = e.srcElement || win; // #2820 fn.call(el, e); } // Handle DOM events in modern browsers if (el.addEventListener) { el.addEventListener(type, fn, false); // Handle old IE implementation } else if (el.attachEvent) { if (!el.hcEventsIE) { el.hcEventsIE = {}; } // Link wrapped fn with original fn, so we can get this in removeEvent el.hcEventsIE[fn.toString()] = wrappedFn; el.attachEvent('on' + type, wrappedFn); } if (!events[type]) { events[type] = []; } events[type].push(fn); }; /** * Remove event added with addEvent */ H.removeEvent = function(el, type, fn) { var events, hcEvents = el.hcEvents, index; function removeOneEvent(type, fn) { if (el.removeEventListener) { el.removeEventListener(type, fn, false); } else if (el.attachEvent) { fn = el.hcEventsIE[fn.toString()]; el.detachEvent('on' + type, fn); } } function removeAllEvents() { var types, len, n; if (!el.nodeName) { return; // break on non-DOM events } if (type) { types = {}; types[type] = true; } else { types = hcEvents; } for (n in types) { if (hcEvents[n]) { len = hcEvents[n].length; while (len--) { removeOneEvent(n, hcEvents[n][len]); } } } } if (hcEvents) { if (type) { events = hcEvents[type] || []; if (fn) { index = H.inArray(fn, events); if (index > -1) { events.splice(index, 1); hcEvents[type] = events; } removeOneEvent(type, fn); } else { removeAllEvents(); hcEvents[type] = []; } } else { removeAllEvents(); el.hcEvents = {}; } } }; /** * Fire an event on a custom object */ H.fireEvent = function(el, type, eventArguments, defaultFunction) { var e, hcEvents = el.hcEvents, events, len, i, fn; eventArguments = eventArguments || {}; if (doc.createEvent && (el.dispatchEvent || el.fireEvent)) { e = doc.createEvent('Events'); e.initEvent(type, true, true); //e.target = el; H.extend(e, eventArguments); if (el.dispatchEvent) { el.dispatchEvent(e); } else { el.fireEvent(type, e); } } else if (hcEvents) { events = hcEvents[type] || []; len = events.length; if (!eventArguments.target) { // We're running a custom event H.extend(eventArguments, { // Attach a simple preventDefault function to skip default handler if called. // The built-in defaultPrevented property is not overwritable (#5112) preventDefault: function() { eventArguments.defaultPrevented = true; }, // Setting target to native events fails with clicking the zoom-out button in Chrome. target: el, // If the type is not set, we're running a custom event (#2297). If it is set, // we're running a browser event, and setting it will cause en error in // IE8 (#2465). type: type }); } for (i = 0; i < len; i++) { fn = events[i]; // If the event handler return false, prevent the default handler from executing if (fn && fn.call(el, eventArguments) === false) { eventArguments.preventDefault(); } } } // Run the default if not prevented if (defaultFunction && !eventArguments.defaultPrevented) { defaultFunction(eventArguments); } }; /** * The global animate method, which uses Fx to create individual animators. */ H.animate = function(el, params, opt) { var start, unit = '', end, fx, args, prop; if (!H.isObject(opt)) { // Number or undefined/null args = arguments; opt = { duration: args[2], easing: args[3], complete: args[4] }; } if (!H.isNumber(opt.duration)) { opt.duration = 400; } opt.easing = typeof opt.easing === 'function' ? opt.easing : (Math[opt.easing] || Math.easeInOutSine); opt.curAnim = H.merge(params); for (prop in params) { fx = new H.Fx(el, opt, prop); end = null; if (prop === 'd') { fx.paths = fx.initPath( el, el.d, params.d ); fx.toD = params.d; start = 0; end = 1; } else if (el.attr) { start = el.attr(prop); } else { start = parseFloat(H.getStyle(el, prop)) || 0; if (prop !== 'opacity') { unit = 'px'; } } if (!end) { end = params[prop]; } if (end.match && end.match('px')) { end = end.replace(/px/g, ''); // #4351 } fx.run(start, end, unit); } }; /** * The series type factory. * * @param {string} type The series type name. * @param {string} parent The parent series type name. * @param {object} options The additional default options that is merged with the parent's options. * @param {object} props The properties (functions and primitives) to set on the new prototype. * @param {object} pointProps Members for a series-specific Point prototype if needed. */ H.seriesType = function(type, parent, options, props, pointProps) { // docs: add to API + extending Highcharts var defaultOptions = H.getOptions(), seriesTypes = H.seriesTypes; // Merge the options defaultOptions.plotOptions[type] = H.merge( defaultOptions.plotOptions[parent], options ); // Create the class seriesTypes[type] = H.extendClass(seriesTypes[parent] || function() {}, props); seriesTypes[type].prototype.type = type; // Create the point class if needed if (pointProps) { seriesTypes[type].prototype.pointClass = H.extendClass(H.Point, pointProps); } return seriesTypes[type]; }; /** * Register Highcharts as a plugin in jQuery */ if (win.jQuery) { win.jQuery.fn.highcharts = function() { var args = [].slice.call(arguments); if (this[0]) { // this[0] is the renderTo div // Create the chart if (args[0]) { new H[ // eslint-disable-line no-new H.isString(args[0]) ? args.shift() : 'Chart' // Constructor defaults to Chart ](this[0], args[0], args[1]); return this; } // When called without parameters or with the return argument, return an existing chart return charts[H.attr(this[0], 'data-highcharts-chart')]; } }; } /** * Compatibility section to add support for legacy IE. This can be removed if old IE * support is not needed. */ if (doc && !doc.defaultView) { H.getStyle = function(el, prop) { var val, alias = { width: 'clientWidth', height: 'clientHeight' }[prop]; if (el.style[prop]) { return H.pInt(el.style[prop]); } if (prop === 'opacity') { prop = 'filter'; } // Getting the rendered width and height if (alias) { el.style.zoom = 1; return Math.max(el[alias] - 2 * H.getStyle(el, 'padding'), 0); } val = el.currentStyle[prop.replace(/\-(\w)/g, function(a, b) { return b.toUpperCase(); })]; if (prop === 'filter') { val = val.replace( /alpha\(opacity=([0-9]+)\)/, function(a, b) { return b / 100; } ); } return val === '' ? 1 : H.pInt(val); }; } if (!Array.prototype.forEach) { H.each = function(arr, fn, ctx) { // legacy var i = 0, len = arr.length; for (; i < len; i++) { if (fn.call(ctx, arr[i], i, arr) === false) { return i; } } }; } if (!Array.prototype.indexOf) { H.inArray = function(item, arr) { var len, i = 0; if (arr) { len = arr.length; for (; i < len; i++) { if (arr[i] === item) { return i; } } } return -1; }; } if (!Array.prototype.filter) { H.grep = function(elements, fn) { var ret = [], i = 0, length = elements.length; for (; i < length; i++) { if (fn(elements[i], i)) { ret.push(elements[i]); } } return ret; }; } //--- End compatibility section --- }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var each = H.each, isNumber = H.isNumber, map = H.map, merge = H.merge, pInt = H.pInt; /** * Handle color operations. The object methods are chainable. * @param {String} input The input color in either rbga or hex format */ H.Color = function(input) { // Backwards compatibility, allow instanciation without new if (!(this instanceof H.Color)) { return new H.Color(input); } // Initialize this.init(input); }; H.Color.prototype = { // Collection of parsers. This can be extended from the outside by pushing parsers // to Highcharts.Color.prototype.parsers. parsers: [{ // RGBA color regex: /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/, parse: function(result) { return [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)]; } }, { // HEX color regex: /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/, parse: function(result) { return [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1]; } }, { // RGB color regex: /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/, parse: function(result) { return [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1]; } }], // Collection of named colors. Can be extended from the outside by adding colors // to Highcharts.Color.prototype.names. names: { white: '#ffffff', black: '#000000' }, /** * Parse the input color to rgba array * @param {String} input */ init: function(input) { var result, rgba, i, parser; this.input = input = this.names[input] || input; // Gradients if (input && input.stops) { this.stops = map(input.stops, function(stop) { return new H.Color(stop[1]); }); // Solid colors } else { i = this.parsers.length; while (i-- && !rgba) { parser = this.parsers[i]; result = parser.regex.exec(input); if (result) { rgba = parser.parse(result); } } } this.rgba = rgba || []; }, /** * Return the color a specified format * @param {String} format */ get: function(format) { var input = this.input, rgba = this.rgba, ret; if (this.stops) { ret = merge(input); ret.stops = [].concat(ret.stops); each(this.stops, function(stop, i) { ret.stops[i] = [ret.stops[i][0], stop.get(format)]; }); // it's NaN if gradient colors on a column chart } else if (rgba && isNumber(rgba[0])) { if (format === 'rgb' || (!format && rgba[3] === 1)) { ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')'; } else if (format === 'a') { ret = rgba[3]; } else { ret = 'rgba(' + rgba.join(',') + ')'; } } else { ret = input; } return ret; }, /** * Brighten the color * @param {Number} alpha */ brighten: function(alpha) { var i, rgba = this.rgba; if (this.stops) { each(this.stops, function(stop) { stop.brighten(alpha); }); } else if (isNumber(alpha) && alpha !== 0) { for (i = 0; i < 3; i++) { rgba[i] += pInt(alpha * 255); if (rgba[i] < 0) { rgba[i] = 0; } if (rgba[i] > 255) { rgba[i] = 255; } } } return this; }, /** * Set the color's opacity to a given alpha value * @param {Number} alpha */ setOpacity: function(alpha) { this.rgba[3] = alpha; return this; } }; H.color = function(input) { return new H.Color(input); }; }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var color = H.color, each = H.each, getTZOffset = H.getTZOffset, isTouchDevice = H.isTouchDevice, merge = H.merge, pick = H.pick, svg = H.svg, win = H.win; /* **************************************************************************** * Handle the options * *****************************************************************************/ H.defaultOptions = { symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'], lang: { loading: 'Loading...', months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ], shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // invalidDate: '', decimalPoint: '.', numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels resetZoom: 'Reset zoom', resetZoomTitle: 'Reset zoom level 1:1', thousandsSep: ' ' }, global: { useUTC: true, //timezoneOffset: 0 }, chart: { //animation: true, //alignTicks: false, //reflow: true, //className: null, //events: { load, selection }, //margin: [null], //marginTop: null, //marginRight: null, //marginBottom: null, //marginLeft: null, borderRadius: 0, colorCount: 10, defaultSeriesType: 'line', ignoreHiddenSeries: true, //inverted: false, spacing: [10, 10, 15, 10], //spacingTop: 10, //spacingRight: 10, //spacingBottom: 15, //spacingLeft: 10, //zoomType: '' resetZoomButton: { theme: { zIndex: 20 }, position: { align: 'right', x: -10, //verticalAlign: 'top', y: 10 } // relativeTo: 'plot' }, width: null, height: null }, defs: { dropShadow: { // used by tooltip tagName: 'filter', id: 'drop-shadow', opacity: 0.5, children: [{ tagName: 'feGaussianBlur', in: 'SourceAlpha', stdDeviation: 1 }, { tagName: 'feOffset', dx: 1, dy: 1 }, { tagName: 'feComponentTransfer', children: [{ tagName: 'feFuncA', type: 'linear', slope: 0.3 }] }, { tagName: 'feMerge', children: [{ tagName: 'feMergeNode' }, { tagName: 'feMergeNode', in: 'SourceGraphic' }] }] }, style: { tagName: 'style', textContent: '.highcharts-tooltip{' + 'filter:url(#drop-shadow)' + '}' } }, title: { text: 'Chart title', align: 'center', // floating: false, margin: 15, // x: 0, // verticalAlign: 'top', // y: null, widthAdjust: -44 }, subtitle: { text: '', align: 'center', // floating: false // x: 0, // verticalAlign: 'top', // y: null, widthAdjust: -44 }, plotOptions: {}, labels: { //items: [], style: { //font: defaultFont, position: 'absolute', color: '#333333' } }, legend: { enabled: true, align: 'center', //floating: false, layout: 'horizontal', labelFormatter: function() { return this.name; }, //borderWidth: 0, borderColor: '#999999', borderRadius: 0, navigation: { // animation: true, // arrowSize: 12 // style: {} // text styles }, // margin: 20, // reversed: false, // backgroundColor: null, /*style: { padding: '5px' },*/ itemCheckboxStyle: { position: 'absolute', width: '13px', // for IE precision height: '13px' }, // itemWidth: undefined, squareSymbol: true, // symbolRadius: 0, // symbolWidth: 16, symbolPadding: 5, verticalAlign: 'bottom', // width: undefined, x: 0, y: 0, title: { //text: null } }, loading: { // hideDuration: 100, // showDuration: 0 }, tooltip: { enabled: true, animation: svg, //crosshairs: null, borderRadius: 3, dateTimeLabelFormats: { millisecond: '%A, %b %e, %H:%M:%S.%L', second: '%A, %b %e, %H:%M:%S', minute: '%A, %b %e, %H:%M', hour: '%A, %b %e, %H:%M', day: '%A, %b %e, %Y', week: 'Week from %A, %b %e, %Y', month: '%B %Y', year: '%Y' }, footerFormat: '', //formatter: defaultFormatter, /* todo: em font-size when finished comparing against HC4 headerFormat: '<span style="font-size: 0.85em">{point.key}</span><br/>', */ padding: 8, //shape: 'callout', //shared: false, snap: isTouchDevice ? 25 : 10, headerFormat: '<span class="highcharts-header">{point.key}</span><br/>', pointFormat: '<span class="highcharts-color-{point.colorIndex}">\u25CF</span> {series.name}: <b>{point.y}</b><br/>', //xDateFormat: '%A, %b %e, %Y', //valueDecimals: null, //valuePrefix: '', //valueSuffix: '' }, credits: { enabled: true, href: 'http://www.highcharts.com', position: { align: 'right', x: -10, verticalAlign: 'bottom', y: -5 }, text: 'Highcharts.com' } }; /** * Set the time methods globally based on the useUTC option. Time method can be either * local time or UTC (default). */ function setTimeMethods() { var globalOptions = H.defaultOptions.global, Date, useUTC = globalOptions.useUTC, GET = useUTC ? 'getUTC' : 'get', SET = useUTC ? 'setUTC' : 'set'; H.Date = Date = globalOptions.Date || win.Date; // Allow using a different Date class Date.hcTimezoneOffset = useUTC && globalOptions.timezoneOffset; Date.hcGetTimezoneOffset = useUTC && globalOptions.getTimezoneOffset; Date.hcMakeTime = function(year, month, date, hours, minutes, seconds) { var d; if (useUTC) { d = Date.UTC.apply(0, arguments); d += getTZOffset(d); } else { d = new Date( year, month, pick(date, 1), pick(hours, 0), pick(minutes, 0), pick(seconds, 0) ).getTime(); } return d; }; each(['Minutes', 'Hours', 'Day', 'Date', 'Month', 'FullYear'], function(s) { Date['hcGet' + s] = GET + s; }); each(['Milliseconds', 'Seconds', 'Minutes', 'Hours', 'Date', 'Month', 'FullYear'], function(s) { Date['hcSet' + s] = SET + s; }); } /** * Merge the default options with custom options and return the new options structure * @param {Object} options The new custom options */ H.setOptions = function(options) { // Copy in the default options H.defaultOptions = merge(true, H.defaultOptions, options); // Apply UTC setTimeMethods(); return H.defaultOptions; }; /** * Get the updated default options. Until 3.0.7, merely exposing defaultOptions for outside modules * wasn't enough because the setOptions method created a new object. */ H.getOptions = function() { return H.defaultOptions; }; // Series defaults H.defaultPlotOptions = H.defaultOptions.plotOptions; // set the default time methods setTimeMethods(); }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var SVGElement, SVGRenderer, addEvent = H.addEvent, animate = H.animate, attr = H.attr, charts = H.charts, color = H.color, css = H.css, createElement = H.createElement, defined = H.defined, deg2rad = H.deg2rad, destroyObjectProperties = H.destroyObjectProperties, doc = H.doc, each = H.each, extend = H.extend, erase = H.erase, grep = H.grep, hasTouch = H.hasTouch, isArray = H.isArray, isFirefox = H.isFirefox, isMS = H.isMS, isObject = H.isObject, isString = H.isString, isWebKit = H.isWebKit, merge = H.merge, noop = H.noop, pick = H.pick, pInt = H.pInt, removeEvent = H.removeEvent, splat = H.splat, stop = H.stop, svg = H.svg, SVG_NS = H.SVG_NS, symbolSizes = H.symbolSizes, win = H.win; /** * A wrapper object for SVG elements */ SVGElement = H.SVGElement = function() { return this; }; SVGElement.prototype = { // Default base for animation opacity: 1, SVG_NS: SVG_NS, // For labels, these CSS properties are applied to the <text> node directly textProps: ['direction', 'fontSize', 'fontWeight', 'fontFamily', 'fontStyle', 'color', 'lineHeight', 'width', 'textDecoration', 'textOverflow', 'textShadow' ], /** * Initialize the SVG renderer * @param {Object} renderer * @param {String} nodeName */ init: function(renderer, nodeName) { var wrapper = this; wrapper.element = nodeName === 'span' ? createElement(nodeName) : doc.createElementNS(wrapper.SVG_NS, nodeName); wrapper.renderer = renderer; }, /** * Animate a given attribute * @param {Object} params * @param {Number} options Options include duration, easing, step and complete * @param {Function} complete Function to perform at the end of animation */ animate: function(params, options, complete) { var animOptions = pick(options, this.renderer.globalAnimation, true); stop(this); // stop regardless of animation actually running, or reverting to .attr (#607) if (animOptions) { if (complete) { // allows using a callback with the global animation without overwriting it animOptions.complete = complete; } animate(this, params, animOptions); } else { this.attr(params, null, complete); } return this; }, /** * Build an SVG gradient out of a common JavaScript configuration object */ colorGradient: function(color, prop, elem) { var renderer = this.renderer, colorObject, gradName, gradAttr, radAttr, gradients, gradientObject, stops, stopColor, stopOpacity, radialReference, n, id, key = [], value; // Apply linear or radial gradients if (color.linearGradient) { gradName = 'linearGradient'; } else if (color.radialGradient) { gradName = 'radialGradient'; } if (gradName) { gradAttr = color[gradName]; gradients = renderer.gradients; stops = color.stops; radialReference = elem.radialReference; // Keep < 2.2 kompatibility if (isArray(gradAttr)) { color[gradName] = gradAttr = { x1: gradAttr[0], y1: gradAttr[1], x2: gradAttr[2], y2: gradAttr[3], gradientUnits: 'userSpaceOnUse' }; } // Correct the radial gradient for the radial reference system if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) { radAttr = gradAttr; // Save the radial attributes for updating gradAttr = merge(gradAttr, renderer.getRadialAttr(radialReference, radAttr), { gradientUnits: 'userSpaceOnUse' } ); } // Build the unique key to detect whether we need to create a new element (#1282) for (n in gradAttr) { if (n !== 'id') { key.push(n, gradAttr[n]); } } for (n in stops) { key.push(stops[n]); } key = key.join(','); // Check if a gradient object with the same config object is created within this renderer if (gradients[key]) { id = gradients[key].attr('id'); } else { // Set the id and create the element gradAttr.id = id = 'highcharts-' + H.idCounter++; gradients[key] = gradientObject = renderer.createElement(gradName) .attr(gradAttr) .add(renderer.defs); gradientObject.radAttr = radAttr; // The gradient needs to keep a list of stops to be able to destroy them gradientObject.stops = []; each(stops, function(stop) { var stopObject; if (stop[1].indexOf('rgba') === 0) { colorObject = H.color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } stopObject = renderer.createElement('stop').attr({ offset: stop[0], 'stop-color': stopColor, 'stop-opacity': stopOpacity }).add(gradientObject); // Add the stop element to the gradient gradientObject.stops.push(stopObject); }); } // Set the reference to the gradient object value = 'url(' + renderer.url + '#' + id + ')'; elem.setAttribute(prop, value); elem.gradient = key; // Allow the color to be concatenated into tooltips formatters etc. (#2995) color.toString = function() { return value; }; } }, /** * Apply a polyfill to the text-stroke CSS property, by copying the text element * and apply strokes to the copy. * * Contrast checks at http://jsfiddle.net/highcharts/43soe9m1/2/ */ applyTextShadow: function(textShadow) { var elem = this.element, tspans, hasContrast = textShadow.indexOf('contrast') !== -1, styles = {}, forExport = this.renderer.forExport, // IE10 and IE11 report textShadow in elem.style even though it doesn't work. Check // this again with new IE release. In exports, the rendering is passed to PhantomJS. supports = this.renderer.forExport || (elem.style.textShadow !== undefined && !isMS); // When the text shadow is set to contrast, use dark stroke for light text and vice versa if (hasContrast) { styles.textShadow = textShadow = textShadow.replace(/contrast/g, this.renderer.getContrast(elem.style.fill)); } // Safari with retina displays as well as PhantomJS bug (#3974). Firefox does not tolerate this, // it removes the text shadows. if (isWebKit || forExport) { styles.textRendering = 'geometricPrecision'; } /* Selective side-by-side testing in supported browser (http://jsfiddle.net/highcharts/73L1ptrh/) if (elem.textContent.indexOf('2.') === 0) { elem.style['text-shadow'] = 'none'; supports = false; } // */ // No reason to polyfill, we've got native support if (supports) { this.css(styles); // Apply altered textShadow or textRendering workaround } else { this.fakeTS = true; // Fake text shadow // In order to get the right y position of the clones, // copy over the y setter this.ySetter = this.xSetter; tspans = [].slice.call(elem.getElementsByTagName('tspan')); each(textShadow.split(/\s?,\s?/g), function(textShadow) { var firstChild = elem.firstChild, color, strokeWidth; textShadow = textShadow.split(' '); color = textShadow[textShadow.length - 1]; // Approximately tune the settings to the text-shadow behaviour strokeWidth = textShadow[textShadow.length - 2]; if (strokeWidth) { each(tspans, function(tspan, y) { var clone; // Let the first line start at the correct X position if (y === 0) { tspan.setAttribute('x', elem.getAttribute('x')); y = elem.getAttribute('y'); tspan.setAttribute('y', y || 0); if (y === null) { elem.setAttribute('y', 0); } } // Create the clone and apply shadow properties clone = tspan.cloneNode(1); attr(clone, { 'class': 'highcharts-text-shadow', 'fill': color, 'stroke': color, 'stroke-opacity': 1 / Math.max(pInt(strokeWidth), 3), 'stroke-width': strokeWidth, 'stroke-linejoin': 'round' }); elem.insertBefore(clone, firstChild); }); } }); } }, /** * Set or get a given attribute * @param {Object|String} hash * @param {Mixed|Undefined} val */ attr: function(hash, val, complete) { var key, value, element = this.element, hasSetSymbolSize, ret = this, skipAttr, setter; // single key-value pair if (typeof hash === 'string' && val !== undefined) { key = hash; hash = {}; hash[key] = val; } // used as a getter: first argument is a string, second is undefined if (typeof hash === 'string') { ret = (this[hash + 'Getter'] || this._defaultGetter).call(this, hash, element); // setter } else { for (key in hash) { value = hash[key]; skipAttr = false; if (this.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) { if (!hasSetSymbolSize) { this.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } if (this.rotation && (key === 'x' || key === 'y')) { this.doTransform = true; } if (!skipAttr) { setter = this[key + 'Setter'] || this._defaultSetter; setter.call(this, value, key, element); } } // Update transform. Do this outside the loop to prevent redundant updating for batch setting // of attributes. if (this.doTransform) { this.updateTransform(); this.doTransform = false; } } // In accordance with animate, run a complete callback if (complete) { complete(); } return ret; }, /** * Add a class name to an element */ addClass: function(className, replace) { var currentClassName = this.attr('class') || ''; if (currentClassName.indexOf(className) === -1) { if (!replace) { className = (currentClassName + (currentClassName ? ' ' : '') + className).replace(' ', ' '); } this.attr('class', className); } return this; }, hasClass: function(className) { return attr(this.element, 'class').indexOf(className) !== -1; }, removeClass: function(className) { attr(this.element, 'class', (attr(this.element, 'class') || '').replace(className, '')); return this; }, /** * If one of the symbol size affecting parameters are changed, * check all the others only once for each call to an element's * .attr() method * @param {Object} hash */ symbolAttr: function(hash) { var wrapper = this; each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function(key) { wrapper[key] = pick(hash[key], wrapper[key]); }); wrapper.attr({ d: wrapper.renderer.symbols[wrapper.symbolName]( wrapper.x, wrapper.y, wrapper.width, wrapper.height, wrapper ) }); }, /** * Apply a clipping path to this object * @param {String} id */ clip: function(clipRect) { return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : 'none'); }, /** * Calculate the coordinates needed for drawing a rectangle crisply and return the * calculated attributes * @param {Number} strokeWidth * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ crisp: function(rect, strokeWidth) { var wrapper = this, key, attribs = {}, normalizer; strokeWidth = strokeWidth || rect.strokeWidth || 0; normalizer = Math.round(strokeWidth) % 2 / 2; // Math.round because strokeWidth can sometimes have roundoff errors // normalize for crisp edges rect.x = Math.floor(rect.x || wrapper.x || 0) + normalizer; rect.y = Math.floor(rect.y || wrapper.y || 0) + normalizer; rect.width = Math.floor((rect.width || wrapper.width || 0) - 2 * normalizer); rect.height = Math.floor((rect.height || wrapper.height || 0) - 2 * normalizer); if (defined(rect.strokeWidth)) { rect.strokeWidth = strokeWidth; } for (key in rect) { if (wrapper[key] !== rect[key]) { // only set attribute if changed wrapper[key] = attribs[key] = rect[key]; } } return attribs; }, /** * Set styles for the element * @param {Object} styles */ css: function(styles) { var elemWrapper = this, oldStyles = elemWrapper.styles, newStyles = {}, elem = elemWrapper.element, textWidth, n, serializedCss = '', hyphenate, hasNew = !oldStyles; // convert legacy if (styles && styles.color) { styles.fill = styles.color; } // Filter out existing styles to increase performance (#2640) if (oldStyles) { for (n in styles) { if (styles[n] !== oldStyles[n]) { newStyles[n] = styles[n]; hasNew = true; } } } if (hasNew) { textWidth = elemWrapper.textWidth = (styles && styles.width && elem.nodeName.toLowerCase() === 'text' && pInt(styles.width)) || elemWrapper.textWidth; // #3501 // Merge the new styles with the old ones if (oldStyles) { styles = extend( oldStyles, newStyles ); } // store object elemWrapper.styles = styles; if (textWidth && (!svg && elemWrapper.renderer.forExport)) { delete styles.width; } // serialize and set style attribute if (isMS && !svg) { css(elemWrapper.element, styles); } else { hyphenate = function(a, b) { return '-' + b.toLowerCase(); }; for (n in styles) { serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';'; } attr(elem, 'style', serializedCss); // #1881 } // Rebuild text after added if (elemWrapper.added && textWidth) { elemWrapper.renderer.buildText(elemWrapper); } } return elemWrapper; }, /** * Get a computed style */ getStyle: function(prop) { return win.getComputedStyle(this.element || this, '').getPropertyValue(prop); }, /** * Get a computed style in pixel values */ strokeWidth: function() { var val = this.getStyle('stroke-width'), ret, dummy; // Read pixel values directly if (val.indexOf('px') === val.length - 2) { ret = pInt(val); // Other values like em, pt etc need to be measured } else { dummy = doc.createElementNS(SVG_NS, 'rect'); attr(dummy, { 'width': val, 'stroke-width': 0 }); this.element.parentNode.appendChild(dummy); ret = dummy.getBBox().width; dummy.parentNode.removeChild(dummy); } return ret; }, /** * Add an event listener * @param {String} eventType * @param {Function} handler */ on: function(eventType, handler) { var svgElement = this, element = svgElement.element; // touch if (hasTouch && eventType === 'click') { element.ontouchstart = function(e) { svgElement.touchEventFired = Date.now(); e.preventDefault(); handler.call(element, e); }; element.onclick = function(e) { if (win.navigator.userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269 handler.call(element, e); } }; } else { // simplest possible event model for internal use element['on' + eventType] = handler; } return this; }, /** * Set the coordinates needed to draw a consistent radial gradient across * pie slices regardless of positioning inside the chart. The format is * [centerX, centerY, diameter] in pixels. */ setRadialReference: function(coordinates) { var existingGradient = this.renderer.gradients[this.element.gradient]; this.element.radialReference = coordinates; // On redrawing objects with an existing gradient, the gradient needs // to be repositioned (#3801) if (existingGradient && existingGradient.radAttr) { existingGradient.animate( this.renderer.getRadialAttr( coordinates, existingGradient.radAttr ) ); } return this; }, /** * Move an object and its children by x and y values * @param {Number} x * @param {Number} y */ translate: function(x, y) { return this.attr({ translateX: x, translateY: y }); }, /** * Invert a group, rotate and flip */ invert: function(inverted) { var wrapper = this; wrapper.inverted = inverted; wrapper.updateTransform(); return wrapper; }, /** * Private method to update the transform attribute based on internal * properties */ updateTransform: function() { var wrapper = this, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, scaleX = wrapper.scaleX, scaleY = wrapper.scaleY, inverted = wrapper.inverted, rotation = wrapper.rotation, element = wrapper.element, transform; // flipping affects translate as adjustment for flipping around the group's axis if (inverted) { translateX += wrapper.attr('width'); translateY += wrapper.attr('height'); } // Apply translate. Nearly all transformed elements have translation, so instead // of checking for translate = 0, do it always (#1767, #1846). transform = ['translate(' + translateX + ',' + translateY + ')']; // apply rotation if (inverted) { transform.push('rotate(90) scale(-1,1)'); } else if (rotation) { // text rotation transform.push('rotate(' + rotation + ' ' + (element.getAttribute('x') || 0) + ' ' + (element.getAttribute('y') || 0) + ')'); // Delete bBox memo when the rotation changes //delete wrapper.bBox; } // apply scale if (defined(scaleX) || defined(scaleY)) { transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')'); } if (transform.length) { element.setAttribute('transform', transform.join(' ')); } }, /** * Bring the element to the front */ toFront: function() { var element = this.element; element.parentNode.appendChild(element); return this; }, /** * Break down alignment options like align, verticalAlign, x and y * to x and y relative to the chart. * * @param {Object} alignOptions * @param {Boolean} alignByTranslate * @param {String[Object} box The box to align to, needs a width and height. When the * box is a string, it refers to an object in the Renderer. For example, when * box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height * x and y properties. * */ align: function(alignOptions, alignByTranslate, box) { var align, vAlign, x, y, attribs = {}, alignTo, renderer = this.renderer, alignedObjects = renderer.alignedObjects, alignFactor, vAlignFactor; // First call on instanciate if (alignOptions) { this.alignOptions = alignOptions; this.alignByTranslate = alignByTranslate; if (!box || isString(box)) { // boxes other than renderer handle this internally this.alignTo = alignTo = box || 'renderer'; erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize alignedObjects.push(this); box = null; // reassign it below } // When called on resize, no arguments are supplied } else { alignOptions = this.alignOptions; alignByTranslate = this.alignByTranslate; alignTo = this.alignTo; } box = pick(box, renderer[alignTo], renderer); // Assign variables align = alignOptions.align; vAlign = alignOptions.verticalAlign; x = (box.x || 0) + (alignOptions.x || 0); // default: left align y = (box.y || 0) + (alignOptions.y || 0); // default: top align // Align if (align === 'right') { alignFactor = 1; } else if (align === 'center') { alignFactor = 2; } if (alignFactor) { x += (box.width - (alignOptions.width || 0)) / alignFactor; } attribs[alignByTranslate ? 'translateX' : 'x'] = Math.round(x); // Vertical align if (vAlign === 'bottom') { vAlignFactor = 1; } else if (vAlign === 'middle') { vAlignFactor = 2; } if (vAlignFactor) { y += (box.height - (alignOptions.height || 0)) / vAlignFactor; } attribs[alignByTranslate ? 'translateY' : 'y'] = Math.round(y); // Animate only if already placed this[this.placed ? 'animate' : 'attr'](attribs); this.placed = true; this.alignAttr = attribs; return this; }, /** * Get the bounding box (width, height, x and y) for the element */ getBBox: function(reload, rot) { var wrapper = this, bBox, // = wrapper.bBox, renderer = wrapper.renderer, width, height, rotation, rad, element = wrapper.element, styles = wrapper.styles, fontSize, textStr = wrapper.textStr, textShadow, elemStyle = element.style, toggleTextShadowShim, cache = renderer.cache, cacheKeys = renderer.cacheKeys, cacheKey; rotation = pick(rot, wrapper.rotation); rad = rotation * deg2rad; fontSize = element && SVGElement.prototype.getStyle.call(element, 'font-size'); if (textStr !== undefined) { cacheKey = // Since numbers are monospaced, and numerical labels appear a lot in a chart, // we assume that a label of n characters has the same bounding box as others // of the same length. textStr.toString().replace(/[0-9]/g, '0') + // Properties that affect bounding box ['', rotation || 0, fontSize, element.style.width].join(','); } if (cacheKey && !reload) { bBox = cache[cacheKey]; } // No cache found if (!bBox) { // SVG elements if (element.namespaceURI === wrapper.SVG_NS || renderer.forExport) { try { // Fails in Firefox if the container has display: none. // When the text shadow shim is used, we need to hide the fake shadows // to get the correct bounding box (#3872) toggleTextShadowShim = this.fakeTS && function(display) { each(element.querySelectorAll('.highcharts-text-shadow'), function(tspan) { tspan.style.display = display; }); }; // Workaround for #3842, Firefox reporting wrong bounding box for shadows if (isFirefox && elemStyle.textShadow) { textShadow = elemStyle.textShadow; elemStyle.textShadow = ''; } else if (toggleTextShadowShim) { toggleTextShadowShim('none'); } bBox = element.getBBox ? // SVG: use extend because IE9 is not allowed to change width and height in case // of rotation (below) extend({}, element.getBBox()) : // Legacy IE in export mode { width: element.offsetWidth, height: element.offsetHeight }; // #3842 if (textShadow) { elemStyle.textShadow = textShadow; } else if (toggleTextShadowShim) { toggleTextShadowShim(''); } } catch (e) {} // If the bBox is not set, the try-catch block above failed. The other condition // is for Opera that returns a width of -Infinity on hidden elements. if (!bBox || bBox.width < 0) { bBox = { width: 0, height: 0 }; } // VML Renderer or useHTML within SVG } else { bBox = wrapper.htmlGetBBox(); } // True SVG elements as well as HTML elements in modern browsers using the .useHTML option // need to compensated for rotation if (renderer.isSVG) { width = bBox.width; height = bBox.height; // Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669, #2568) if (isMS && styles && styles.fontSize === '11px' && height.toPrecision(3) === '16.9') { bBox.height = height = 14; } // Adjust for rotated text if (rotation) { bBox.width = Math.abs(height * Math.sin(rad)) + Math.abs(width * Math.cos(rad)); bBox.height = Math.abs(height * Math.cos(rad)) + Math.abs(width * Math.sin(rad)); } } // Cache it. When loading a chart in a hidden iframe in Firefox and IE/Edge, the // bounding box height is 0, so don't cache it (#5620). if (cacheKey && bBox.height > 0) { // Rotate (#4681) while (cacheKeys.length > 250) { delete cache[cacheKeys.shift()]; } if (!cache[cacheKey]) { cacheKeys.push(cacheKey); } cache[cacheKey] = bBox; } } return bBox; }, /** * Show the element */ show: function(inherit) { return this.attr({ visibility: inherit ? 'inherit' : 'visible' }); }, /** * Hide the element */ hide: function() { return this.attr({ visibility: 'hidden' }); }, fadeOut: function(duration) { var elemWrapper = this; elemWrapper.animate({ opacity: 0 }, { duration: duration || 150, complete: function() { elemWrapper.attr({ y: -9999 }); // #3088, assuming we're only using this for tooltips } }); }, /** * Add the element * @param {Object|Undefined} parent Can be an element, an element wrapper or undefined * to append the element to the renderer.box. */ add: function(parent) { var renderer = this.renderer, element = this.element, inserted; if (parent) { this.parentGroup = parent; } // mark as inverted this.parentInverted = parent && parent.inverted; // build formatted text if (this.textStr !== undefined) { renderer.buildText(this); } // Mark as added this.added = true; // If we're adding to renderer root, or other elements in the group // have a z index, we need to handle it if (!parent || parent.handleZ || this.zIndex) { inserted = this.zIndexSetter(); } // If zIndex is not handled, append at the end if (!inserted) { (parent ? parent.element : renderer.box).appendChild(element); } // fire an event for internal hooks if (this.onAdd) { this.onAdd(); } return this; }, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function(element) { var parentNode = element.parentNode; if (parentNode) { parentNode.removeChild(element); } }, /** * Destroy the element and element wrapper */ destroy: function() { var wrapper = this, element = wrapper.element || {}, parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && wrapper.parentGroup, grandParent, key, i; // remove events element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null; stop(wrapper); // stop running animations if (wrapper.clipPath) { wrapper.clipPath = wrapper.clipPath.destroy(); } // Destroy stops in case this is a gradient object if (wrapper.stops) { for (i = 0; i < wrapper.stops.length; i++) { wrapper.stops[i] = wrapper.stops[i].destroy(); } wrapper.stops = null; } // remove element wrapper.safeRemoveChild(element); // In case of useHTML, clean up empty containers emulating SVG groups (#1960, #2393, #2697). while (parentToClean && parentToClean.div && parentToClean.div.childNodes.length === 0) { grandParent = parentToClean.parentGroup; wrapper.safeRemoveChild(parentToClean.div); delete parentToClean.div; parentToClean = grandParent; } // remove from alignObjects if (wrapper.alignTo) { erase(wrapper.renderer.alignedObjects, wrapper); } for (key in wrapper) { delete wrapper[key]; } return null; }, xGetter: function(key) { if (this.element.nodeName === 'circle') { if (key === 'x') { key = 'cx'; } else if (key === 'y') { key = 'cy'; } } return this._defaultGetter(key); }, /** * Get the current value of an attribute or pseudo attribute, used mainly * for animation. */ _defaultGetter: function(key) { var ret = pick(this[key], this.element ? this.element.getAttribute(key) : null, 0); if (/^[\-0-9\.]+$/.test(ret)) { // is numerical ret = parseFloat(ret); } return ret; }, dSetter: function(value, key, element) { if (value && value.join) { // join path value = value.join(' '); } if (/(NaN| {2}|^$)/.test(value)) { value = 'M 0 0'; } element.setAttribute(key, value); this[key] = value; }, alignSetter: function(value) { var convert = { left: 'start', center: 'middle', right: 'end' }; this.element.setAttribute('text-anchor', convert[value]); }, opacitySetter: function(value, key, element) { this[key] = value; element.setAttribute(key, value); }, titleSetter: function(value) { var titleNode = this.element.getElementsByTagName('title')[0]; if (!titleNode) { titleNode = doc.createElementNS(this.SVG_NS, 'title'); this.element.appendChild(titleNode); } // Remove text content if it exists if (titleNode.firstChild) { titleNode.removeChild(titleNode.firstChild); } titleNode.appendChild( doc.createTextNode( (String(pick(value), '')).replace(/<[^>]*>/g, '') // #3276, #3895 ) ); }, textSetter: function(value) { if (value !== this.textStr) { // Delete bBox memo when the text changes delete this.bBox; this.textStr = value; if (this.added) { this.renderer.buildText(this); } } }, fillSetter: function(value, key, element) { if (typeof value === 'string') { element.setAttribute(key, value); } else if (value) { this.colorGradient(value, key, element); } }, visibilitySetter: function(value, key, element) { // IE9-11 doesn't handle visibilty:inherit well, so we remove the attribute instead (#2881, #3909) if (value === 'inherit') { element.removeAttribute(key); } else { element.setAttribute(key, value); } }, zIndexSetter: function(value, key) { var renderer = this.renderer, parentGroup = this.parentGroup, parentWrapper = parentGroup || renderer, parentNode = parentWrapper.element || renderer.box, childNodes, otherElement, otherZIndex, element = this.element, inserted, run = this.added, i; if (defined(value)) { element.zIndex = value; // So we can read it for other elements in the group value = +value; if (this[key] === value) { // Only update when needed (#3865) run = false; } this[key] = value; } // Insert according to this and other elements' zIndex. Before .add() is called, // nothing is done. Then on add, or by later calls to zIndexSetter, the node // is placed on the right place in the DOM. if (run) { value = this.zIndex; if (value && parentGroup) { parentGroup.handleZ = true; } childNodes = parentNode.childNodes; for (i = 0; i < childNodes.length && !inserted; i++) { otherElement = childNodes[i]; otherZIndex = otherElement.zIndex; if (otherElement !== element && ( // Insert before the first element with a higher zIndex pInt(otherZIndex) > value || // If no zIndex given, insert before the first element with a zIndex (!defined(value) && defined(otherZIndex)) || // Negative zIndex versus no zIndex: // On all levels except the highest. If the parent is <svg>, // then we don't want to put items before <desc> or <defs> (value < 0 && !defined(otherZIndex) && parentNode !== renderer.box) )) { parentNode.insertBefore(element, otherElement); inserted = true; } } if (!inserted) { parentNode.appendChild(element); } } return inserted; }, _defaultSetter: function(value, key, element) { element.setAttribute(key, value); } }; // Some shared setters and getters SVGElement.prototype.yGetter = SVGElement.prototype.xGetter; SVGElement.prototype.translateXSetter = SVGElement.prototype.translateYSetter = SVGElement.prototype.rotationSetter = SVGElement.prototype.verticalAlignSetter = SVGElement.prototype.scaleXSetter = SVGElement.prototype.scaleYSetter = function(value, key) { this[key] = value; this.doTransform = true; }; /** * The default SVG renderer */ SVGRenderer = H.SVGRenderer = function() { this.init.apply(this, arguments); }; SVGRenderer.prototype = { Element: SVGElement, SVG_NS: SVG_NS, /** * Initialize the SVGRenderer * @param {Object} container * @param {Number} width * @param {Number} height * @param {Boolean} forExport */ init: function(container, width, height, style, forExport, allowHTML) { var renderer = this, boxWrapper, element, desc; boxWrapper = renderer.createElement('svg') .attr({ 'version': '1.1', 'class': 'highcharts-root' }); element = boxWrapper.element; container.appendChild(element); // For browsers other than IE, add the namespace attribute (#1978) if (container.innerHTML.indexOf('xmlns') === -1) { attr(element, 'xmlns', this.SVG_NS); } // object properties renderer.isSVG = true; renderer.box = element; renderer.boxWrapper = boxWrapper; renderer.alignedObjects = []; // Page url used for internal references. #24, #672, #1070 renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ? win.location.href .replace(/#.*?$/, '') // remove the hash .replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes .replace(/ /g, '%20') : // replace spaces (needed for Safari only) ''; // Add description desc = this.createElement('desc').add(); desc.element.appendChild(doc.createTextNode('Created with Highmaps 5.0.1')); renderer.defs = this.createElement('defs').add(); renderer.allowHTML = allowHTML; renderer.forExport = forExport; renderer.gradients = {}; // Object where gradient SvgElements are stored renderer.cache = {}; // Cache for numerical bounding boxes renderer.cacheKeys = []; renderer.imgCount = 0; renderer.setSize(width, height, false); // Issue 110 workaround: // In Firefox, if a div is positioned by percentage, its pixel position may land // between pixels. The container itself doesn't display this, but an SVG element // inside this container will be drawn at subpixel precision. In order to draw // sharp lines, this must be compensated for. This doesn't seem to work inside // iframes though (like in jsFiddle). var subPixelFix, rect; if (isFirefox && container.getBoundingClientRect) { renderer.subPixelFix = subPixelFix = function() { css(container, { left: 0, top: 0 }); rect = container.getBoundingClientRect(); css(container, { left: (Math.ceil(rect.left) - rect.left) + 'px', top: (Math.ceil(rect.top) - rect.top) + 'px' }); }; // run the fix now subPixelFix(); // run it on resize addEvent(win, 'resize', subPixelFix); } }, /** * General method for adding a definition. Can be used for gradients, fills, filters etc. * * @return SVGElement The inserted node */ definition: function(def) { var ren = this; function recurse(config, parent) { var ret; each(splat(config), function(item) { var node = ren.createElement(item.tagName), key, attr = {}; // Set attributes for (key in item) { if (key !== 'tagName' && key !== 'children' && key !== 'textContent') { attr[key] = item[key]; } } node.attr(attr); // Add to the tree node.add(parent || ren.defs); // Add text content if (item.textContent) { node.element.appendChild(doc.createTextNode(item.textContent)); } // Recurse recurse(item.children || [], node); ret = node; }); // Return last node added (on top level it's the only one) return ret; } return recurse(def); }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none. #608. */ isHidden: function() { return !this.boxWrapper.getBBox().width; }, /** * Destroys the renderer and its allocated members. */ destroy: function() { var renderer = this, rendererDefs = renderer.defs; renderer.box = null; renderer.boxWrapper = renderer.boxWrapper.destroy(); // Call destroy on all gradient elements destroyObjectProperties(renderer.gradients || {}); renderer.gradients = null; // Defs are null in VMLRenderer // Otherwise, destroy them here. if (rendererDefs) { renderer.defs = rendererDefs.destroy(); } // Remove sub pixel fix handler // We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed // See issue #982 if (renderer.subPixelFix) { removeEvent(win, 'resize', renderer.subPixelFix); } renderer.alignedObjects = null; return null; }, /** * Create a wrapper for an SVG element * @param {Object} nodeName */ createElement: function(nodeName) { var wrapper = new this.Element(); wrapper.init(this, nodeName); return wrapper; }, /** * Dummy function for plugins */ draw: noop, /** * Get converted radial gradient attributes */ getRadialAttr: function(radialReference, gradAttr) { return { cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2], cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2], r: gradAttr.r * radialReference[2] }; }, /** * Parse a simple HTML string into SVG tspans * * @param {Object} textNode The parent text SVG node */ buildText: function(wrapper) { var textNode = wrapper.element, renderer = this, forExport = renderer.forExport, textStr = pick(wrapper.textStr, '').toString(), hasMarkup = textStr.indexOf('<') !== -1, lines, childNodes = textNode.childNodes, clsRegex, styleRegex, hrefRegex, wasTooLong, parentX = attr(textNode, 'x'), textStyles = wrapper.styles, width = wrapper.textWidth, textLineHeight = textStyles && textStyles.lineHeight, textShadow = textStyles && textStyles.textShadow, ellipsis = textStyles && textStyles.textOverflow === 'ellipsis', i = childNodes.length, tempParent = width && !wrapper.added && this.box, getLineHeight = function(tspan) { var fontSizeStyle; return textLineHeight ? pInt(textLineHeight) : renderer.fontMetrics( fontSizeStyle, tspan ).h; }, unescapeAngleBrackets = function(inputStr) { return inputStr.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); }; /// remove old text while (i--) { textNode.removeChild(childNodes[i]); } // Skip tspans, add text directly to text node. The forceTSpan is a hook // used in text outline hack. if (!hasMarkup && !textShadow && !ellipsis && !width && textStr.indexOf(' ') === -1) { textNode.appendChild(doc.createTextNode(unescapeAngleBrackets(textStr))); // Complex strings, add more logic } else { clsRegex = /<.*class="([^"]+)".*>/; styleRegex = /<.*style="([^"]+)".*>/; hrefRegex = /<.*href="(http[^"]+)".*>/; if (tempParent) { tempParent.appendChild(textNode); // attach it to the DOM to read offset width } if (hasMarkup) { lines = textStr .replace(/<(b|strong)>/g, '<span style="font-weight:bold">') .replace(/<(i|em)>/g, '<span style="font-style:italic">') .replace(/<a/g, '<span') .replace(/<\/(b|strong|i|em|a)>/g, '</span>') .split(/<br.*?>/g); } else { lines = [textStr]; } // Trim empty lines (#5261) lines = grep(lines, function(line) { return line !== ''; }); // build the lines each(lines, function buildTextLines(line, lineNo) { var spans, spanNo = 0; line = line .replace(/^\s+|\s+$/g, '') // Trim to prevent useless/costly process on the spaces (#5258) .replace(/<span/g, '|||<span') .replace(/<\/span>/g, '</span>|||'); spans = line.split('|||'); each(spans, function buildTextSpans(span) { if (span !== '' || spans.length === 1) { var attributes = {}, tspan = doc.createElementNS(renderer.SVG_NS, 'tspan'), spanCls, spanStyle; // #390 if (clsRegex.test(span)) { spanCls = span.match(clsRegex)[1]; attr(tspan, 'class', spanCls); } if (styleRegex.test(span)) { spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2'); attr(tspan, 'style', spanStyle); } if (hrefRegex.test(span) && !forExport) { // Not for export - #1529 attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"'); css(tspan, { cursor: 'pointer' }); } span = unescapeAngleBrackets(span.replace(/<(.|\n)*?>/g, '') || ' '); // Nested tags aren't supported, and cause crash in Safari (#1596) if (span !== ' ') { // add the text node tspan.appendChild(doc.createTextNode(span)); if (!spanNo) { // first span in a line, align it to the left if (lineNo && parentX !== null) { attributes.x = parentX; } } else { attributes.dx = 0; // #16 } // add attributes attr(tspan, attributes); // Append it textNode.appendChild(tspan); // first span on subsequent line, add the line height if (!spanNo && lineNo) { // allow getting the right offset height in exporting in IE if (!svg && forExport) { css(tspan, { display: 'block' }); } // Set the line height based on the font size of either // the text element or the tspan element attr( tspan, 'dy', getLineHeight(tspan) ); } /*if (width) { renderer.breakText(wrapper, width); }*/ // Check width and apply soft breaks or ellipsis if (width) { var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273 noWrap = textStyles.whiteSpace === 'nowrap', hasWhiteSpace = spans.length > 1 || lineNo || (words.length > 1 && !noWrap), tooLong, actualWidth, rest = [], dy = getLineHeight(tspan), rotation = wrapper.rotation, wordStr = span, // for ellipsis cursor = wordStr.length, // binary search cursor bBox; while ((hasWhiteSpace || ellipsis) && (words.length || rest.length)) { wrapper.rotation = 0; // discard rotation when computing box bBox = wrapper.getBBox(true); actualWidth = bBox.width; // Old IE cannot measure the actualWidth for SVG elements (#2314) if (!svg && renderer.forExport) { actualWidth = renderer.measureSpanWidth(tspan.firstChild.data, wrapper.styles); } tooLong = actualWidth > width; // For ellipsis, do a binary search for the correct string length if (wasTooLong === undefined) { wasTooLong = tooLong; // First time } if (ellipsis && wasTooLong) { cursor /= 2; if (wordStr === '' || (!tooLong && cursor < 0.5)) { words = []; // All ok, break out } else { wordStr = span.substring(0, wordStr.length + (tooLong ? -1 : 1) * Math.ceil(cursor)); words = [wordStr + (width > 3 ? '\u2026' : '')]; tspan.removeChild(tspan.firstChild); } // Looping down, this is the first word sequence that is not too long, // so we can move on to build the next line. } else if (!tooLong || words.length === 1) { words = rest; rest = []; if (words.length && !noWrap) { tspan = doc.createElementNS(SVG_NS, 'tspan'); attr(tspan, { dy: dy, x: parentX }); if (spanStyle) { // #390 attr(tspan, 'style', spanStyle); } textNode.appendChild(tspan); } if (actualWidth > width) { // a single word is pressing it out width = actualWidth; } } else { // append to existing line tspan tspan.removeChild(tspan.firstChild); rest.unshift(words.pop()); } if (words.length) { tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-'))); } } wrapper.rotation = rotation; } spanNo++; } } }); }); if (wasTooLong) { wrapper.attr('title', wrapper.textStr); } if (tempParent) { tempParent.removeChild(textNode); // attach it to the DOM to read offset width } // Apply the text shadow if (textShadow && wrapper.applyTextShadow) { wrapper.applyTextShadow(textShadow); } } }, /* breakText: function (wrapper, width) { var bBox = wrapper.getBBox(), node = wrapper.element, textLength = node.textContent.length, pos = Math.round(width * textLength / bBox.width), // try this position first, based on average character width increment = 0, finalPos; if (bBox.width > width) { while (finalPos === undefined) { textLength = node.getSubStringLength(0, pos); if (textLength <= width) { if (increment === -1) { finalPos = pos; } else { increment = 1; } } else { if (increment === 1) { finalPos = pos - 1; } else { increment = -1; } } pos += increment; } } console.log('width', width, 'stringWidth', node.getSubStringLength(0, finalPos)) }, */ /** * Returns white for dark colors and black for bright colors */ getContrast: function(rgba) { rgba = color(rgba).rgba; return rgba[0] + rgba[1] + rgba[2] > 2 * 255 ? '#000000' : '#FFFFFF'; }, /** * Create a button with preset states * @param {String} text * @param {Number} x * @param {Number} y * @param {Function} callback * @param {Object} normalState * @param {Object} hoverState * @param {Object} pressedState */ button: function(text, x, y, callback, normalState, hoverState, pressedState, disabledState, shape) { var label = this.label(text, x, y, shape, null, null, null, null, 'button'), curState = 0; // Default, non-stylable attributes label.attr(merge({ 'padding': 8, 'r': 2 }, normalState)); // Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667). addEvent(label.element, isMS ? 'mouseover' : 'mouseenter', function() { if (curState !== 3) { label.setState(1); } }); addEvent(label.element, isMS ? 'mouseout' : 'mouseleave', function() { if (curState !== 3) { label.setState(curState); } }); label.setState = function(state) { // Hover state is temporary, don't record it if (state !== 1) { label.state = curState = state; } // Update visuals label.removeClass(/highcharts-button-(normal|hover|pressed|disabled)/) .addClass('highcharts-button-' + ['normal', 'hover', 'pressed', 'disabled'][state || 0]); }; return label .on('click', function(e) { if (curState !== 3) { callback.call(label, e); } }); }, /** * Make a straight line crisper by not spilling out to neighbour pixels * @param {Array} points * @param {Number} width */ crispLine: function(points, width) { // points format: ['M', 0, 0, 'L', 100, 0] // normalize to a crisp line if (points[1] === points[4]) { // Substract due to #1129. Now bottom and left axis gridlines behave the same. points[1] = points[4] = Math.round(points[1]) - (width % 2 / 2); } if (points[2] === points[5]) { points[2] = points[5] = Math.round(points[2]) + (width % 2 / 2); } return points; }, /** * Draw a path * @param {Array} path An SVG path in array form */ path: function(path) { var attribs = { }; if (isArray(path)) { attribs.d = path; } else if (isObject(path)) { // attributes extend(attribs, path); } return this.createElement('path').attr(attribs); }, /** * Draw and return an SVG circle * @param {Number} x The x position * @param {Number} y The y position * @param {Number} r The radius */ circle: function(x, y, r) { var attribs = isObject(x) ? x : { x: x, y: y, r: r }, wrapper = this.createElement('circle'); // Setting x or y translates to cx and cy wrapper.xSetter = wrapper.ySetter = function(value, key, element) { element.setAttribute('c' + key, value); }; return wrapper.attr(attribs); }, /** * Draw and return an arc * @param {Number} x X position * @param {Number} y Y position * @param {Number} r Radius * @param {Number} innerR Inner radius like used in donut charts * @param {Number} start Starting angle * @param {Number} end Ending angle */ arc: function(x, y, r, innerR, start, end) { var arc; if (isObject(x)) { y = x.y; r = x.r; innerR = x.innerR; start = x.start; end = x.end; x = x.x; } // Arcs are defined as symbols for the ability to set // attributes in attr and animate arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, { innerR: innerR || 0, start: start || 0, end: end || 0 }); arc.r = r; // #959 return arc; }, /** * Draw and return a rectangle * @param {Number} x Left position * @param {Number} y Top position * @param {Number} width * @param {Number} height * @param {Number} r Border corner radius * @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing */ rect: function(x, y, width, height, r, strokeWidth) { r = isObject(x) ? x.r : r; var wrapper = this.createElement('rect'), attribs = isObject(x) ? x : x === undefined ? {} : { x: x, y: y, width: Math.max(width, 0), height: Math.max(height, 0) }; if (r) { attribs.r = r; } wrapper.rSetter = function(value, key, element) { attr(element, { rx: value, ry: value }); }; return wrapper.attr(attribs); }, /** * Resize the box and re-align all aligned elements * @param {Object} width * @param {Object} height * @param {Boolean} animate * */ setSize: function(width, height, animate) { var renderer = this, alignedObjects = renderer.alignedObjects, i = alignedObjects.length; renderer.width = width; renderer.height = height; renderer.boxWrapper.animate({ width: width, height: height }, { step: function() { this.attr({ viewBox: '0 0 ' + this.attr('width') + ' ' + this.attr('height') }); }, duration: pick(animate, true) ? undefined : 0 }); while (i--) { alignedObjects[i].align(); } }, /** * Create a group * @param {String} name The group will be given a class name of 'highcharts-{name}'. * This can be used for styling and scripting. */ g: function(name) { var elem = this.createElement('g'); return name ? elem.attr({ 'class': 'highcharts-' + name }) : elem; }, /** * Display an image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function(src, x, y, width, height) { var attribs = { preserveAspectRatio: 'none' }, elemWrapper; // optional properties if (arguments.length > 1) { extend(attribs, { x: x, y: y, width: width, height: height }); } elemWrapper = this.createElement('image').attr(attribs); // set the href in the xlink namespace if (elemWrapper.element.setAttributeNS) { elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink', 'href', src); } else { // could be exporting in IE // using href throws "not supported" in ie7 and under, requries regex shim to fix later elemWrapper.element.setAttribute('hc-svg-href', src); } return elemWrapper; }, /** * Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object. * * @param {Object} symbol * @param {Object} x * @param {Object} y * @param {Object} radius * @param {Object} options */ symbol: function(symbol, x, y, width, height, options) { var ren = this, obj, // get the symbol definition function symbolFn = this.symbols[symbol], // check if there's a path defined for this symbol path = defined(x) && symbolFn && symbolFn( Math.round(x), Math.round(y), width, height, options ), imageRegex = /^url\((.*?)\)$/, imageSrc, centerImage; if (symbolFn) { obj = this.path(path); // expando properties for use in animate and attr extend(obj, { symbolName: symbol, x: x, y: y, width: width, height: height }); if (options) { extend(obj, options); } // image symbols } else if (imageRegex.test(symbol)) { imageSrc = symbol.match(imageRegex)[1]; // Create the image synchronously, add attribs async obj = this.image(imageSrc); // The image width is not always the same as the symbol width. The // image may be centered within the symbol, as is the case when // image shapes are used as label backgrounds, for example in flags. obj.imgwidth = pick( symbolSizes[imageSrc] && symbolSizes[imageSrc].width, options && options.width ); obj.imgheight = pick( symbolSizes[imageSrc] && symbolSizes[imageSrc].height, options && options.height ); /** * Set the size and position */ centerImage = function() { obj.attr({ width: obj.width, height: obj.height }); }; /** * Width and height setters that take both the image's physical size * and the label size into consideration, and translates the image * to center within the label. */ each(['width', 'height'], function(key) { obj[key + 'Setter'] = function(value, key) { var attribs = {}, imgSize = this['img' + key], trans = key === 'width' ? 'translateX' : 'translateY'; this[key] = value; if (defined(imgSize)) { if (this.element) { this.element.setAttribute(key, imgSize); } if (!this.alignByTranslate) { attribs[trans] = ((this[key] || 0) - imgSize) / 2; this.attr(attribs); } } }; }); if (defined(x)) { obj.attr({ x: x, y: y }); } obj.isImg = true; if (defined(obj.imgwidth) && defined(obj.imgheight)) { centerImage(); } else { // Initialize image to be 0 size so export will still function if there's no cached sizes. obj.attr({ width: 0, height: 0 }); // Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8, // the created element must be assigned to a variable in order to load (#292). createElement('img', { onload: function() { var chart = charts[ren.chartIndex]; // Special case for SVGs on IE11, the width is not accessible until the image is // part of the DOM (#2854). if (this.width === 0) { css(this, { position: 'absolute', top: '-999em' }); doc.body.appendChild(this); } // Center the image symbolSizes[imageSrc] = { // Cache for next width: this.width, height: this.height }; obj.imgwidth = this.width; obj.imgheight = this.height; if (obj.element) { centerImage(); } // Clean up after #2854 workaround. if (this.parentNode) { this.parentNode.removeChild(this); } // Fire the load event when all external images are loaded ren.imgCount--; if (!ren.imgCount && chart && chart.onload) { chart.onload(); } }, src: imageSrc }); this.imgCount++; } } return obj; }, /** * An extendable collection of functions for defining symbol paths. */ symbols: { 'circle': function(x, y, w, h) { var cpw = 0.166 * w; return [ 'M', x + w / 2, y, 'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h, 'C', x - cpw, y + h, x - cpw, y, x + w / 2, y, 'Z' ]; }, 'square': function(x, y, w, h) { return [ 'M', x, y, 'L', x + w, y, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle': function(x, y, w, h) { return [ 'M', x + w / 2, y, 'L', x + w, y + h, x, y + h, 'Z' ]; }, 'triangle-down': function(x, y, w, h) { return [ 'M', x, y, 'L', x + w, y, x + w / 2, y + h, 'Z' ]; }, 'diamond': function(x, y, w, h) { return [ 'M', x + w / 2, y, 'L', x + w, y + h / 2, x + w / 2, y + h, x, y + h / 2, 'Z' ]; }, 'arc': function(x, y, w, h, options) { var start = options.start, radius = options.r || w || h, end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561) innerRadius = options.innerR, open = options.open, cosStart = Math.cos(start), sinStart = Math.sin(start), cosEnd = Math.cos(end), sinEnd = Math.sin(end), longArc = options.end - start < Math.PI ? 0 : 1; return [ 'M', x + radius * cosStart, y + radius * sinStart, 'A', // arcTo radius, // x radius radius, // y radius 0, // slanting longArc, // long or short arc 1, // clockwise x + radius * cosEnd, y + radius * sinEnd, open ? 'M' : 'L', x + innerRadius * cosEnd, y + innerRadius * sinEnd, 'A', // arcTo innerRadius, // x radius innerRadius, // y radius 0, // slanting longArc, // long or short arc 0, // clockwise x + innerRadius * cosStart, y + innerRadius * sinStart, open ? '' : 'Z' // close ]; }, /** * Callout shape used for default tooltips, also used for rounded rectangles in VML */ callout: function(x, y, w, h, options) { var arrowLength = 6, halfDistance = 6, r = Math.min((options && options.r) || 0, w, h), safeDistance = r + halfDistance, anchorX = options && options.anchorX, anchorY = options && options.anchorY, path; path = [ 'M', x + r, y, 'L', x + w - r, y, // top side 'C', x + w, y, x + w, y, x + w, y + r, // top-right corner 'L', x + w, y + h - r, // right side 'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-right corner 'L', x + r, y + h, // bottom side 'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner 'L', x, y + r, // left side 'C', x, y, x, y, x + r, y // top-right corner ]; if (anchorX && anchorX > w && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace right side path.splice(13, 3, 'L', x + w, anchorY - halfDistance, x + w + arrowLength, anchorY, x + w, anchorY + halfDistance, x + w, y + h - r ); } else if (anchorX && anchorX < 0 && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace left side path.splice(33, 3, 'L', x, anchorY + halfDistance, x - arrowLength, anchorY, x, anchorY - halfDistance, x, y + r ); } else if (anchorY && anchorY > h && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace bottom path.splice(23, 3, 'L', anchorX + halfDistance, y + h, anchorX, y + h + arrowLength, anchorX - halfDistance, y + h, x + r, y + h ); } else if (anchorY && anchorY < 0 && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace top path.splice(3, 3, 'L', anchorX - halfDistance, y, anchorX, y - arrowLength, anchorX + halfDistance, y, w - r, y ); } return path; } }, /** * Define a clipping rectangle * @param {String} id * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function(x, y, width, height) { var wrapper, id = 'highcharts-' + H.idCounter++, clipPath = this.createElement('clipPath').attr({ id: id }).add(this.defs); wrapper = this.rect(x, y, width, height, 0).add(clipPath); wrapper.id = id; wrapper.clipPath = clipPath; wrapper.count = 0; return wrapper; }, /** * Add text to the SVG object * @param {String} str * @param {Number} x Left position * @param {Number} y Top position * @param {Boolean} useHTML Use HTML to render the text */ text: function(str, x, y, useHTML) { // declare variables var renderer = this, fakeSVG = !svg && renderer.forExport, wrapper, attribs = {}; if (useHTML && (renderer.allowHTML || !renderer.forExport)) { return renderer.html(str, x, y); } attribs.x = Math.round(x || 0); // X is always needed for line-wrap logic if (y) { attribs.y = Math.round(y); } if (str || str === 0) { attribs.text = str; } wrapper = renderer.createElement('text') .attr(attribs); // Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063) if (fakeSVG) { wrapper.css({ position: 'absolute' }); } if (!useHTML) { wrapper.xSetter = function(value, key, element) { var tspans = element.getElementsByTagName('tspan'), tspan, parentVal = element.getAttribute(key), i; for (i = 0; i < tspans.length; i++) { tspan = tspans[i]; // If the x values are equal, the tspan represents a linebreak if (tspan.getAttribute(key) === parentVal) { tspan.setAttribute(key, value); } } element.setAttribute(key, value); }; } return wrapper; }, /** * Utility to return the baseline offset and total line height from the font size */ fontMetrics: function(fontSize, elem) { // eslint-disable-line no-unused-vars var lineHeight, baseline; fontSize = elem && SVGElement.prototype.getStyle.call(elem, 'font-size'); fontSize = /px/.test(fontSize) ? pInt(fontSize) : /em/.test(fontSize) ? parseFloat(fontSize) * 12 : 12; // Empirical values found by comparing font size and bounding box height. // Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/ lineHeight = fontSize < 24 ? fontSize + 3 : Math.round(fontSize * 1.2); baseline = Math.round(lineHeight * 0.8); return { h: lineHeight, b: baseline, f: fontSize }; }, /** * Correct X and Y positioning of a label for rotation (#1764) */ rotCorr: function(baseline, rotation, alterY) { var y = baseline; if (rotation && alterY) { y = Math.max(y * Math.cos(rotation * deg2rad), 4); } return { x: (-baseline / 3) * Math.sin(rotation * deg2rad), y: y }; }, /** * Add a label, a text item that can hold a colored or gradient background * as well as a border and shadow. * @param {string} str * @param {Number} x * @param {Number} y * @param {String} shape * @param {Number} anchorX In case the shape has a pointer, like a flag, this is the * coordinates it should be pinned to * @param {Number} anchorY * @param {Boolean} baseline Whether to position the label relative to the text baseline, * like renderer.text, or to the upper border of the rectangle. * @param {String} className Class name for the group */ label: function(str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) { var renderer = this, wrapper = renderer.g(className !== 'button' && 'label'), text = wrapper.text = renderer.text('', 0, 0, useHTML) .attr({ zIndex: 1 }), box, bBox, alignFactor = 0, padding = 3, paddingLeft = 0, width, height, wrapperX, wrapperY, textAlign, deferredAttr = {}, strokeWidth, baselineOffset, hasBGImage = /^url\((.*?)\)$/.test(shape), needsBox = hasBGImage, getCrispAdjust, updateBoxSize, updateTextPadding, boxAttr; if (className) { wrapper.addClass('highcharts-' + className); } needsBox = true; // for styling getCrispAdjust = function() { return box.strokeWidth() % 2 / 2; }; /** * This function runs after the label is added to the DOM (when the bounding box is * available), and after the text of the label is updated to detect the new bounding * box and reflect it in the border box. */ updateBoxSize = function() { var style = text.element.style, crispAdjust, attribs = {}; bBox = (width === undefined || height === undefined || textAlign) && defined(text.textStr) && text.getBBox(); //#3295 && 3514 box failure when string equals 0 wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft; wrapper.height = (height || bBox.height || 0) + 2 * padding; // Update the label-scoped y offset baselineOffset = padding + renderer.fontMetrics(style && style.fontSize, text).b; if (needsBox) { // Create the border box if it is not already present if (!box) { wrapper.box = box = renderer.symbols[shape] || hasBGImage ? // Symbol definition exists (#5324) renderer.symbol(shape) : renderer.rect(); box.addClass( (className === 'button' ? '' : 'highcharts-label-box') + // Don't use label className for buttons (className ? ' highcharts-' + className + '-box' : '') ); box.add(wrapper); crispAdjust = getCrispAdjust(); attribs.x = crispAdjust; attribs.y = (baseline ? -baselineOffset : 0) + crispAdjust; } // Apply the box attributes attribs.width = Math.round(wrapper.width); attribs.height = Math.round(wrapper.height); box.attr(extend(attribs, deferredAttr)); deferredAttr = {}; } }; /** * This function runs after setting text or padding, but only if padding is changed */ updateTextPadding = function() { var textX = paddingLeft + padding, textY; // determin y based on the baseline textY = baseline ? 0 : baselineOffset; // compensate for alignment if (defined(width) && bBox && (textAlign === 'center' || textAlign === 'right')) { textX += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width); } // update if anything changed if (textX !== text.x || textY !== text.y) { text.attr('x', textX); if (textY !== undefined) { text.attr('y', textY); } } // record current values text.x = textX; text.y = textY; }; /** * Set a box attribute, or defer it if the box is not yet created * @param {Object} key * @param {Object} value */ boxAttr = function(key, value) { if (box) { box.attr(key, value); } else { deferredAttr[key] = value; } }; /** * After the text element is added, get the desired size of the border box * and add it before the text in the DOM. */ wrapper.onAdd = function() { text.add(wrapper); wrapper.attr({ text: (str || str === 0) ? str : '', // alignment is available now // #3295: 0 not rendered if given as a value x: x, y: y }); if (box && defined(anchorX)) { wrapper.attr({ anchorX: anchorX, anchorY: anchorY }); } }; /* * Add specific attribute setters. */ // only change local variables wrapper.widthSetter = function(value) { width = value; }; wrapper.heightSetter = function(value) { height = value; }; wrapper['text-alignSetter'] = function(value) { textAlign = value; }; wrapper.paddingSetter = function(value) { if (defined(value) && value !== padding) { padding = wrapper.padding = value; updateTextPadding(); } }; wrapper.paddingLeftSetter = function(value) { if (defined(value) && value !== paddingLeft) { paddingLeft = value; updateTextPadding(); } }; // change local variable and prevent setting attribute on the group wrapper.alignSetter = function(value) { value = { left: 0, center: 0.5, right: 1 }[value]; if (value !== alignFactor) { alignFactor = value; if (bBox) { // Bounding box exists, means we're dynamically changing wrapper.attr({ x: wrapperX }); // #5134 } } }; // apply these to the box and the text alike wrapper.textSetter = function(value) { if (value !== undefined) { text.textSetter(value); } updateBoxSize(); updateTextPadding(); }; // apply these to the box but not to the text wrapper['stroke-widthSetter'] = function(value, key) { if (value) { needsBox = true; } strokeWidth = this['stroke-width'] = value; boxAttr(key, value); }; wrapper.rSetter = function(value, key) { boxAttr(key, value); }; wrapper.anchorXSetter = function(value, key) { anchorX = value; boxAttr(key, Math.round(value) - getCrispAdjust() - wrapperX); }; wrapper.anchorYSetter = function(value, key) { anchorY = value; boxAttr(key, value - wrapperY); }; // rename attributes wrapper.xSetter = function(value) { wrapper.x = value; // for animation getter if (alignFactor) { value -= alignFactor * ((width || bBox.width) + 2 * padding); } wrapperX = Math.round(value); wrapper.attr('translateX', wrapperX); }; wrapper.ySetter = function(value) { wrapperY = wrapper.y = Math.round(value); wrapper.attr('translateY', wrapperY); }; // Redirect certain methods to either the box or the text var baseCss = wrapper.css; return extend(wrapper, { /** * Pick up some properties and apply them to the text instead of the wrapper */ css: function(styles) { if (styles) { var textStyles = {}; styles = merge(styles); // create a copy to avoid altering the original object (#537) each(wrapper.textProps, function(prop) { if (styles[prop] !== undefined) { textStyles[prop] = styles[prop]; delete styles[prop]; } }); text.css(textStyles); } return baseCss.call(wrapper, styles); }, /** * Return the bounding box of the box, not the group */ getBBox: function() { return { width: bBox.width + 2 * padding, height: bBox.height + 2 * padding, x: bBox.x - padding, y: bBox.y - padding }; }, /** * Destroy and release memory. */ destroy: function() { // Added by button implementation removeEvent(wrapper.element, 'mouseenter'); removeEvent(wrapper.element, 'mouseleave'); if (text) { text = text.destroy(); } if (box) { box = box.destroy(); } // Call base implementation to destroy the rest SVGElement.prototype.destroy.call(wrapper); // Release local pointers (#1298) wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = null; } }); } }; // end SVGRenderer // general renderer H.Renderer = SVGRenderer; }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var attr = H.attr, createElement = H.createElement, css = H.css, defined = H.defined, each = H.each, extend = H.extend, isFirefox = H.isFirefox, isMS = H.isMS, isWebKit = H.isWebKit, pInt = H.pInt, SVGElement = H.SVGElement, SVGRenderer = H.SVGRenderer, win = H.win, wrap = H.wrap; // extend SvgElement for useHTML option extend(SVGElement.prototype, { /** * Apply CSS to HTML elements. This is used in text within SVG rendering and * by the VML renderer */ htmlCss: function(styles) { var wrapper = this, element = wrapper.element, textWidth = styles && element.tagName === 'SPAN' && styles.width; if (textWidth) { delete styles.width; wrapper.textWidth = textWidth; wrapper.updateTransform(); } if (styles && styles.textOverflow === 'ellipsis') { styles.whiteSpace = 'nowrap'; styles.overflow = 'hidden'; } wrapper.styles = extend(wrapper.styles, styles); css(wrapper.element, styles); return wrapper; }, /** * VML and useHTML method for calculating the bounding box based on offsets * @param {Boolean} refresh Whether to force a fresh value from the DOM or to * use the cached value * * @return {Object} A hash containing values for x, y, width and height */ htmlGetBBox: function() { var wrapper = this, element = wrapper.element; // faking getBBox in exported SVG in legacy IE // faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?) if (element.nodeName === 'text') { element.style.position = 'absolute'; } return { x: element.offsetLeft, y: element.offsetTop, width: element.offsetWidth, height: element.offsetHeight }; }, /** * VML override private method to update elements based on internal * properties based on SVG transform */ htmlUpdateTransform: function() { // aligning non added elements is expensive if (!this.added) { this.alignOnAdd = true; return; } var wrapper = this, renderer = wrapper.renderer, elem = wrapper.element, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, x = wrapper.x || 0, y = wrapper.y || 0, align = wrapper.textAlign || 'left', alignCorrection = { left: 0, center: 0.5, right: 1 }[align], styles = wrapper.styles; // apply translate css(elem, { marginLeft: translateX, marginTop: translateY }); // apply inversion if (wrapper.inverted) { // wrapper is a group each(elem.childNodes, function(child) { renderer.invertChild(child, elem); }); } if (elem.tagName === 'SPAN') { var rotation = wrapper.rotation, baseline, textWidth = pInt(wrapper.textWidth), whiteSpace = styles && styles.whiteSpace, currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth, wrapper.textAlign].join(','); if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed baseline = renderer.fontMetrics(elem.style.fontSize).b; // Renderer specific handling of span rotation if (defined(rotation)) { wrapper.setSpanRotation(rotation, alignCorrection, baseline); } // Reset multiline/ellipsis in order to read width (#4928, #5417) css(elem, { width: '', whiteSpace: whiteSpace || 'nowrap' }); // Update textWidth if (elem.offsetWidth > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254 css(elem, { width: textWidth + 'px', display: 'block', whiteSpace: whiteSpace || 'normal' // #3331 }); } wrapper.getSpanCorrection(elem.offsetWidth, baseline, alignCorrection, rotation, align); } // apply position with correction css(elem, { left: (x + (wrapper.xCorr || 0)) + 'px', top: (y + (wrapper.yCorr || 0)) + 'px' }); // force reflow in webkit to apply the left and top on useHTML element (#1249) if (isWebKit) { baseline = elem.offsetHeight; // assigned to baseline for lint purpose } // record current text transform wrapper.cTT = currentTextTransform; } }, /** * Set the rotation of an individual HTML span */ setSpanRotation: function(rotation, alignCorrection, baseline) { var rotationStyle = {}, cssTransformKey = isMS ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : win.opera ? '-o-transform' : ''; rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)'; rotationStyle[cssTransformKey + (isFirefox ? 'Origin' : '-origin')] = rotationStyle.transformOrigin = (alignCorrection * 100) + '% ' + baseline + 'px'; css(this.element, rotationStyle); }, /** * Get the correction in X and Y positioning as the element is rotated. */ getSpanCorrection: function(width, baseline, alignCorrection) { this.xCorr = -width * alignCorrection; this.yCorr = -baseline; } }); // Extend SvgRenderer for useHTML option. extend(SVGRenderer.prototype, { /** * Create HTML text node. This is used by the VML renderer as well as the SVG * renderer through the useHTML option. * * @param {String} str * @param {Number} x * @param {Number} y */ html: function(str, x, y) { var wrapper = this.createElement('span'), element = wrapper.element, renderer = wrapper.renderer, isSVG = renderer.isSVG, addSetters = function(element, style) { // These properties are set as attributes on the SVG group, and as // identical CSS properties on the div. (#3542) each(['opacity', 'visibility'], function(prop) { wrap(element, prop + 'Setter', function(proceed, value, key, elem) { proceed.call(this, value, key, elem); style[key] = value; }); }); }; // Text setter wrapper.textSetter = function(value) { if (value !== element.innerHTML) { delete this.bBox; } element.innerHTML = this.textStr = value; wrapper.htmlUpdateTransform(); }; // Add setters for the element itself (#4938) if (isSVG) { // #4938, only for HTML within SVG addSetters(wrapper, wrapper.element.style); } // Various setters which rely on update transform wrapper.xSetter = wrapper.ySetter = wrapper.alignSetter = wrapper.rotationSetter = function(value, key) { if (key === 'align') { key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML. } wrapper[key] = value; wrapper.htmlUpdateTransform(); }; // Set the default attributes wrapper .attr({ text: str, x: Math.round(x), y: Math.round(y) }) .css({ position: 'absolute' }); // Keep the whiteSpace style outside the wrapper.styles collection element.style.whiteSpace = 'nowrap'; // Use the HTML specific .css method wrapper.css = wrapper.htmlCss; // This is specific for HTML within SVG if (isSVG) { wrapper.add = function(svgGroupWrapper) { var htmlGroup, container = renderer.box.parentNode, parentGroup, parents = []; this.parentGroup = svgGroupWrapper; // Create a mock group to hold the HTML elements if (svgGroupWrapper) { htmlGroup = svgGroupWrapper.div; if (!htmlGroup) { // Read the parent chain into an array and read from top down parentGroup = svgGroupWrapper; while (parentGroup) { parents.push(parentGroup); // Move up to the next parent group parentGroup = parentGroup.parentGroup; } // Ensure dynamically updating position when any parent is translated each(parents.reverse(), function(parentGroup) { var htmlGroupStyle, cls = attr(parentGroup.element, 'class'); if (cls) { cls = { className: cls }; } // else null // Create a HTML div and append it to the parent div to emulate // the SVG group structure htmlGroup = parentGroup.div = parentGroup.div || createElement('div', cls, { position: 'absolute', left: (parentGroup.translateX || 0) + 'px', top: (parentGroup.translateY || 0) + 'px', display: parentGroup.display, opacity: parentGroup.opacity, // #5075 pointerEvents: parentGroup.styles && parentGroup.styles.pointerEvents // #5595 }, htmlGroup || container); // the top group is appended to container // Shortcut htmlGroupStyle = htmlGroup.style; // Set listeners to update the HTML div's position whenever the SVG group // position is changed extend(parentGroup, { translateXSetter: function(value, key) { htmlGroupStyle.left = value + 'px'; parentGroup[key] = value; parentGroup.doTransform = true; }, translateYSetter: function(value, key) { htmlGroupStyle.top = value + 'px'; parentGroup[key] = value; parentGroup.doTransform = true; } }); addSetters(parentGroup, htmlGroupStyle); }); } } else { htmlGroup = container; } htmlGroup.appendChild(element); // Shared with VML: wrapper.added = true; if (wrapper.alignOnAdd) { wrapper.htmlUpdateTransform(); } return wrapper; }; } return wrapper; } }); }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var correctFloat = H.correctFloat, defined = H.defined, destroyObjectProperties = H.destroyObjectProperties, isNumber = H.isNumber, merge = H.merge, pick = H.pick, stop = H.stop, deg2rad = H.deg2rad; /** * The Tick class */ H.Tick = function(axis, pos, type, noLabel) { this.axis = axis; this.pos = pos; this.type = type || ''; this.isNew = true; if (!type && !noLabel) { this.addLabel(); } }; H.Tick.prototype = { /** * Write the tick label */ addLabel: function() { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, categories = axis.categories, names = axis.names, pos = tick.pos, labelOptions = options.labels, str, tickPositions = axis.tickPositions, isFirst = pos === tickPositions[0], isLast = pos === tickPositions[tickPositions.length - 1], value = categories ? pick(categories[pos], names[pos], pos) : pos, label = tick.label, tickPositionInfo = tickPositions.info, dateTimeLabelFormat; // Set the datetime label format. If a higher rank is set for this position, use that. If not, // use the general format. if (axis.isDatetimeAxis && tickPositionInfo) { dateTimeLabelFormat = options.dateTimeLabelFormats[ tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName ]; } // set properties for access in render method tick.isFirst = isFirst; tick.isLast = isLast; // get the string str = axis.labelFormatter.call({ axis: axis, chart: chart, isFirst: isFirst, isLast: isLast, dateTimeLabelFormat: dateTimeLabelFormat, value: axis.isLog ? correctFloat(axis.lin2log(value)) : value }); // prepare CSS //css = width && { width: Math.max(1, Math.round(width - 2 * (labelOptions.padding || 10))) + 'px' }; // first call if (!defined(label)) { tick.label = label = defined(str) && labelOptions.enabled ? chart.renderer.text( str, 0, 0, labelOptions.useHTML ) .add(axis.labelGroup): null; tick.labelLength = label && label.getBBox().width; // Un-rotated length tick.rotation = 0; // Base value to detect change for new calls to getBBox // update } else if (label) { label.attr({ text: str }); } }, /** * Get the offset height or width of the label */ getLabelSize: function() { return this.label ? this.label.getBBox()[this.axis.horiz ? 'height' : 'width'] : 0; }, /** * Handle the label overflow by adjusting the labels to the left and right edge, or * hide them if they collide into the neighbour label. */ handleOverflow: function(xy) { var axis = this.axis, pxPos = xy.x, chartWidth = axis.chart.chartWidth, spacing = axis.chart.spacing, leftBound = pick(axis.labelLeft, Math.min(axis.pos, spacing[3])), rightBound = pick(axis.labelRight, Math.max(axis.pos + axis.len, chartWidth - spacing[1])), label = this.label, rotation = this.rotation, factor = { left: 0, center: 0.5, right: 1 }[axis.labelAlign], labelWidth = label.getBBox().width, slotWidth = axis.getSlotWidth(), modifiedSlotWidth = slotWidth, xCorrection = factor, goRight = 1, leftPos, rightPos, textWidth, css = {}; // Check if the label overshoots the chart spacing box. If it does, move it. // If it now overshoots the slotWidth, add ellipsis. if (!rotation) { leftPos = pxPos - factor * labelWidth; rightPos = pxPos + (1 - factor) * labelWidth; if (leftPos < leftBound) { modifiedSlotWidth = xy.x + modifiedSlotWidth * (1 - factor) - leftBound; } else if (rightPos > rightBound) { modifiedSlotWidth = rightBound - xy.x + modifiedSlotWidth * factor; goRight = -1; } modifiedSlotWidth = Math.min(slotWidth, modifiedSlotWidth); // #4177 if (modifiedSlotWidth < slotWidth && axis.labelAlign === 'center') { xy.x += goRight * (slotWidth - modifiedSlotWidth - xCorrection * (slotWidth - Math.min(labelWidth, modifiedSlotWidth))); } // If the label width exceeds the available space, set a text width to be // picked up below. Also, if a width has been set before, we need to set a new // one because the reported labelWidth will be limited by the box (#3938). if (labelWidth > modifiedSlotWidth || (axis.autoRotation && (label.styles || {}).width)) { textWidth = modifiedSlotWidth; } // Add ellipsis to prevent rotated labels to be clipped against the edge of the chart } else if (rotation < 0 && pxPos - factor * labelWidth < leftBound) { textWidth = Math.round(pxPos / Math.cos(rotation * deg2rad) - leftBound); } else if (rotation > 0 && pxPos + factor * labelWidth > rightBound) { textWidth = Math.round((chartWidth - pxPos) / Math.cos(rotation * deg2rad)); } if (textWidth) { css.width = textWidth; if (!(axis.options.labels.style || {}).textOverflow) { css.textOverflow = 'ellipsis'; } label.css(css); } }, /** * Get the x and y position for ticks and labels */ getPosition: function(horiz, pos, tickmarkOffset, old) { var axis = this.axis, chart = axis.chart, cHeight = (old && chart.oldChartHeight) || chart.chartHeight; return { x: horiz ? axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB : axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0 ), y: horiz ? cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) : cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB }; }, /** * Get the x, y position of the tick label */ getLabelPosition: function(x, y, label, horiz, labelOptions, tickmarkOffset, index, step) { var axis = this.axis, transA = axis.transA, reversed = axis.reversed, staggerLines = axis.staggerLines, rotCorr = axis.tickRotCorr || { x: 0, y: 0 }, yOffset = labelOptions.y, line; if (!defined(yOffset)) { if (axis.side === 0) { yOffset = label.rotation ? -8 : -label.getBBox().height; } else if (axis.side === 2) { yOffset = rotCorr.y + 8; } else { // #3140, #3140 yOffset = Math.cos(label.rotation * deg2rad) * (rotCorr.y - label.getBBox(false, 0).height / 2); } } x = x + labelOptions.x + rotCorr.x - (tickmarkOffset && horiz ? tickmarkOffset * transA * (reversed ? -1 : 1) : 0); y = y + yOffset - (tickmarkOffset && !horiz ? tickmarkOffset * transA * (reversed ? 1 : -1) : 0); // Correct for staggered labels if (staggerLines) { line = (index / (step || 1) % staggerLines); if (axis.opposite) { line = staggerLines - line - 1; } y += line * (axis.labelOffset / staggerLines); } return { x: x, y: Math.round(y) }; }, /** * Extendible method to return the path of the marker */ getMarkPath: function(x, y, tickLength, tickWidth, horiz, renderer) { return renderer.crispLine([ 'M', x, y, 'L', x + (horiz ? 0 : -tickLength), y + (horiz ? tickLength : 0) ], tickWidth); }, /** * Put everything in place * * @param index {Number} * @param old {Boolean} Use old coordinates to prepare an animation into new position */ render: function(index, old, opacity) { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, renderer = chart.renderer, horiz = axis.horiz, type = tick.type, label = tick.label, pos = tick.pos, labelOptions = options.labels, gridLine = tick.gridLine, tickPrefix = type ? type + 'Tick' : 'tick', tickSize = axis.tickSize(tickPrefix), gridLinePath, mark = tick.mark, isNewMark = !mark, step = labelOptions.step, attribs = {}, show = true, tickmarkOffset = axis.tickmarkOffset, xy = tick.getPosition(horiz, pos, tickmarkOffset, old), x = xy.x, y = xy.y, reverseCrisp = ((horiz && x === axis.pos + axis.len) || (!horiz && y === axis.pos)) ? -1 : 1; // #1480, #1687 opacity = pick(opacity, 1); this.isActive = true; // Create the grid line if (!gridLine) { if (!type) { attribs.zIndex = 1; } if (old) { attribs.opacity = 0; } tick.gridLine = gridLine = renderer.path() .attr(attribs) .addClass('highcharts-' + (type ? type + '-' : '') + 'grid-line') .add(axis.gridGroup); } // If the parameter 'old' is set, the current call will be followed // by another call, therefore do not do any animations this time if (!old && gridLine) { gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLine.strokeWidth() * reverseCrisp, old, true); if (gridLinePath) { gridLine[tick.isNew ? 'attr' : 'animate']({ d: gridLinePath, opacity: opacity }); } } // create the tick mark if (tickSize) { // negate the length if (axis.opposite) { tickSize[0] = -tickSize[0]; } // First time, create it if (isNewMark) { tick.mark = mark = renderer.path() .addClass('highcharts-' + (type ? type + '-' : '') + 'tick') .add(axis.axisGroup); } mark[isNewMark ? 'attr' : 'animate']({ d: tick.getMarkPath(x, y, tickSize[0], mark.strokeWidth() * reverseCrisp, horiz, renderer), opacity: opacity }); } // the label is created on init - now move it into place if (label && isNumber(x)) { label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step); // Apply show first and show last. If the tick is both first and last, it is // a single centered tick, in which case we show the label anyway (#2100). if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) || (tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) { show = false; // Handle label overflow and show or hide accordingly } else if (horiz && !axis.isRadial && !labelOptions.step && !labelOptions.rotation && !old && opacity !== 0) { tick.handleOverflow(xy); } // apply step if (step && index % step) { // show those indices dividable by step show = false; } // Set the new position, and show or hide if (show && isNumber(xy.y)) { xy.opacity = opacity; label[tick.isNew ? 'attr' : 'animate'](xy); } else { stop(label); // #5332 label.attr('y', -9999); // #1338 } tick.isNew = false; } }, /** * Destructor for the tick prototype */ destroy: function() { destroyObjectProperties(this, this.axis); } }; }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var arrayMax = H.arrayMax, arrayMin = H.arrayMin, defined = H.defined, destroyObjectProperties = H.destroyObjectProperties, each = H.each, erase = H.erase, merge = H.merge, pick = H.pick; /* * The object wrapper for plot lines and plot bands * @param {Object} options */ H.PlotLineOrBand = function(axis, options) { this.axis = axis; if (options) { this.options = options; this.id = options.id; } }; H.PlotLineOrBand.prototype = { /** * Render the plot line or plot band. If it is already existing, * move it. */ render: function() { var plotLine = this, axis = plotLine.axis, horiz = axis.horiz, options = plotLine.options, optionsLabel = options.label, label = plotLine.label, to = options.to, from = options.from, value = options.value, isBand = defined(from) && defined(to), isLine = defined(value), svgElem = plotLine.svgElem, isNew = !svgElem, path = [], addEvent, eventType, color = options.color, zIndex = pick(options.zIndex, 0), events = options.events, attribs = { 'class': 'highcharts-plot-' + (isBand ? 'band ' : 'line ') + (options.className || '') }, groupAttribs = {}, renderer = axis.chart.renderer, groupName = isBand ? 'bands' : 'lines', group, log2lin = axis.log2lin; // logarithmic conversion if (axis.isLog) { from = log2lin(from); to = log2lin(to); value = log2lin(value); } // Grouping and zIndex groupAttribs.zIndex = zIndex; groupName += '-' + zIndex; group = axis[groupName]; if (!group) { axis[groupName] = group = renderer.g('plot-' + groupName) .attr(groupAttribs).add(); } // Create the path if (isNew) { plotLine.svgElem = svgElem = renderer .path() .attr(attribs).add(group); } // Set the path or return if (isLine) { path = axis.getPlotLinePath(value, svgElem.strokeWidth()); } else if (isBand) { // plot band path = axis.getPlotBandPath(from, to, options); } else { return; } // common for lines and bands if (isNew && path && path.length) { svgElem.attr({ d: path }); // events if (events) { addEvent = function(eventType) { svgElem.on(eventType, function(e) { events[eventType].apply(plotLine, [e]); }); }; for (eventType in events) { addEvent(eventType); } } } else if (svgElem) { if (path) { svgElem.show(); svgElem.animate({ d: path }); } else { svgElem.hide(); if (label) { plotLine.label = label = label.destroy(); } } } // the plot band/line label if (optionsLabel && defined(optionsLabel.text) && path && path.length && axis.width > 0 && axis.height > 0 && !path.flat) { // apply defaults optionsLabel = merge({ align: horiz && isBand && 'center', x: horiz ? !isBand && 4 : 10, verticalAlign: !horiz && isBand && 'middle', y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4, rotation: horiz && !isBand && 90 }, optionsLabel); this.renderLabel(optionsLabel, path, isBand, zIndex); } else if (label) { // move out of sight label.hide(); } // chainable return plotLine; }, /** * Render and align label for plot line or band. */ renderLabel: function(optionsLabel, path, isBand, zIndex) { var plotLine = this, label = plotLine.label, renderer = plotLine.axis.chart.renderer, attribs, xs, ys, x, y; // add the SVG element if (!label) { attribs = { align: optionsLabel.textAlign || optionsLabel.align, rotation: optionsLabel.rotation, 'class': 'highcharts-plot-' + (isBand ? 'band' : 'line') + '-label ' + (optionsLabel.className || '') }; attribs.zIndex = zIndex; plotLine.label = label = renderer.text( optionsLabel.text, 0, 0, optionsLabel.useHTML ) .attr(attribs) .add(); } // get the bounding box and align the label // #3000 changed to better handle choice between plotband or plotline xs = [path[1], path[4], (isBand ? path[6] : path[1])]; ys = [path[2], path[5], (isBand ? path[7] : path[2])]; x = arrayMin(xs); y = arrayMin(ys); label.align(optionsLabel, false, { x: x, y: y, width: arrayMax(xs) - x, height: arrayMax(ys) - y }); label.show(); }, /** * Remove the plot line or band */ destroy: function() { // remove it from the lookup erase(this.axis.plotLinesAndBands, this); delete this.axis; destroyObjectProperties(this); } }; /** * Object with members for extending the Axis prototype * @todo Extend directly instead of adding object to Highcharts first */ H.AxisPlotLineOrBandExtension = { /** * Create the path for a plot band */ getPlotBandPath: function(from, to) { var toPath = this.getPlotLinePath(to, null, null, true), path = this.getPlotLinePath(from, null, null, true); if (path && toPath) { // Flat paths don't need labels (#3836) path.flat = path.toString() === toPath.toString(); path.push( toPath[4], toPath[5], toPath[1], toPath[2] ); } else { // outside the axis area path = null; } return path; }, addPlotBand: function(options) { return this.addPlotBandOrLine(options, 'plotBands'); }, addPlotLine: function(options) { return this.addPlotBandOrLine(options, 'plotLines'); }, /** * Add a plot band or plot line after render time * * @param options {Object} The plotBand or plotLine configuration object */ addPlotBandOrLine: function(options, coll) { var obj = new H.PlotLineOrBand(this, options).render(), userOptions = this.userOptions; if (obj) { // #2189 // Add it to the user options for exporting and Axis.update if (coll) { userOptions[coll] = userOptions[coll] || []; userOptions[coll].push(options); } this.plotLinesAndBands.push(obj); } return obj; }, /** * Remove a plot band or plot line from the chart by id * @param {Object} id */ removePlotBandOrLine: function(id) { var plotLinesAndBands = this.plotLinesAndBands, options = this.options, userOptions = this.userOptions, i = plotLinesAndBands.length; while (i--) { if (plotLinesAndBands[i].id === id) { plotLinesAndBands[i].destroy(); } } each([options.plotLines || [], userOptions.plotLines || [], options.plotBands || [], userOptions.plotBands || []], function(arr) { i = arr.length; while (i--) { if (arr[i].id === id) { erase(arr, arr[i]); } } }); } }; }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var addEvent = H.addEvent, animObject = H.animObject, arrayMax = H.arrayMax, arrayMin = H.arrayMin, AxisPlotLineOrBandExtension = H.AxisPlotLineOrBandExtension, color = H.color, correctFloat = H.correctFloat, defaultOptions = H.defaultOptions, defined = H.defined, deg2rad = H.deg2rad, destroyObjectProperties = H.destroyObjectProperties, each = H.each, error = H.error, extend = H.extend, fireEvent = H.fireEvent, format = H.format, getMagnitude = H.getMagnitude, grep = H.grep, inArray = H.inArray, isArray = H.isArray, isNumber = H.isNumber, isString = H.isString, merge = H.merge, normalizeTickInterval = H.normalizeTickInterval, pick = H.pick, PlotLineOrBand = H.PlotLineOrBand, removeEvent = H.removeEvent, splat = H.splat, syncTimeout = H.syncTimeout, Tick = H.Tick; /** * Create a new axis object * @param {Object} chart * @param {Object} options */ H.Axis = function() { this.init.apply(this, arguments); }; H.Axis.prototype = { /** * Default options for the X axis - the Y axis has extended defaults */ defaultOptions: { // allowDecimals: null, // alternateGridColor: null, // categories: [], dateTimeLabelFormats: { millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%e. %b', week: '%e. %b', month: '%b \'%y', year: '%Y' }, endOnTick: false, // reversed: false, labels: { enabled: true, // rotation: 0, // align: 'center', // step: null, x: 0 //y: undefined /*formatter: function () { return this.value; },*/ }, //linkedTo: null, //max: undefined, //min: undefined, minPadding: 0.01, maxPadding: 0.01, //minRange: null, //minorTickInterval: null, minorTickLength: 2, minorTickPosition: 'outside', // inside or outside //opposite: false, //offset: 0, //plotBands: [{ // events: {}, // zIndex: 1, // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //plotLines: [{ // events: {} // dashStyle: {} // zIndex: // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //reversed: false, // showFirstLabel: true, // showLastLabel: true, startOfWeek: 1, startOnTick: false, //tickInterval: null, tickLength: 10, tickmarkPlacement: 'between', // on or between tickPixelInterval: 100, tickPosition: 'outside', title: { //text: null, align: 'middle', // low, middle or high //margin: 0 for horizontal, 10 for vertical axes, //rotation: 0, //side: 'outside', //x: 0, //y: 0 }, type: 'linear', // linear, logarithmic or datetime //visible: true }, /** * This options set extends the defaultOptions for Y axes */ defaultYAxisOptions: { endOnTick: true, tickPixelInterval: 72, showLastLabel: true, labels: { x: -8 }, maxPadding: 0.05, minPadding: 0.05, startOnTick: true, title: { rotation: 270, text: 'Values' }, stackLabels: { enabled: false, //align: dynamic, //y: dynamic, //x: dynamic, //verticalAlign: dynamic, //textAlign: dynamic, //rotation: 0, formatter: function() { return H.numberFormat(this.total, -1); } } }, /** * These options extend the defaultOptions for left axes */ defaultLeftAxisOptions: { labels: { x: -15 }, title: { rotation: 270 } }, /** * These options extend the defaultOptions for right axes */ defaultRightAxisOptions: { labels: { x: 15 }, title: { rotation: 90 } }, /** * These options extend the defaultOptions for bottom axes */ defaultBottomAxisOptions: { labels: { autoRotation: [-45], x: 0 // overflow: undefined, // staggerLines: null }, title: { rotation: 0 } }, /** * These options extend the defaultOptions for top axes */ defaultTopAxisOptions: { labels: { autoRotation: [-45], x: 0 // overflow: undefined // staggerLines: null }, title: { rotation: 0 } }, /** * Initialize the axis */ init: function(chart, userOptions) { var isXAxis = userOptions.isX, axis = this; axis.chart = chart; // Flag, is the axis horizontal axis.horiz = chart.inverted ? !isXAxis : isXAxis; // Flag, isXAxis axis.isXAxis = isXAxis; axis.coll = axis.coll || (isXAxis ? 'xAxis' : 'yAxis'); axis.opposite = userOptions.opposite; // needed in setOptions axis.side = userOptions.side || (axis.horiz ? (axis.opposite ? 0 : 2) : // top : bottom (axis.opposite ? 1 : 3)); // right : left axis.setOptions(userOptions); var options = this.options, type = options.type, isDatetimeAxis = type === 'datetime'; axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format // Flag, stagger lines or not axis.userOptions = userOptions; //axis.axisTitleMargin = undefined,// = options.title.margin, axis.minPixelPadding = 0; axis.reversed = options.reversed; axis.visible = options.visible !== false; axis.zoomEnabled = options.zoomEnabled !== false; // Initial categories axis.hasNames = type === 'category' || options.categories === true; axis.categories = options.categories || axis.hasNames; axis.names = axis.names || []; // Preserve on update (#3830) // Elements //axis.axisGroup = undefined; //axis.gridGroup = undefined; //axis.axisTitle = undefined; //axis.axisLine = undefined; // Shorthand types axis.isLog = type === 'logarithmic'; axis.isDatetimeAxis = isDatetimeAxis; // Flag, if axis is linked to another axis axis.isLinked = defined(options.linkedTo); // Linked axis. //axis.linkedParent = undefined; // Tick positions //axis.tickPositions = undefined; // array containing predefined positions // Tick intervals //axis.tickInterval = undefined; //axis.minorTickInterval = undefined; // Major ticks axis.ticks = {}; axis.labelEdge = []; // Minor ticks axis.minorTicks = {}; // List of plotLines/Bands axis.plotLinesAndBands = []; // Alternate bands axis.alternateBands = {}; // Axis metrics //axis.left = undefined; //axis.top = undefined; //axis.width = undefined; //axis.height = undefined; //axis.bottom = undefined; //axis.right = undefined; //axis.transA = undefined; //axis.transB = undefined; //axis.oldTransA = undefined; axis.len = 0; //axis.oldMin = undefined; //axis.oldMax = undefined; //axis.oldUserMin = undefined; //axis.oldUserMax = undefined; //axis.oldAxisLength = undefined; axis.minRange = axis.userMinRange = options.minRange || options.maxZoom; axis.range = options.range; axis.offset = options.offset || 0; // Dictionary for stacks axis.stacks = {}; axis.oldStacks = {}; axis.stacksTouched = 0; // Min and max in the data //axis.dataMin = undefined, //axis.dataMax = undefined, // The axis range axis.max = null; axis.min = null; // User set min and max //axis.userMin = undefined, //axis.userMax = undefined, // Crosshair options axis.crosshair = pick(options.crosshair, splat(chart.options.tooltip.crosshairs)[isXAxis ? 0 : 1], false); // Run Axis var eventType, events = axis.options.events; // Register if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update() if (isXAxis) { // #2713 chart.axes.splice(chart.xAxis.length, 0, axis); } else { chart.axes.push(axis); } chart[axis.coll].push(axis); } axis.series = axis.series || []; // populated by Series // inverted charts have reversed xAxes as default if (chart.inverted && isXAxis && axis.reversed === undefined) { axis.reversed = true; } axis.removePlotBand = axis.removePlotBandOrLine; axis.removePlotLine = axis.removePlotBandOrLine; // register event listeners for (eventType in events) { addEvent(axis, eventType, events[eventType]); } // extend logarithmic axis if (axis.isLog) { axis.val2lin = axis.log2lin; axis.lin2val = axis.lin2log; } }, /** * Merge and set options */ setOptions: function(userOptions) { this.options = merge( this.defaultOptions, this.coll === 'yAxis' && this.defaultYAxisOptions, [this.defaultTopAxisOptions, this.defaultRightAxisOptions, this.defaultBottomAxisOptions, this.defaultLeftAxisOptions ][this.side], merge( defaultOptions[this.coll], // if set in setOptions (#1053) userOptions ) ); }, /** * The default label formatter. The context is a special config object for the label. */ defaultLabelFormatter: function() { var axis = this.axis, value = this.value, categories = axis.categories, dateTimeLabelFormat = this.dateTimeLabelFormat, numericSymbols = defaultOptions.lang.numericSymbols, i = numericSymbols && numericSymbols.length, multi, ret, formatOption = axis.options.labels.format, // make sure the same symbol is added for all labels on a linear axis numericSymbolDetector = axis.isLog ? value : axis.tickInterval; if (formatOption) { ret = format(formatOption, this); } else if (categories) { ret = value; } else if (dateTimeLabelFormat) { // datetime axis ret = H.dateFormat(dateTimeLabelFormat, value); } else if (i && numericSymbolDetector >= 1000) { // Decide whether we should add a numeric symbol like k (thousands) or M (millions). // If we are to enable this in tooltip or other places as well, we can move this // logic to the numberFormatter and enable it by a parameter. while (i-- && ret === undefined) { multi = Math.pow(1000, i + 1); if (numericSymbolDetector >= multi && (value * 10) % multi === 0 && numericSymbols[i] !== null && value !== 0) { // #5480 ret = H.numberFormat(value / multi, -1) + numericSymbols[i]; } } } if (ret === undefined) { if (Math.abs(value) >= 10000) { // add thousands separators ret = H.numberFormat(value, -1); } else { // small numbers ret = H.numberFormat(value, -1, undefined, ''); // #2466 } } return ret; }, /** * Get the minimum and maximum for the series of each axis */ getSeriesExtremes: function() { var axis = this, chart = axis.chart; axis.hasVisibleSeries = false; // Reset properties in case we're redrawing (#3353) axis.dataMin = axis.dataMax = axis.threshold = null; axis.softThreshold = !axis.isXAxis; if (axis.buildStacks) { axis.buildStacks(); } // loop through this axis' series each(axis.series, function(series) { if (series.visible || !chart.options.chart.ignoreHiddenSeries) { var seriesOptions = series.options, xData, threshold = seriesOptions.threshold, seriesDataMin, seriesDataMax; axis.hasVisibleSeries = true; // Validate threshold in logarithmic axes if (axis.isLog && threshold <= 0) { threshold = null; } // Get dataMin and dataMax for X axes if (axis.isXAxis) { xData = series.xData; if (xData.length) { // If xData contains values which is not numbers, then filter them out. // To prevent performance hit, we only do this after we have already // found seriesDataMin because in most cases all data is valid. #5234. seriesDataMin = arrayMin(xData); if (!isNumber(seriesDataMin) && !(seriesDataMin instanceof Date)) { // Date for #5010 xData = grep(xData, function(x) { return isNumber(x); }); seriesDataMin = arrayMin(xData); // Do it again with valid data } axis.dataMin = Math.min(pick(axis.dataMin, xData[0]), seriesDataMin); axis.dataMax = Math.max(pick(axis.dataMax, xData[0]), arrayMax(xData)); } // Get dataMin and dataMax for Y axes, as well as handle stacking and processed data } else { // Get this particular series extremes series.getExtremes(); seriesDataMax = series.dataMax; seriesDataMin = series.dataMin; // Get the dataMin and dataMax so far. If percentage is used, the min and max are // always 0 and 100. If seriesDataMin and seriesDataMax is null, then series // doesn't have active y data, we continue with nulls if (defined(seriesDataMin) && defined(seriesDataMax)) { axis.dataMin = Math.min(pick(axis.dataMin, seriesDataMin), seriesDataMin); axis.dataMax = Math.max(pick(axis.dataMax, seriesDataMax), seriesDataMax); } // Adjust to threshold if (defined(threshold)) { axis.threshold = threshold; } // If any series has a hard threshold, it takes precedence if (!seriesOptions.softThreshold || axis.isLog) { axis.softThreshold = false; } } } }); }, /** * Translate from axis value to pixel position on the chart, or back * */ translate: function(val, backwards, cvsCoord, old, handleLog, pointPlacement) { var axis = this.linkedParent || this, // #1417 sign = 1, cvsOffset = 0, localA = old ? axis.oldTransA : axis.transA, localMin = old ? axis.oldMin : axis.min, returnValue, minPixelPadding = axis.minPixelPadding, doPostTranslate = (axis.isOrdinal || axis.isBroken || (axis.isLog && handleLog)) && axis.lin2val; if (!localA) { localA = axis.transA; } // In vertical axes, the canvas coordinates start from 0 at the top like in // SVG. if (cvsCoord) { sign *= -1; // canvas coordinates inverts the value cvsOffset = axis.len; } // Handle reversed axis if (axis.reversed) { sign *= -1; cvsOffset -= sign * (axis.sector || axis.len); } // From pixels to value if (backwards) { // reverse translation val = val * sign + cvsOffset; val -= minPixelPadding; returnValue = val / localA + localMin; // from chart pixel to value if (doPostTranslate) { // log and ordinal axes returnValue = axis.lin2val(returnValue); } // From value to pixels } else { if (doPostTranslate) { // log and ordinal axes val = axis.val2lin(val); } if (pointPlacement === 'between') { pointPlacement = 0.5; } returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) + (isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0); } return returnValue; }, /** * Utility method to translate an axis value to pixel position. * @param {Number} value A value in terms of axis units * @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart * or just the axis/pane itself. */ toPixels: function(value, paneCoordinates) { return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos); }, /* * Utility method to translate a pixel position in to an axis value * @param {Number} pixel The pixel value coordinate * @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the * axis/pane itself. */ toValue: function(pixel, paneCoordinates) { return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true); }, /** * Create the path for a plot line that goes from the given value on * this axis, across the plot to the opposite side * @param {Number} value * @param {Number} lineWidth Used for calculation crisp line * @param {Number] old Use old coordinates (for resizing and rescaling) */ getPlotLinePath: function(value, lineWidth, old, force, translatedValue) { var axis = this, chart = axis.chart, axisLeft = axis.left, axisTop = axis.top, x1, y1, x2, y2, cHeight = (old && chart.oldChartHeight) || chart.chartHeight, cWidth = (old && chart.oldChartWidth) || chart.chartWidth, skip, transB = axis.transB, /** * Check if x is between a and b. If not, either move to a/b or skip, * depending on the force parameter. */ between = function(x, a, b) { if (x < a || x > b) { if (force) { x = Math.min(Math.max(a, x), b); } else { skip = true; } } return x; }; translatedValue = pick(translatedValue, axis.translate(value, null, null, old)); x1 = x2 = Math.round(translatedValue + transB); y1 = y2 = Math.round(cHeight - translatedValue - transB); if (!isNumber(translatedValue)) { // no min or max skip = true; } else if (axis.horiz) { y1 = axisTop; y2 = cHeight - axis.bottom; x1 = x2 = between(x1, axisLeft, axisLeft + axis.width); } else { x1 = axisLeft; x2 = cWidth - axis.right; y1 = y2 = between(y1, axisTop, axisTop + axis.height); } return skip && !force ? null : chart.renderer.crispLine(['M', x1, y1, 'L', x2, y2], lineWidth || 1); }, /** * Set the tick positions of a linear axis to round values like whole tens or every five. */ getLinearTickPositions: function(tickInterval, min, max) { var pos, lastPos, roundedMin = correctFloat(Math.floor(min / tickInterval) * tickInterval), roundedMax = correctFloat(Math.ceil(max / tickInterval) * tickInterval), tickPositions = []; // For single points, add a tick regardless of the relative position (#2662) if (min === max && isNumber(min)) { return [min]; } // Populate the intermediate values pos = roundedMin; while (pos <= roundedMax) { // Place the tick on the rounded value tickPositions.push(pos); // Always add the raw tickInterval, not the corrected one. pos = correctFloat(pos + tickInterval); // If the interval is not big enough in the current min - max range to actually increase // the loop variable, we need to break out to prevent endless loop. Issue #619 if (pos === lastPos) { break; } // Record the last value lastPos = pos; } return tickPositions; }, /** * Return the minor tick positions. For logarithmic axes, reuse the same logic * as for major ticks. */ getMinorTickPositions: function() { var axis = this, options = axis.options, tickPositions = axis.tickPositions, minorTickInterval = axis.minorTickInterval, minorTickPositions = [], pos, i, pointRangePadding = axis.pointRangePadding || 0, min = axis.min - pointRangePadding, // #1498 max = axis.max + pointRangePadding, // #1498 range = max - min, len; // If minor ticks get too dense, they are hard to read, and may cause long running script. So we don't draw them. if (range && range / minorTickInterval < axis.len / 3) { // #3875 if (axis.isLog) { len = tickPositions.length; for (i = 1; i < len; i++) { minorTickPositions = minorTickPositions.concat( axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true) ); } } else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314 minorTickPositions = minorTickPositions.concat( axis.getTimeTicks( axis.normalizeTimeTickInterval(minorTickInterval), min, max, options.startOfWeek ) ); } else { for (pos = min + (tickPositions[0] - min) % minorTickInterval; pos <= max; pos += minorTickInterval) { minorTickPositions.push(pos); } } } if (minorTickPositions.length !== 0) { // don't change the extremes, when there is no minor ticks axis.trimTicks(minorTickPositions, options.startOnTick, options.endOnTick); // #3652 #3743 #1498 } return minorTickPositions; }, /** * Adjust the min and max for the minimum range. Keep in mind that the series data is * not yet processed, so we don't have information on data cropping and grouping, or * updated axis.pointRange or series.pointRange. The data can't be processed until * we have finally established min and max. */ adjustForMinRange: function() { var axis = this, options = axis.options, min = axis.min, max = axis.max, zoomOffset, spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange, closestDataRange, i, distance, xData, loopLength, minArgs, maxArgs, minRange; // Set the automatic minimum range based on the closest point distance if (axis.isXAxis && axis.minRange === undefined && !axis.isLog) { if (defined(options.min) || defined(options.max)) { axis.minRange = null; // don't do this again } else { // Find the closest distance between raw data points, as opposed to // closestPointRange that applies to processed points (cropped and grouped) each(axis.series, function(series) { xData = series.xData; loopLength = series.xIncrement ? 1 : xData.length - 1; for (i = loopLength; i > 0; i--) { distance = xData[i] - xData[i - 1]; if (closestDataRange === undefined || distance < closestDataRange) { closestDataRange = distance; } } }); axis.minRange = Math.min(closestDataRange * 5, axis.dataMax - axis.dataMin); } } // if minRange is exceeded, adjust if (max - min < axis.minRange) { minRange = axis.minRange; zoomOffset = (minRange - max + min) / 2; // if min and max options have been set, don't go beyond it minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)]; if (spaceAvailable) { // if space is available, stay within the data range minArgs[2] = axis.isLog ? axis.log2lin(axis.dataMin) : axis.dataMin; } min = arrayMax(minArgs); maxArgs = [min + minRange, pick(options.max, min + minRange)]; if (spaceAvailable) { // if space is availabe, stay within the data range maxArgs[2] = axis.isLog ? axis.log2lin(axis.dataMax) : axis.dataMax; } max = arrayMin(maxArgs); // now if the max is adjusted, adjust the min back if (max - min < minRange) { minArgs[0] = max - minRange; minArgs[1] = pick(options.min, max - minRange); min = arrayMax(minArgs); } } // Record modified extremes axis.min = min; axis.max = max; }, /** * Find the closestPointRange across all series */ getClosest: function() { var ret; if (this.categories) { ret = 1; } else { each(this.series, function(series) { var seriesClosest = series.closestPointRange; if (!series.noSharedTooltip && defined(seriesClosest)) { ret = defined(ret) ? Math.min(ret, seriesClosest) : seriesClosest; } }); } return ret; }, /** * When a point name is given and no x, search for the name in the existing categories, * or if categories aren't provided, search names or create a new category (#2522). */ nameToX: function(point) { var explicitCategories = isArray(this.categories), names = explicitCategories ? this.categories : this.names, nameX = point.options.x, x; point.series.requireSorting = false; if (!defined(nameX)) { nameX = this.options.uniqueNames === false ? point.series.autoIncrement() : inArray(point.name, names); } if (nameX === -1) { // The name is not found in currenct categories if (!explicitCategories) { x = names.length; } } else { x = nameX; } // Write the last point's name to the names array this.names[x] = point.name; return x; }, /** * When changes have been done to series data, update the axis.names. */ updateNames: function() { var axis = this; if (this.names.length > 0) { this.names.length = 0; this.minRange = undefined; each(this.series || [], function(series) { // When adding a series, points are not yet generated if (!series.points || series.isDirtyData) { series.processData(); series.generatePoints(); } each(series.points, function(point, i) { var x; if (point.options && point.options.x === undefined) { x = axis.nameToX(point); if (x !== point.x) { point.x = x; series.xData[i] = x; } } }); }); } }, /** * Update translation information */ setAxisTranslation: function(saveOld) { var axis = this, range = axis.max - axis.min, pointRange = axis.axisPointRange || 0, closestPointRange, minPointOffset = 0, pointRangePadding = 0, linkedParent = axis.linkedParent, ordinalCorrection, hasCategories = !!axis.categories, transA = axis.transA, isXAxis = axis.isXAxis; // Adjust translation for padding. Y axis with categories need to go through the same (#1784). if (isXAxis || hasCategories || pointRange) { if (linkedParent) { minPointOffset = linkedParent.minPointOffset; pointRangePadding = linkedParent.pointRangePadding; } else { // Get the closest points closestPointRange = axis.getClosest(); each(axis.series, function(series) { var seriesPointRange = hasCategories ? 1 : (isXAxis ? pick(series.options.pointRange, closestPointRange, 0) : (axis.axisPointRange || 0)), // #2806 pointPlacement = series.options.pointPlacement; pointRange = Math.max(pointRange, seriesPointRange); if (!axis.single) { // minPointOffset is the value padding to the left of the axis in order to make // room for points with a pointRange, typically columns. When the pointPlacement option // is 'between' or 'on', this padding does not apply. minPointOffset = Math.max( minPointOffset, isString(pointPlacement) ? 0 : seriesPointRange / 2 ); // Determine the total padding needed to the length of the axis to make room for the // pointRange. If the series' pointPlacement is 'on', no padding is added. pointRangePadding = Math.max( pointRangePadding, pointPlacement === 'on' ? 0 : seriesPointRange ); } }); } // Record minPointOffset and pointRangePadding ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853 axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection; axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection; // pointRange means the width reserved for each point, like in a column chart axis.pointRange = Math.min(pointRange, range); // closestPointRange means the closest distance between points. In columns // it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange // is some other value if (isXAxis) { axis.closestPointRange = closestPointRange; } } // Secondary values if (saveOld) { axis.oldTransA = transA; } axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1); axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend axis.minPixelPadding = transA * minPointOffset; }, minFromRange: function() { return this.max - this.range; }, /** * Set the tick positions to round values and optionally extend the extremes * to the nearest tick */ setTickInterval: function(secondPass) { var axis = this, chart = axis.chart, options = axis.options, isLog = axis.isLog, log2lin = axis.log2lin, isDatetimeAxis = axis.isDatetimeAxis, isXAxis = axis.isXAxis, isLinked = axis.isLinked, maxPadding = options.maxPadding, minPadding = options.minPadding, length, linkedParentExtremes, tickIntervalOption = options.tickInterval, minTickInterval, tickPixelIntervalOption = options.tickPixelInterval, categories = axis.categories, threshold = axis.threshold, softThreshold = axis.softThreshold, thresholdMin, thresholdMax, hardMin, hardMax; if (!isDatetimeAxis && !categories && !isLinked) { this.getTickAmount(); } // Min or max set either by zooming/setExtremes or initial options hardMin = pick(axis.userMin, options.min); hardMax = pick(axis.userMax, options.max); // Linked axis gets the extremes from the parent axis if (isLinked) { axis.linkedParent = chart[axis.coll][options.linkedTo]; linkedParentExtremes = axis.linkedParent.getExtremes(); axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin); axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax); if (options.type !== axis.linkedParent.options.type) { error(11, 1); // Can't link axes of different type } // Initial min and max from the extreme data values } else { // Adjust to hard threshold if (!softThreshold && defined(threshold)) { if (axis.dataMin >= threshold) { thresholdMin = threshold; minPadding = 0; } else if (axis.dataMax <= threshold) { thresholdMax = threshold; maxPadding = 0; } } axis.min = pick(hardMin, thresholdMin, axis.dataMin); axis.max = pick(hardMax, thresholdMax, axis.dataMax); } if (isLog) { if (!secondPass && Math.min(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978 error(10, 1); // Can't plot negative values on log axis } // The correctFloat cures #934, float errors on full tens. But it // was too aggressive for #4360 because of conversion back to lin, // therefore use precision 15. axis.min = correctFloat(log2lin(axis.min), 15); axis.max = correctFloat(log2lin(axis.max), 15); } // handle zoomed range if (axis.range && defined(axis.max)) { axis.userMin = axis.min = hardMin = Math.max(axis.min, axis.minFromRange()); // #618 axis.userMax = hardMax = axis.max; axis.range = null; // don't use it when running setExtremes } // Hook for Highstock Scroller. Consider combining with beforePadding. fireEvent(axis, 'foundExtremes'); // Hook for adjusting this.min and this.max. Used by bubble series. if (axis.beforePadding) { axis.beforePadding(); } // adjust min and max for the minimum range axis.adjustForMinRange(); // Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding // into account, we do this after computing tick interval (#1337). if (!categories && !axis.axisPointRange && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) { length = axis.max - axis.min; if (length) { if (!defined(hardMin) && minPadding) { axis.min -= length * minPadding; } if (!defined(hardMax) && maxPadding) { axis.max += length * maxPadding; } } } // Handle options for floor, ceiling, softMin and softMax if (isNumber(options.floor)) { axis.min = Math.max(axis.min, options.floor); } else if (isNumber(options.softMin)) { axis.min = Math.min(axis.min, options.softMin); } if (isNumber(options.ceiling)) { axis.max = Math.min(axis.max, options.ceiling); } else if (isNumber(options.softMax)) { axis.max = Math.max(axis.max, options.softMax); } // When the threshold is soft, adjust the extreme value only if // the data extreme and the padded extreme land on either side of the threshold. For example, // a series of [0, 1, 2, 3] would make the yAxis add a tick for -1 because of the // default minPadding and startOnTick options. This is prevented by the softThreshold // option. if (softThreshold && defined(axis.dataMin)) { threshold = threshold || 0; if (!defined(hardMin) && axis.min < threshold && axis.dataMin >= threshold) { axis.min = threshold; } else if (!defined(hardMax) && axis.max > threshold && axis.dataMax <= threshold) { axis.max = threshold; } } // get tickInterval if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) { axis.tickInterval = 1; } else if (isLinked && !tickIntervalOption && tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) { axis.tickInterval = tickIntervalOption = axis.linkedParent.tickInterval; } else { axis.tickInterval = pick( tickIntervalOption, this.tickAmount ? ((axis.max - axis.min) / Math.max(this.tickAmount - 1, 1)) : undefined, categories ? // for categoried axis, 1 is default, for linear axis use tickPix 1 : // don't let it be more than the data range (axis.max - axis.min) * tickPixelIntervalOption / Math.max(axis.len, tickPixelIntervalOption) ); } // Now we're finished detecting min and max, crop and group series data. This // is in turn needed in order to find tick positions in ordinal axes. if (isXAxis && !secondPass) { each(axis.series, function(series) { series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax); }); } // set the translation factor used in translate function axis.setAxisTranslation(true); // hook for ordinal axes and radial axes if (axis.beforeSetTickPositions) { axis.beforeSetTickPositions(); } // hook for extensions, used in Highstock ordinal axes if (axis.postProcessTickInterval) { axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval); } // In column-like charts, don't cramp in more ticks than there are points (#1943, #4184) if (axis.pointRange && !tickIntervalOption) { axis.tickInterval = Math.max(axis.pointRange, axis.tickInterval); } // Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined. minTickInterval = pick(options.minTickInterval, axis.isDatetimeAxis && axis.closestPointRange); if (!tickIntervalOption && axis.tickInterval < minTickInterval) { axis.tickInterval = minTickInterval; } // for linear axes, get magnitude and normalize the interval if (!isDatetimeAxis && !isLog && !tickIntervalOption) { axis.tickInterval = normalizeTickInterval( axis.tickInterval, null, getMagnitude(axis.tickInterval), // If the tick interval is between 0.5 and 5 and the axis max is in the order of // thousands, chances are we are dealing with years. Don't allow decimals. #3363. pick(options.allowDecimals, !(axis.tickInterval > 0.5 && axis.tickInterval < 5 && axis.max > 1000 && axis.max < 9999)), !!this.tickAmount ); } // Prevent ticks from getting so close that we can't draw the labels if (!this.tickAmount) { axis.tickInterval = axis.unsquish(); } this.setTickPositions(); }, /** * Now we have computed the normalized tickInterval, get the tick positions */ setTickPositions: function() { var options = this.options, tickPositions, tickPositionsOption = options.tickPositions, tickPositioner = options.tickPositioner, startOnTick = options.startOnTick, endOnTick = options.endOnTick, single; // Set the tickmarkOffset this.tickmarkOffset = (this.categories && options.tickmarkPlacement === 'between' && this.tickInterval === 1) ? 0.5 : 0; // #3202 // get minorTickInterval this.minorTickInterval = options.minorTickInterval === 'auto' && this.tickInterval ? this.tickInterval / 5 : options.minorTickInterval; // Find the tick positions this.tickPositions = tickPositions = tickPositionsOption && tickPositionsOption.slice(); // Work on a copy (#1565) if (!tickPositions) { if (this.isDatetimeAxis) { tickPositions = this.getTimeTicks( this.normalizeTimeTickInterval(this.tickInterval, options.units), this.min, this.max, options.startOfWeek, this.ordinalPositions, this.closestPointRange, true ); } else if (this.isLog) { tickPositions = this.getLogTickPositions(this.tickInterval, this.min, this.max); } else { tickPositions = this.getLinearTickPositions(this.tickInterval, this.min, this.max); } // Too dense ticks, keep only the first and last (#4477) if (tickPositions.length > this.len) { tickPositions = [tickPositions[0], tickPositions.pop()]; } this.tickPositions = tickPositions; // Run the tick positioner callback, that allows modifying auto tick positions. if (tickPositioner) { tickPositioner = tickPositioner.apply(this, [this.min, this.max]); if (tickPositioner) { this.tickPositions = tickPositions = tickPositioner; } } } if (!this.isLinked) { // reset min/max or remove extremes based on start/end on tick this.trimTicks(tickPositions, startOnTick, endOnTick); // When there is only one point, or all points have the same value on this axis, then min // and max are equal and tickPositions.length is 0 or 1. In this case, add some padding // in order to center the point, but leave it with one tick. #1337. if (this.min === this.max && defined(this.min) && !this.tickAmount) { // Substract half a unit (#2619, #2846, #2515, #3390) single = true; this.min -= 0.5; this.max += 0.5; } this.single = single; if (!tickPositionsOption && !tickPositioner) { this.adjustTickAmount(); } } }, /** * Handle startOnTick and endOnTick by either adapting to padding min/max or rounded min/max */ trimTicks: function(tickPositions, startOnTick, endOnTick) { var roundedMin = tickPositions[0], roundedMax = tickPositions[tickPositions.length - 1], minPointOffset = this.minPointOffset || 0; if (startOnTick) { this.min = roundedMin; } else { while (this.min - minPointOffset > tickPositions[0]) { tickPositions.shift(); } } if (endOnTick) { this.max = roundedMax; } else { while (this.max + minPointOffset < tickPositions[tickPositions.length - 1]) { tickPositions.pop(); } } // If no tick are left, set one tick in the middle (#3195) if (tickPositions.length === 0 && defined(roundedMin)) { tickPositions.push((roundedMax + roundedMin) / 2); } }, /** * Check if there are multiple axes in the same pane * @returns {Boolean} There are other axes */ alignToOthers: function() { var others = {}, // Whether there is another axis to pair with this one hasOther, options = this.options; if (this.chart.options.chart.alignTicks !== false && options.alignTicks !== false) { each(this.chart[this.coll], function(axis) { var otherOptions = axis.options, horiz = axis.horiz, key = [ horiz ? otherOptions.left : otherOptions.top, otherOptions.width, otherOptions.height, otherOptions.pane ].join(','); if (axis.series.length) { // #4442 if (others[key]) { hasOther = true; // #4201 } else { others[key] = 1; } } }); } return hasOther; }, /** * Set the max ticks of either the x and y axis collection */ getTickAmount: function() { var options = this.options, tickAmount = options.tickAmount, tickPixelInterval = options.tickPixelInterval; if (!defined(options.tickInterval) && this.len < tickPixelInterval && !this.isRadial && !this.isLog && options.startOnTick && options.endOnTick) { tickAmount = 2; } if (!tickAmount && this.alignToOthers()) { // Add 1 because 4 tick intervals require 5 ticks (including first and last) tickAmount = Math.ceil(this.len / tickPixelInterval) + 1; } // For tick amounts of 2 and 3, compute five ticks and remove the intermediate ones. This // prevents the axis from adding ticks that are too far away from the data extremes. if (tickAmount < 4) { this.finalTickAmt = tickAmount; tickAmount = 5; } this.tickAmount = tickAmount; }, /** * When using multiple axes, adjust the number of ticks to match the highest * number of ticks in that group */ adjustTickAmount: function() { var tickInterval = this.tickInterval, tickPositions = this.tickPositions, tickAmount = this.tickAmount, finalTickAmt = this.finalTickAmt, currentTickAmount = tickPositions && tickPositions.length, i, len; if (currentTickAmount < tickAmount) { while (tickPositions.length < tickAmount) { tickPositions.push(correctFloat( tickPositions[tickPositions.length - 1] + tickInterval )); } this.transA *= (currentTickAmount - 1) / (tickAmount - 1); this.max = tickPositions[tickPositions.length - 1]; // We have too many ticks, run second pass to try to reduce ticks } else if (currentTickAmount > tickAmount) { this.tickInterval *= 2; this.setTickPositions(); } // The finalTickAmt property is set in getTickAmount if (defined(finalTickAmt)) { i = len = tickPositions.length; while (i--) { if ( (finalTickAmt === 3 && i % 2 === 1) || // Remove every other tick (finalTickAmt <= 2 && i > 0 && i < len - 1) // Remove all but first and last ) { tickPositions.splice(i, 1); } } this.finalTickAmt = undefined; } }, /** * Set the scale based on data min and max, user set min and max or options * */ setScale: function() { var axis = this, isDirtyData, isDirtyAxisLength; axis.oldMin = axis.min; axis.oldMax = axis.max; axis.oldAxisLength = axis.len; // set the new axisLength axis.setAxisSize(); //axisLength = horiz ? axisWidth : axisHeight; isDirtyAxisLength = axis.len !== axis.oldAxisLength; // is there new data? each(axis.series, function(series) { if (series.isDirtyData || series.isDirty || series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well isDirtyData = true; } }); // do we really need to go through all this? if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw || axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax || axis.alignToOthers()) { if (axis.resetStacks) { axis.resetStacks(); } axis.forceRedraw = false; // get data extremes if needed axis.getSeriesExtremes(); // get fixed positions based on tickInterval axis.setTickInterval(); // record old values to decide whether a rescale is necessary later on (#540) axis.oldUserMin = axis.userMin; axis.oldUserMax = axis.userMax; // Mark as dirty if it is not already set to dirty and extremes have changed. #595. if (!axis.isDirty) { axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax; } } else if (axis.cleanStacks) { axis.cleanStacks(); } }, /** * Set the extremes and optionally redraw * @param {Number} newMin * @param {Number} newMax * @param {Boolean} redraw * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * @param {Object} eventArguments * */ setExtremes: function(newMin, newMax, redraw, animation, eventArguments) { var axis = this, chart = axis.chart; redraw = pick(redraw, true); // defaults to true each(axis.series, function(serie) { delete serie.kdTree; }); // Extend the arguments with min and max eventArguments = extend(eventArguments, { min: newMin, max: newMax }); // Fire the event fireEvent(axis, 'setExtremes', eventArguments, function() { // the default event handler axis.userMin = newMin; axis.userMax = newMax; axis.eventArgs = eventArguments; if (redraw) { chart.redraw(animation); } }); }, /** * Overridable method for zooming chart. Pulled out in a separate method to allow overriding * in stock charts. */ zoom: function(newMin, newMax) { var dataMin = this.dataMin, dataMax = this.dataMax, options = this.options, min = Math.min(dataMin, pick(options.min, dataMin)), max = Math.max(dataMax, pick(options.max, dataMax)); if (newMin !== this.min || newMax !== this.max) { // #5790 // Prevent pinch zooming out of range. Check for defined is for #1946. #1734. if (!this.allowZoomOutside) { if (defined(dataMin) && newMin <= min) { newMin = min; } if (defined(dataMax) && newMax >= max) { newMax = max; } } // In full view, displaying the reset zoom button is not required this.displayBtn = newMin !== undefined || newMax !== undefined; // Do it this.setExtremes( newMin, newMax, false, undefined, { trigger: 'zoom' } ); } return true; }, /** * Update the axis metrics */ setAxisSize: function() { var chart = this.chart, options = this.options, offsetLeft = options.offsetLeft || 0, offsetRight = options.offsetRight || 0, horiz = this.horiz, width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight), height = pick(options.height, chart.plotHeight), top = pick(options.top, chart.plotTop), left = pick(options.left, chart.plotLeft + offsetLeft), percentRegex = /%$/; // Check for percentage based input values. Rounding fixes problems with // column overflow and plot line filtering (#4898, #4899) if (percentRegex.test(height)) { height = Math.round(parseFloat(height) / 100 * chart.plotHeight); } if (percentRegex.test(top)) { top = Math.round(parseFloat(top) / 100 * chart.plotHeight + chart.plotTop); } // Expose basic values to use in Series object and navigator this.left = left; this.top = top; this.width = width; this.height = height; this.bottom = chart.chartHeight - height - top; this.right = chart.chartWidth - width - left; // Direction agnostic properties this.len = Math.max(horiz ? width : height, 0); // Math.max fixes #905 this.pos = horiz ? left : top; // distance from SVG origin }, /** * Get the actual axis extremes */ getExtremes: function() { var axis = this, isLog = axis.isLog, lin2log = axis.lin2log; return { min: isLog ? correctFloat(lin2log(axis.min)) : axis.min, max: isLog ? correctFloat(lin2log(axis.max)) : axis.max, dataMin: axis.dataMin, dataMax: axis.dataMax, userMin: axis.userMin, userMax: axis.userMax }; }, /** * Get the zero plane either based on zero or on the min or max value. * Used in bar and area plots */ getThreshold: function(threshold) { var axis = this, isLog = axis.isLog, lin2log = axis.lin2log, realMin = isLog ? lin2log(axis.min) : axis.min, realMax = isLog ? lin2log(axis.max) : axis.max; if (threshold === null) { threshold = realMin; } else if (realMin > threshold) { threshold = realMin; } else if (realMax < threshold) { threshold = realMax; } return axis.translate(threshold, 0, 1, 0, 1); }, /** * Compute auto alignment for the axis label based on which side the axis is on * and the given rotation for the label */ autoLabelAlign: function(rotation) { var ret, angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360; if (angle > 15 && angle < 165) { ret = 'right'; } else if (angle > 195 && angle < 345) { ret = 'left'; } else { ret = 'center'; } return ret; }, /** * Get the tick length and width for the axis. * @param {String} prefix 'tick' or 'minorTick' * @returns {Array} An array of tickLength and tickWidth */ tickSize: function(prefix) { var options = this.options, tickLength = options[prefix + 'Length'], tickWidth = pick(options[prefix + 'Width'], prefix === 'tick' && this.isXAxis ? 1 : 0); // X axis defaults to 1 if (tickWidth && tickLength) { // Negate the length if (options[prefix + 'Position'] === 'inside') { tickLength = -tickLength; } return [tickLength, tickWidth]; } }, /** * Return the size of the labels */ labelMetrics: function() { return this.chart.renderer.fontMetrics( this.options.labels.style && this.options.labels.style.fontSize, this.ticks[0] && this.ticks[0].label ); }, /** * Prevent the ticks from getting so close we can't draw the labels. On a horizontal * axis, this is handled by rotating the labels, removing ticks and adding ellipsis. * On a vertical axis remove ticks and add ellipsis. */ unsquish: function() { var labelOptions = this.options.labels, horiz = this.horiz, tickInterval = this.tickInterval, newTickInterval = tickInterval, slotSize = this.len / (((this.categories ? 1 : 0) + this.max - this.min) / tickInterval), rotation, rotationOption = labelOptions.rotation, labelMetrics = this.labelMetrics(), step, bestScore = Number.MAX_VALUE, autoRotation, // Return the multiple of tickInterval that is needed to avoid collision getStep = function(spaceNeeded) { var step = spaceNeeded / (slotSize || 1); step = step > 1 ? Math.ceil(step) : 1; return step * tickInterval; }; if (horiz) { autoRotation = !labelOptions.staggerLines && !labelOptions.step && ( // #3971 defined(rotationOption) ? [rotationOption] : slotSize < pick(labelOptions.autoRotationLimit, 80) && labelOptions.autoRotation ); if (autoRotation) { // Loop over the given autoRotation options, and determine which gives the best score. The // best score is that with the lowest number of steps and a rotation closest to horizontal. each(autoRotation, function(rot) { var score; if (rot === rotationOption || (rot && rot >= -90 && rot <= 90)) { // #3891 step = getStep(Math.abs(labelMetrics.h / Math.sin(deg2rad * rot))); score = step + Math.abs(rot / 360); if (score < bestScore) { bestScore = score; rotation = rot; newTickInterval = step; } } }); } } else if (!labelOptions.step) { // #4411 newTickInterval = getStep(labelMetrics.h); } this.autoRotation = autoRotation; this.labelRotation = pick(rotation, rotationOption); return newTickInterval; }, /** * Get the general slot width for this axis. This may change between the pre-render (from Axis.getOffset) * and the final tick rendering and placement (#5086). */ getSlotWidth: function() { var chart = this.chart, horiz = this.horiz, labelOptions = this.options.labels, slotCount = Math.max(this.tickPositions.length - (this.categories ? 0 : 1), 1), marginLeft = chart.margin[3]; return (horiz && (labelOptions.step || 0) < 2 && !labelOptions.rotation && // #4415 ((this.staggerLines || 1) * chart.plotWidth) / slotCount) || (!horiz && ((marginLeft && (marginLeft - chart.spacing[3])) || chart.chartWidth * 0.33)); // #1580, #1931 }, /** * Render the axis labels and determine whether ellipsis or rotation need to be applied */ renderUnsquish: function() { var chart = this.chart, renderer = chart.renderer, tickPositions = this.tickPositions, ticks = this.ticks, labelOptions = this.options.labels, horiz = this.horiz, slotWidth = this.getSlotWidth(), innerWidth = Math.max(1, Math.round(slotWidth - 2 * (labelOptions.padding || 5))), attr = {}, labelMetrics = this.labelMetrics(), textOverflowOption = labelOptions.style && labelOptions.style.textOverflow, css, maxLabelLength = 0, label, i, pos; // Set rotation option unless it is "auto", like in gauges if (!isString(labelOptions.rotation)) { attr.rotation = labelOptions.rotation || 0; // #4443 } // Get the longest label length each(tickPositions, function(tick) { tick = ticks[tick]; if (tick && tick.labelLength > maxLabelLength) { maxLabelLength = tick.labelLength; } }); this.maxLabelLength = maxLabelLength; // Handle auto rotation on horizontal axis if (this.autoRotation) { // Apply rotation only if the label is too wide for the slot, and // the label is wider than its height. if (maxLabelLength > innerWidth && maxLabelLength > labelMetrics.h) { attr.rotation = this.labelRotation; } else { this.labelRotation = 0; } // Handle word-wrap or ellipsis on vertical axis } else if (slotWidth) { // For word-wrap or ellipsis css = { width: innerWidth + 'px' }; if (!textOverflowOption) { css.textOverflow = 'clip'; // On vertical axis, only allow word wrap if there is room for more lines. i = tickPositions.length; while (!horiz && i--) { pos = tickPositions[i]; label = ticks[pos].label; if (label) { // Reset ellipsis in order to get the correct bounding box (#4070) if (label.styles && label.styles.textOverflow === 'ellipsis') { label.css({ textOverflow: 'clip' }); // Set the correct width in order to read the bounding box height (#4678, #5034) } else if (ticks[pos].labelLength > slotWidth) { label.css({ width: slotWidth + 'px' }); } if (label.getBBox().height > this.len / tickPositions.length - (labelMetrics.h - labelMetrics.f)) { label.specCss = { textOverflow: 'ellipsis' }; } } } } } // Add ellipsis if the label length is significantly longer than ideal if (attr.rotation) { css = { width: (maxLabelLength > chart.chartHeight * 0.5 ? chart.chartHeight * 0.33 : chart.chartHeight) + 'px' }; if (!textOverflowOption) { css.textOverflow = 'ellipsis'; } } // Set the explicit or automatic label alignment this.labelAlign = labelOptions.align || this.autoLabelAlign(this.labelRotation); if (this.labelAlign) { attr.align = this.labelAlign; } // Apply general and specific CSS each(tickPositions, function(pos) { var tick = ticks[pos], label = tick && tick.label; if (label) { label.attr(attr); // This needs to go before the CSS in old IE (#4502) if (css) { label.css(merge(css, label.specCss)); } delete label.specCss; tick.rotation = attr.rotation; } }); // Note: Why is this not part of getLabelPosition? this.tickRotCorr = renderer.rotCorr(labelMetrics.b, this.labelRotation || 0, this.side !== 0); }, /** * Return true if the axis has associated data */ hasData: function() { return this.hasVisibleSeries || (defined(this.min) && defined(this.max) && !!this.tickPositions); }, /** * Render the tick labels to a preliminary position to get their sizes */ getOffset: function() { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, tickPositions = axis.tickPositions, ticks = axis.ticks, horiz = axis.horiz, side = axis.side, invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side, hasData, showAxis, titleOffset = 0, titleOffsetOption, titleMargin = 0, axisTitleOptions = options.title, labelOptions = options.labels, labelOffset = 0, // reset labelOffsetPadded, opposite = axis.opposite, axisOffset = chart.axisOffset, clipOffset = chart.clipOffset, clip, directionFactor = [-1, 1, 1, -1][side], n, className = options.className, textAlign, axisParent = axis.axisParent, // Used in color axis lineHeightCorrection, tickSize = this.tickSize('tick'); // For reuse in Axis.render hasData = axis.hasData(); axis.showAxis = showAxis = hasData || pick(options.showEmpty, true); // Set/reset staggerLines axis.staggerLines = axis.horiz && labelOptions.staggerLines; // Create the axisGroup and gridGroup elements on first iteration if (!axis.axisGroup) { axis.gridGroup = renderer.g('grid') .attr({ zIndex: options.gridZIndex || 1 }) .addClass('highcharts-' + this.coll.toLowerCase() + '-grid ' + (className || '')) .add(axisParent); axis.axisGroup = renderer.g('axis') .attr({ zIndex: options.zIndex || 2 }) .addClass('highcharts-' + this.coll.toLowerCase() + ' ' + (className || '')) .add(axisParent); axis.labelGroup = renderer.g('axis-labels') .attr({ zIndex: labelOptions.zIndex || 7 }) .addClass('highcharts-' + axis.coll.toLowerCase() + '-labels ' + (className || '')) .add(axisParent); } if (hasData || axis.isLinked) { // Generate ticks each(tickPositions, function(pos) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } else { ticks[pos].addLabel(); // update labels depending on tick interval } }); axis.renderUnsquish(); // Left side must be align: right and right side must have align: left for labels if (labelOptions.reserveSpace !== false && (side === 0 || side === 2 || { 1: 'left', 3: 'right' }[side] === axis.labelAlign || axis.labelAlign === 'center')) { each(tickPositions, function(pos) { // get the highest offset labelOffset = Math.max( ticks[pos].getLabelSize(), labelOffset ); }); } if (axis.staggerLines) { labelOffset *= axis.staggerLines; axis.labelOffset = labelOffset * (axis.opposite ? -1 : 1); } } else { // doesn't have data for (n in ticks) { ticks[n].destroy(); delete ticks[n]; } } if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) { if (!axis.axisTitle) { textAlign = axisTitleOptions.textAlign; if (!textAlign) { textAlign = (horiz ? { low: 'left', middle: 'center', high: 'right' } : { low: opposite ? 'right' : 'left', middle: 'center', high: opposite ? 'left' : 'right' })[axisTitleOptions.align]; } axis.axisTitle = renderer.text( axisTitleOptions.text, 0, 0, axisTitleOptions.useHTML ) .attr({ zIndex: 7, rotation: axisTitleOptions.rotation || 0, align: textAlign }) .addClass('highcharts-axis-title') .add(axis.axisGroup); axis.axisTitle.isNew = true; } if (showAxis) { titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width']; titleOffsetOption = axisTitleOptions.offset; titleMargin = defined(titleOffsetOption) ? 0 : pick(axisTitleOptions.margin, horiz ? 5 : 10); } // hide or show the title depending on whether showEmpty is set axis.axisTitle[showAxis ? 'show' : 'hide'](true); } // Render the axis line axis.renderLine(); // handle automatic or user set offset axis.offset = directionFactor * pick(options.offset, axisOffset[side]); axis.tickRotCorr = axis.tickRotCorr || { x: 0, y: 0 }; // polar if (side === 0) { lineHeightCorrection = -axis.labelMetrics().h; } else if (side === 2) { lineHeightCorrection = axis.tickRotCorr.y; } else { lineHeightCorrection = 0; } // Find the padded label offset labelOffsetPadded = Math.abs(labelOffset) + titleMargin; if (labelOffset) { labelOffsetPadded -= lineHeightCorrection; labelOffsetPadded += directionFactor * (horiz ? pick(labelOptions.y, axis.tickRotCorr.y + directionFactor * 8) : labelOptions.x); } axis.axisTitleMargin = pick(titleOffsetOption, labelOffsetPadded); axisOffset[side] = Math.max( axisOffset[side], axis.axisTitleMargin + titleOffset + directionFactor * axis.offset, labelOffsetPadded, // #3027 hasData && tickPositions.length && tickSize ? tickSize[0] : 0 // #4866 ); // Decide the clipping needed to keep the graph inside the plot area and axis lines clip = options.offset ? 0 : Math.floor(axis.axisLine.strokeWidth() / 2) * 2; // #4308, #4371 clipOffset[invertedSide] = Math.max(clipOffset[invertedSide], clip); }, /** * Get the path for the axis line */ getLinePath: function(lineWidth) { var chart = this.chart, opposite = this.opposite, offset = this.offset, horiz = this.horiz, lineLeft = this.left + (opposite ? this.width : 0) + offset, lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset; if (opposite) { lineWidth *= -1; // crispify the other way - #1480, #1687 } return chart.renderer .crispLine([ 'M', horiz ? this.left : lineLeft, horiz ? lineTop : this.top, 'L', horiz ? chart.chartWidth - this.right : lineLeft, horiz ? lineTop : chart.chartHeight - this.bottom ], lineWidth); }, /** * Render the axis line * @returns {[type]} [description] */ renderLine: function() { if (!this.axisLine) { this.axisLine = this.chart.renderer.path() .addClass('highcharts-axis-line') .add(this.axisGroup); } }, /** * Position the title */ getTitlePosition: function() { // compute anchor points for each of the title align options var horiz = this.horiz, axisLeft = this.left, axisTop = this.top, axisLength = this.len, axisTitleOptions = this.options.title, margin = horiz ? axisLeft : axisTop, opposite = this.opposite, offset = this.offset, xOption = axisTitleOptions.x || 0, yOption = axisTitleOptions.y || 0, fontSize = this.chart.renderer.fontMetrics(axisTitleOptions.style && axisTitleOptions.style.fontSize, this.axisTitle).f, // the position in the length direction of the axis alongAxis = { low: margin + (horiz ? 0 : axisLength), middle: margin + axisLength / 2, high: margin + (horiz ? axisLength : 0) }[axisTitleOptions.align], // the position in the perpendicular direction of the axis offAxis = (horiz ? axisTop + this.height : axisLeft) + (horiz ? 1 : -1) * // horizontal axis reverses the margin (opposite ? -1 : 1) * // so does opposite axes this.axisTitleMargin + (this.side === 2 ? fontSize : 0); return { x: horiz ? alongAxis + xOption : offAxis + (opposite ? this.width : 0) + offset + xOption, y: horiz ? offAxis + yOption - (opposite ? this.height : 0) + offset : alongAxis + yOption }; }, /** * Render the axis */ render: function() { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, isLog = axis.isLog, lin2log = axis.lin2log, isLinked = axis.isLinked, tickPositions = axis.tickPositions, axisTitle = axis.axisTitle, ticks = axis.ticks, minorTicks = axis.minorTicks, alternateBands = axis.alternateBands, stackLabelOptions = options.stackLabels, alternateGridColor = options.alternateGridColor, tickmarkOffset = axis.tickmarkOffset, axisLine = axis.axisLine, hasRendered = chart.hasRendered, slideInTicks = hasRendered && isNumber(axis.oldMin), showAxis = axis.showAxis, animation = animObject(renderer.globalAnimation), from, to; // Reset axis.labelEdge.length = 0; //axis.justifyToPlot = overflow === 'justify'; axis.overlap = false; // Mark all elements inActive before we go over and mark the active ones each([ticks, minorTicks, alternateBands], function(coll) { var pos; for (pos in coll) { coll[pos].isActive = false; } }); // If the series has data draw the ticks. Else only the line and title if (axis.hasData() || isLinked) { // minor ticks if (axis.minorTickInterval && !axis.categories) { each(axis.getMinorTickPositions(), function(pos) { if (!minorTicks[pos]) { minorTicks[pos] = new Tick(axis, pos, 'minor'); } // render new ticks in old position if (slideInTicks && minorTicks[pos].isNew) { minorTicks[pos].render(null, true); } minorTicks[pos].render(null, false, 1); }); } // Major ticks. Pull out the first item and render it last so that // we can get the position of the neighbour label. #808. if (tickPositions.length) { // #1300 each(tickPositions, function(pos, i) { // linked axes need an extra check to find out if if (!isLinked || (pos >= axis.min && pos <= axis.max)) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } // render new ticks in old position if (slideInTicks && ticks[pos].isNew) { ticks[pos].render(i, true, 0.1); } ticks[pos].render(i); } }); // In a categorized axis, the tick marks are displayed between labels. So // we need to add a tick mark and grid line at the left edge of the X axis. if (tickmarkOffset && (axis.min === 0 || axis.single)) { if (!ticks[-1]) { ticks[-1] = new Tick(axis, -1, null, true); } ticks[-1].render(-1); } } // alternate grid color if (alternateGridColor) { each(tickPositions, function(pos, i) { to = tickPositions[i + 1] !== undefined ? tickPositions[i + 1] + tickmarkOffset : axis.max - tickmarkOffset; if (i % 2 === 0 && pos < axis.max && to <= axis.max + (chart.polar ? -tickmarkOffset : tickmarkOffset)) { // #2248, #4660 if (!alternateBands[pos]) { alternateBands[pos] = new PlotLineOrBand(axis); } from = pos + tickmarkOffset; // #949 alternateBands[pos].options = { from: isLog ? lin2log(from) : from, to: isLog ? lin2log(to) : to, color: alternateGridColor }; alternateBands[pos].render(); alternateBands[pos].isActive = true; } }); } // custom plot lines and bands if (!axis._addedPlotLB) { // only first time each((options.plotLines || []).concat(options.plotBands || []), function(plotLineOptions) { axis.addPlotBandOrLine(plotLineOptions); }); axis._addedPlotLB = true; } } // end if hasData // Remove inactive ticks each([ticks, minorTicks, alternateBands], function(coll) { var pos, i, forDestruction = [], delay = animation.duration, destroyInactiveItems = function() { i = forDestruction.length; while (i--) { // When resizing rapidly, the same items may be destroyed in different timeouts, // or the may be reactivated if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) { coll[forDestruction[i]].destroy(); delete coll[forDestruction[i]]; } } }; for (pos in coll) { if (!coll[pos].isActive) { // Render to zero opacity coll[pos].render(pos, false, 0); coll[pos].isActive = false; forDestruction.push(pos); } } // When the objects are finished fading out, destroy them syncTimeout( destroyInactiveItems, coll === alternateBands || !chart.hasRendered || !delay ? 0 : delay ); }); // Set the axis line path if (axisLine) { axisLine[axisLine.isPlaced ? 'animate' : 'attr']({ d: this.getLinePath(axisLine.strokeWidth()) }); axisLine.isPlaced = true; // Show or hide the line depending on options.showEmpty axisLine[showAxis ? 'show' : 'hide'](true); } if (axisTitle && showAxis) { axisTitle[axisTitle.isNew ? 'attr' : 'animate']( axis.getTitlePosition() ); axisTitle.isNew = false; } // Stacked totals: if (stackLabelOptions && stackLabelOptions.enabled) { axis.renderStackTotals(); } // End stacked totals axis.isDirty = false; }, /** * Redraw the axis to reflect changes in the data or axis extremes */ redraw: function() { if (this.visible) { // render the axis this.render(); // move plot lines and bands each(this.plotLinesAndBands, function(plotLine) { plotLine.render(); }); } // mark associated series as dirty and ready for redraw each(this.series, function(series) { series.isDirty = true; }); }, /** * Destroys an Axis instance. */ destroy: function(keepEvents) { var axis = this, stacks = axis.stacks, stackKey, plotLinesAndBands = axis.plotLinesAndBands, i, n, keepProps; // Remove the events if (!keepEvents) { removeEvent(axis); } // Destroy each stack total for (stackKey in stacks) { destroyObjectProperties(stacks[stackKey]); stacks[stackKey] = null; } // Destroy collections each([axis.ticks, axis.minorTicks, axis.alternateBands], function(coll) { destroyObjectProperties(coll); }); if (plotLinesAndBands) { i = plotLinesAndBands.length; while (i--) { // #1975 plotLinesAndBands[i].destroy(); } } // Destroy local variables each(['stackTotalGroup', 'axisLine', 'axisTitle', 'axisGroup', 'gridGroup', 'labelGroup', 'cross'], function(prop) { if (axis[prop]) { axis[prop] = axis[prop].destroy(); } }); // Delete all properties and fall back to the prototype. // Preserve some properties, needed for Axis.update (#4317, #5773). keepProps = ['extKey', 'hcEvents', 'names', 'series', 'userMax', 'userMin']; for (n in axis) { if (axis.hasOwnProperty(n) && inArray(n, keepProps) === -1) { delete axis[n]; } } }, /** * Draw the crosshair * * @param {Object} e The event arguments from the modified pointer event * @param {Object} point The Point object */ drawCrosshair: function(e, point) { var path, options = this.crosshair, snap = pick(options.snap, true), pos, categorized, graphic = this.cross; // Use last available event when updating non-snapped crosshairs without // mouse interaction (#5287) if (!e) { e = this.cross && this.cross.e; } if ( // Disabled in options !this.crosshair || // Snap ((defined(point) || !snap) === false) ) { this.hideCrosshair(); } else { // Get the path if (!snap) { pos = e && (this.horiz ? e.chartX - this.pos : this.len - e.chartY + this.pos); } else if (defined(point)) { pos = this.isXAxis ? point.plotX : this.len - point.plotY; // #3834 } if (defined(pos)) { path = this.getPlotLinePath( // First argument, value, only used on radial point && (this.isXAxis ? point.x : pick(point.stackY, point.y)), null, null, null, pos // Translated position ) || null; // #3189 } if (!defined(path)) { this.hideCrosshair(); return; } categorized = this.categories && !this.isRadial; // Draw the cross if (!graphic) { this.cross = graphic = this.chart.renderer .path() .addClass('highcharts-crosshair highcharts-crosshair-' + (categorized ? 'category ' : 'thin ') + options.className) .attr({ zIndex: pick(options.zIndex, 2) }) .add(); } graphic.show().attr({ d: path }); if (categorized && !options.width) { graphic.attr({ 'stroke-width': this.transA }); } this.cross.e = e; } }, /** * Hide the crosshair. */ hideCrosshair: function() { if (this.cross) { this.cross.hide(); } } }; // end Axis extend(H.Axis.prototype, AxisPlotLineOrBandExtension); }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var Axis = H.Axis, getMagnitude = H.getMagnitude, map = H.map, normalizeTickInterval = H.normalizeTickInterval, pick = H.pick; /** * Methods defined on the Axis prototype */ /** * Set the tick positions of a logarithmic axis */ Axis.prototype.getLogTickPositions = function(interval, min, max, minor) { var axis = this, options = axis.options, axisLength = axis.len, lin2log = axis.lin2log, log2lin = axis.log2lin, // Since we use this method for both major and minor ticks, // use a local variable and return the result positions = []; // Reset if (!minor) { axis._minorAutoInterval = null; } // First case: All ticks fall on whole logarithms: 1, 10, 100 etc. if (interval >= 0.5) { interval = Math.round(interval); positions = axis.getLinearTickPositions(interval, min, max); // Second case: We need intermediary ticks. For example // 1, 2, 4, 6, 8, 10, 20, 40 etc. } else if (interval >= 0.08) { var roundedMin = Math.floor(min), intermediate, i, j, len, pos, lastPos, break2; if (interval > 0.3) { intermediate = [1, 2, 4]; } else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc intermediate = [1, 2, 4, 6, 8]; } else { // 0.1 equals ten minor ticks per 1, 10, 100 etc intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9]; } for (i = roundedMin; i < max + 1 && !break2; i++) { len = intermediate.length; for (j = 0; j < len && !break2; j++) { pos = log2lin(lin2log(i) * intermediate[j]); if (pos > min && (!minor || lastPos <= max) && lastPos !== undefined) { // #1670, lastPos is #3113 positions.push(lastPos); } if (lastPos > max) { break2 = true; } lastPos = pos; } } // Third case: We are so deep in between whole logarithmic values that // we might as well handle the tick positions like a linear axis. For // example 1.01, 1.02, 1.03, 1.04. } else { var realMin = lin2log(min), realMax = lin2log(max), tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'], filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption, tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1), totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength; interval = pick( filteredTickIntervalOption, axis._minorAutoInterval, (realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1) ); interval = normalizeTickInterval( interval, null, getMagnitude(interval) ); positions = map(axis.getLinearTickPositions( interval, realMin, realMax ), log2lin); if (!minor) { axis._minorAutoInterval = interval / 5; } } // Set the axis-level tickInterval variable if (!minor) { axis.tickInterval = interval; } return positions; }; Axis.prototype.log2lin = function(num) { return Math.log(num) / Math.LN10; }; Axis.prototype.lin2log = function(num) { return Math.pow(10, num); }; }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var dateFormat = H.dateFormat, each = H.each, extend = H.extend, format = H.format, isNumber = H.isNumber, map = H.map, merge = H.merge, pick = H.pick, splat = H.splat, stop = H.stop, syncTimeout = H.syncTimeout, timeUnits = H.timeUnits; /** * The tooltip object * @param {Object} chart The chart instance * @param {Object} options Tooltip options */ H.Tooltip = function() { this.init.apply(this, arguments); }; H.Tooltip.prototype = { init: function(chart, options) { // Save the chart and options this.chart = chart; this.options = options; // Keep track of the current series //this.currentSeries = undefined; // List of crosshairs this.crosshairs = []; // Current values of x and y when animating this.now = { x: 0, y: 0 }; // The tooltip is initially hidden this.isHidden = true; // Public property for getting the shared state. this.split = options.split && !chart.inverted; this.shared = options.shared || this.split; }, /** * Destroy the single tooltips in a split tooltip. * If the tooltip is active then it is not destroyed, unless forced to. * @param {boolean} force Force destroy all tooltips. * @return {undefined} */ cleanSplit: function(force) { each(this.chart.series, function(series) { var tt = series && series.tt; if (tt) { if (!tt.isActive || force) { series.tt = tt.destroy(); } else { tt.isActive = false; } } }); }, /** * Create the Tooltip label element if it doesn't exist, then return the * label. */ getLabel: function() { var renderer = this.chart.renderer, options = this.options; if (!this.label) { // Create the label if (this.split) { this.label = renderer.g('tooltip'); } else { this.label = renderer.label( '', 0, 0, options.shape || 'callout', null, null, options.useHTML, null, 'tooltip' ) .attr({ padding: options.padding, r: options.borderRadius }); } this.label .attr({ zIndex: 8 }) .add(); } return this.label; }, update: function(options) { this.destroy(); this.init(this.chart, merge(true, this.options, options)); }, /** * Destroy the tooltip and its elements. */ destroy: function() { // Destroy and clear local variables if (this.label) { this.label = this.label.destroy(); } if (this.split && this.tt) { this.cleanSplit(this.chart, true); this.tt = this.tt.destroy(); } clearTimeout(this.hideTimer); clearTimeout(this.tooltipTimeout); }, /** * Provide a soft movement for the tooltip * * @param {Number} x * @param {Number} y * @private */ move: function(x, y, anchorX, anchorY) { var tooltip = this, now = tooltip.now, animate = tooltip.options.animation !== false && !tooltip.isHidden && // When we get close to the target position, abort animation and land on the right place (#3056) (Math.abs(x - now.x) > 1 || Math.abs(y - now.y) > 1), skipAnchor = tooltip.followPointer || tooltip.len > 1; // Get intermediate values for animation extend(now, { x: animate ? (2 * now.x + x) / 3 : x, y: animate ? (now.y + y) / 2 : y, anchorX: skipAnchor ? undefined : animate ? (2 * now.anchorX + anchorX) / 3 : anchorX, anchorY: skipAnchor ? undefined : animate ? (now.anchorY + anchorY) / 2 : anchorY }); // Move to the intermediate value tooltip.getLabel().attr(now); // Run on next tick of the mouse tracker if (animate) { // Never allow two timeouts clearTimeout(this.tooltipTimeout); // Set the fixed interval ticking for the smooth tooltip this.tooltipTimeout = setTimeout(function() { // The interval function may still be running during destroy, // so check that the chart is really there before calling. if (tooltip) { tooltip.move(x, y, anchorX, anchorY); } }, 32); } }, /** * Hide the tooltip */ hide: function(delay) { var tooltip = this; clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766) delay = pick(delay, this.options.hideDelay, 500); if (!this.isHidden) { this.hideTimer = syncTimeout(function() { tooltip.getLabel()[delay ? 'fadeOut' : 'hide'](); tooltip.isHidden = true; }, delay); } }, /** * Extendable method to get the anchor position of the tooltip * from a point or set of points */ getAnchor: function(points, mouseEvent) { var ret, chart = this.chart, inverted = chart.inverted, plotTop = chart.plotTop, plotLeft = chart.plotLeft, plotX = 0, plotY = 0, yAxis, xAxis; points = splat(points); // Pie uses a special tooltipPos ret = points[0].tooltipPos; // When tooltip follows mouse, relate the position to the mouse if (this.followPointer && mouseEvent) { if (mouseEvent.chartX === undefined) { mouseEvent = chart.pointer.normalize(mouseEvent); } ret = [ mouseEvent.chartX - chart.plotLeft, mouseEvent.chartY - plotTop ]; } // When shared, use the average position if (!ret) { each(points, function(point) { yAxis = point.series.yAxis; xAxis = point.series.xAxis; plotX += point.plotX + (!inverted && xAxis ? xAxis.left - plotLeft : 0); plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) + (!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151 }); plotX /= points.length; plotY /= points.length; ret = [ inverted ? chart.plotWidth - plotY : plotX, this.shared && !inverted && points.length > 1 && mouseEvent ? mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424) inverted ? chart.plotHeight - plotX : plotY ]; } return map(ret, Math.round); }, /** * Place the tooltip in a chart without spilling over * and not covering the point it self. */ getPosition: function(boxWidth, boxHeight, point) { var chart = this.chart, distance = this.distance, ret = {}, h = point.h || 0, // #4117 swapped, first = ['y', chart.chartHeight, boxHeight, point.plotY + chart.plotTop, chart.plotTop, chart.plotTop + chart.plotHeight ], second = ['x', chart.chartWidth, boxWidth, point.plotX + chart.plotLeft, chart.plotLeft, chart.plotLeft + chart.plotWidth ], // The far side is right or bottom preferFarSide = !this.followPointer && pick(point.ttBelow, !chart.inverted === !!point.negative), // #4984 /** * Handle the preferred dimension. When the preferred dimension is tooltip * on top or bottom of the point, it will look for space there. */ firstDimension = function(dim, outerSize, innerSize, point, min, max) { var roomLeft = innerSize < point - distance, roomRight = point + distance + innerSize < outerSize, alignedLeft = point - distance - innerSize, alignedRight = point + distance; if (preferFarSide && roomRight) { ret[dim] = alignedRight; } else if (!preferFarSide && roomLeft) { ret[dim] = alignedLeft; } else if (roomLeft) { ret[dim] = Math.min(max - innerSize, alignedLeft - h < 0 ? alignedLeft : alignedLeft - h); } else if (roomRight) { ret[dim] = Math.max( min, alignedRight + h + innerSize > outerSize ? alignedRight : alignedRight + h ); } else { return false; } }, /** * Handle the secondary dimension. If the preferred dimension is tooltip * on top or bottom of the point, the second dimension is to align the tooltip * above the point, trying to align center but allowing left or right * align within the chart box. */ secondDimension = function(dim, outerSize, innerSize, point) { var retVal; // Too close to the edge, return false and swap dimensions if (point < distance || point > outerSize - distance) { retVal = false; // Align left/top } else if (point < innerSize / 2) { ret[dim] = 1; // Align right/bottom } else if (point > outerSize - innerSize / 2) { ret[dim] = outerSize - innerSize - 2; // Align center } else { ret[dim] = point - innerSize / 2; } return retVal; }, /** * Swap the dimensions */ swap = function(count) { var temp = first; first = second; second = temp; swapped = count; }, run = function() { if (firstDimension.apply(0, first) !== false) { if (secondDimension.apply(0, second) === false && !swapped) { swap(true); run(); } } else if (!swapped) { swap(true); run(); } else { ret.x = ret.y = 0; } }; // Under these conditions, prefer the tooltip on the side of the point if (chart.inverted || this.len > 1) { swap(); } run(); return ret; }, /** * In case no user defined formatter is given, this will be used. Note that the context * here is an object holding point, series, x, y etc. * * @returns {String|Array<String>} */ defaultFormatter: function(tooltip) { var items = this.points || splat(this), s; // Build the header s = [tooltip.tooltipFooterHeaderFormatter(items[0])]; // build the values s = s.concat(tooltip.bodyFormatter(items)); // footer s.push(tooltip.tooltipFooterHeaderFormatter(items[0], true)); return s; }, /** * Refresh the tooltip's text and position. * @param {Object} point */ refresh: function(point, mouseEvent) { var tooltip = this, chart = tooltip.chart, label = tooltip.getLabel(), options = tooltip.options, x, y, anchor, textConfig = {}, text, pointConfig = [], formatter = options.formatter || tooltip.defaultFormatter, hoverPoints = chart.hoverPoints, shared = tooltip.shared, currentSeries; clearTimeout(this.hideTimer); // get the reference point coordinates (pie charts use tooltipPos) tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer; anchor = tooltip.getAnchor(point, mouseEvent); x = anchor[0]; y = anchor[1]; // shared tooltip, array is sent over if (shared && !(point.series && point.series.noSharedTooltip)) { // hide previous hoverPoints and set new chart.hoverPoints = point; if (hoverPoints) { each(hoverPoints, function(point) { point.setState(); }); } each(point, function(item) { item.setState('hover'); pointConfig.push(item.getLabelConfig()); }); textConfig = { x: point[0].category, y: point[0].y }; textConfig.points = pointConfig; this.len = pointConfig.length; point = point[0]; // single point tooltip } else { textConfig = point.getLabelConfig(); } text = formatter.call(textConfig, tooltip); // register the current series currentSeries = point.series; this.distance = pick(currentSeries.tooltipOptions.distance, 16); // update the inner HTML if (text === false) { this.hide(); } else { // show it if (tooltip.isHidden) { stop(label); label.attr({ opacity: 1 }).show(); } // update text if (tooltip.split) { this.renderSplit(text, chart.hoverPoints); } else { label.attr({ text: text.join ? text.join('') : text }); // Set the stroke color of the box to reflect the point label.removeClass(/highcharts-color-[\d]+/g) .addClass('highcharts-color-' + pick(point.colorIndex, currentSeries.colorIndex)); tooltip.updatePosition({ plotX: x, plotY: y, negative: point.negative, ttBelow: point.ttBelow, h: anchor[2] || 0 }); } this.isHidden = false; } }, /** * Render the split tooltip. Loops over each point's text and adds * a label next to the point, then uses the distribute function to * find best non-overlapping positions. */ renderSplit: function(labels, points) { var tooltip = this, boxes = [], chart = this.chart, ren = chart.renderer, rightAligned = true, options = this.options, headerHeight, tooltipLabel = this.getLabel(); // Create the individual labels each(labels.slice(0, labels.length - 1), function(str, i) { var point = points[i - 1] || // Item 0 is the header. Instead of this, we could also use the crosshair label { isHeader: true, plotX: points[0].plotX }, owner = point.series || tooltip, tt = owner.tt, series = point.series || {}, colorClass = 'highcharts-color-' + pick(point.colorIndex, series.colorIndex, 'none'), target, x, bBox, boxWidth; // Store the tooltip referance on the series if (!tt) { owner.tt = tt = ren.label(null, null, null, point.isHeader && 'callout') .addClass('highcharts-tooltip-box ' + colorClass) .attr({ 'padding': options.padding, 'r': options.borderRadius }) .add(tooltipLabel); // Add a connector back to the point if (point.series) { tt.connector = ren.path() .addClass('highcharts-tooltip-connector ' + colorClass) // Add it inside the label group so we will get hide and // destroy for free .add(tt); } } tt.isActive = true; tt.attr({ text: str }); // Get X position now, so we can move all to the other side in case of overflow bBox = tt.getBBox(); boxWidth = bBox.width + tt.strokeWidth(); if (point.isHeader) { headerHeight = bBox.height; x = Math.max( 0, // No left overflow Math.min( point.plotX + chart.plotLeft - boxWidth / 2, chart.chartWidth - boxWidth // No right overflow (#5794) ) ); } else { x = point.plotX + chart.plotLeft - pick(options.distance, 16) - boxWidth; } // If overflow left, we don't use this x in the next loop if (x < 0) { rightAligned = false; } // Prepare for distribution target = (point.series && point.series.yAxis && point.series.yAxis.pos) + (point.plotY || 0); target -= chart.plotTop; boxes.push({ target: point.isHeader ? chart.plotHeight + headerHeight : target, rank: point.isHeader ? 1 : 0, size: owner.tt.getBBox().height + 1, point: point, x: x, tt: tt }); }); // Clean previous run (for missing points) this.cleanSplit(); // Distribute and put in place H.distribute(boxes, chart.plotHeight + headerHeight); each(boxes, function(box) { var point = box.point, tt = box.tt, attr; // Put the label in place attr = { visibility: box.pos === undefined ? 'hidden' : 'inherit', x: (rightAligned || point.isHeader ? box.x : point.plotX + chart.plotLeft + pick(options.distance, 16)), y: box.pos + chart.plotTop }; if (point.isHeader) { attr.anchorX = point.plotX + chart.plotLeft; attr.anchorY = attr.y - 100; } tt.attr(attr); // Draw the connector to the point if (!point.isHeader) { tt.connector.attr({ d: [ 'M', point.plotX + chart.plotLeft - attr.x, point.plotY + point.series.yAxis.pos - attr.y, 'L', (rightAligned ? -1 : 1) * pick(options.distance, 16) + point.plotX + chart.plotLeft - attr.x, box.pos + chart.plotTop + tt.getBBox().height / 2 - attr.y ] }); } }); }, /** * Find the new position and perform the move */ updatePosition: function(point) { var chart = this.chart, label = this.getLabel(), pos = (this.options.positioner || this.getPosition).call( this, label.width, label.height, point ); // do the move this.move( Math.round(pos.x), Math.round(pos.y || 0), // can be undefined (#3977) point.plotX + chart.plotLeft, point.plotY + chart.plotTop ); }, /** * Get the best X date format based on the closest point range on the axis. */ getXDateFormat: function(point, options, xAxis) { var xDateFormat, dateTimeLabelFormats = options.dateTimeLabelFormats, closestPointRange = xAxis && xAxis.closestPointRange, n, blank = '01-01 00:00:00.000', strpos = { millisecond: 15, second: 12, minute: 9, hour: 6, day: 3 }, date, lastN = 'millisecond'; // for sub-millisecond data, #4223 if (closestPointRange) { date = dateFormat('%m-%d %H:%M:%S.%L', point.x); for (n in timeUnits) { // If the range is exactly one week and we're looking at a Sunday/Monday, go for the week format if (closestPointRange === timeUnits.week && +dateFormat('%w', point.x) === xAxis.options.startOfWeek && date.substr(6) === blank.substr(6)) { n = 'week'; break; } // The first format that is too great for the range if (timeUnits[n] > closestPointRange) { n = lastN; break; } // If the point is placed every day at 23:59, we need to show // the minutes as well. #2637. if (strpos[n] && date.substr(strpos[n]) !== blank.substr(strpos[n])) { break; } // Weeks are outside the hierarchy, only apply them on Mondays/Sundays like in the first condition if (n !== 'week') { lastN = n; } } if (n) { xDateFormat = dateTimeLabelFormats[n]; } } else { xDateFormat = dateTimeLabelFormats.day; } return xDateFormat || dateTimeLabelFormats.year; // #2546, 2581 }, /** * Format the footer/header of the tooltip * #3397: abstraction to enable formatting of footer and header */ tooltipFooterHeaderFormatter: function(labelConfig, isFooter) { var footOrHead = isFooter ? 'footer' : 'header', series = labelConfig.series, tooltipOptions = series.tooltipOptions, xDateFormat = tooltipOptions.xDateFormat, xAxis = series.xAxis, isDateTime = xAxis && xAxis.options.type === 'datetime' && isNumber(labelConfig.key), formatString = tooltipOptions[footOrHead + 'Format']; // Guess the best date format based on the closest point distance (#568, #3418) if (isDateTime && !xDateFormat) { xDateFormat = this.getXDateFormat(labelConfig, tooltipOptions, xAxis); } // Insert the footer date format if any if (isDateTime && xDateFormat) { formatString = formatString.replace('{point.key}', '{point.key:' + xDateFormat + '}'); } return format(formatString, { point: labelConfig, series: series }); }, /** * Build the body (lines) of the tooltip by iterating over the items and returning one entry for each item, * abstracting this functionality allows to easily overwrite and extend it. */ bodyFormatter: function(items) { return map(items, function(item) { var tooltipOptions = item.series.tooltipOptions; return (tooltipOptions.pointFormatter || item.point.tooltipFormatter) .call(item.point, tooltipOptions.pointFormat); }); } }; }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var addEvent = H.addEvent, attr = H.attr, charts = H.charts, color = H.color, css = H.css, defined = H.defined, doc = H.doc, each = H.each, extend = H.extend, fireEvent = H.fireEvent, offset = H.offset, pick = H.pick, removeEvent = H.removeEvent, splat = H.splat, Tooltip = H.Tooltip, win = H.win; /** * The mouse tracker object. All methods starting with "on" are primary DOM event handlers. * Subsequent methods should be named differently from what they are doing. * @param {Object} chart The Chart instance * @param {Object} options The root options object */ H.Pointer = function(chart, options) { this.init(chart, options); }; H.Pointer.prototype = { /** * Initialize Pointer */ init: function(chart, options) { // Store references this.options = options; this.chart = chart; // Do we need to handle click on a touch device? this.runChartClick = options.chart.events && !!options.chart.events.click; this.pinchDown = []; this.lastValidTouch = {}; if (Tooltip && options.tooltip.enabled) { chart.tooltip = new Tooltip(chart, options.tooltip); this.followTouchMove = pick(options.tooltip.followTouchMove, true); } this.setDOMEvents(); }, /** * Resolve the zoomType option */ zoomOption: function() { var chart = this.chart, zoomType = chart.options.chart.zoomType, zoomX = /x/.test(zoomType), zoomY = /y/.test(zoomType), inverted = chart.inverted; this.zoomX = zoomX; this.zoomY = zoomY; this.zoomHor = (zoomX && !inverted) || (zoomY && inverted); this.zoomVert = (zoomY && !inverted) || (zoomX && inverted); this.hasZoom = zoomX || zoomY; }, /** * Add crossbrowser support for chartX and chartY * @param {Object} e The event object in standard browsers */ normalize: function(e, chartPosition) { var chartX, chartY, ePos; // IE normalizing e = e || win.event; if (!e.target) { e.target = e.srcElement; } // iOS (#2757) ePos = e.touches ? (e.touches.length ? e.touches.item(0) : e.changedTouches[0]) : e; // Get mouse position if (!chartPosition) { this.chartPosition = chartPosition = offset(this.chart.container); } // chartX and chartY if (ePos.pageX === undefined) { // IE < 9. #886. chartX = Math.max(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is // for IE10 quirks mode within framesets chartY = e.y; } else { chartX = ePos.pageX - chartPosition.left; chartY = ePos.pageY - chartPosition.top; } return extend(e, { chartX: Math.round(chartX), chartY: Math.round(chartY) }); }, /** * Get the click position in terms of axis values. * * @param {Object} e A pointer event */ getCoordinates: function(e) { var coordinates = { xAxis: [], yAxis: [] }; each(this.chart.axes, function(axis) { coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({ axis: axis, value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY']) }); }); return coordinates; }, /** * With line type charts with a single tracker, get the point closest to the mouse. * Run Point.onMouseOver and display tooltip for the point or points. */ runPointActions: function(e) { var pointer = this, chart = pointer.chart, series = chart.series, tooltip = chart.tooltip, shared = tooltip ? tooltip.shared : false, followPointer, updatePosition = true, hoverPoint = chart.hoverPoint, hoverSeries = chart.hoverSeries, i, anchor, noSharedTooltip, stickToHoverSeries, directTouch, kdpoints = [], kdpointT; // For hovering over the empty parts of the plot area (hoverSeries is undefined). // If there is one series with point tracking (combo chart), don't go to nearest neighbour. if (!shared && !hoverSeries) { for (i = 0; i < series.length; i++) { if (series[i].directTouch || !series[i].options.stickyTracking) { series = []; } } } // If it has a hoverPoint and that series requires direct touch (like columns, #3899), or we're on // a noSharedTooltip series among shared tooltip series (#4546), use the hoverPoint . Otherwise, // search the k-d tree. stickToHoverSeries = hoverSeries && (shared ? hoverSeries.noSharedTooltip : hoverSeries.directTouch); if (stickToHoverSeries && hoverPoint) { kdpoints = [hoverPoint]; // Handle shared tooltip or cases where a series is not yet hovered } else { // When we have non-shared tooltip and sticky tracking is disabled, // search for the closest point only on hovered series: #5533, #5476 if (!shared && hoverSeries && !hoverSeries.options.stickyTracking) { series = [hoverSeries]; } // Find nearest points on all series each(series, function(s) { // Skip hidden series noSharedTooltip = s.noSharedTooltip && shared; directTouch = !shared && s.directTouch; if (s.visible && !noSharedTooltip && !directTouch && pick(s.options.enableMouseTracking, true)) { // #3821 kdpointT = s.searchPoint(e, !noSharedTooltip && s.kdDimensions === 1); // #3828 if (kdpointT && kdpointT.series) { // Point.series becomes null when reset and before redraw (#5197) kdpoints.push(kdpointT); } } }); // Sort kdpoints by distance to mouse pointer kdpoints.sort(function(p1, p2) { var isCloserX = p1.distX - p2.distX, isCloser = p1.dist - p2.dist, isAbove = p1.series.group.zIndex > p2.series.group.zIndex ? -1 : 1; // We have two points which are not in the same place on xAxis and shared tooltip: if (isCloserX !== 0 && shared) { // #5721 return isCloserX; } // Points are not exactly in the same place on x/yAxis: if (isCloser !== 0) { return isCloser; } // The same xAxis and yAxis position, sort by z-index: return isAbove; }); } // Remove points with different x-positions, required for shared tooltip and crosshairs (#4645): if (shared) { i = kdpoints.length; while (i--) { if (kdpoints[i].x !== kdpoints[0].x || kdpoints[i].series.noSharedTooltip) { kdpoints.splice(i, 1); } } } // Refresh tooltip for kdpoint if new hover point or tooltip was hidden // #3926, #4200 if (kdpoints[0] && (kdpoints[0] !== this.prevKDPoint || (tooltip && tooltip.isHidden))) { // Draw tooltip if necessary if (shared && !kdpoints[0].series.noSharedTooltip) { // Do mouseover on all points (#3919, #3985, #4410, #5622) for (i = 0; i < kdpoints.length; i++) { kdpoints[i].onMouseOver(e, kdpoints[i] !== ((hoverSeries && hoverSeries.directTouch && hoverPoint) || kdpoints[0])); } if (kdpoints.length && tooltip) { // Keep the order of series in tooltip: tooltip.refresh(kdpoints.sort(function(p1, p2) { return p1.series.index - p2.series.index; }), e); } } else { if (tooltip) { tooltip.refresh(kdpoints[0], e); } if (!hoverSeries || !hoverSeries.directTouch) { // #4448 kdpoints[0].onMouseOver(e); } } this.prevKDPoint = kdpoints[0]; updatePosition = false; } // Update positions (regardless of kdpoint or hoverPoint) if (updatePosition) { followPointer = hoverSeries && hoverSeries.tooltipOptions.followPointer; if (tooltip && followPointer && !tooltip.isHidden) { anchor = tooltip.getAnchor([{}], e); tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] }); } } // Start the event listener to pick up the tooltip and crosshairs if (!pointer._onDocumentMouseMove) { pointer._onDocumentMouseMove = function(e) { if (charts[H.hoverChartIndex]) { charts[H.hoverChartIndex].pointer.onDocumentMouseMove(e); } }; addEvent(doc, 'mousemove', pointer._onDocumentMouseMove); } // Crosshair. For each hover point, loop over axes and draw cross if that point // belongs to the axis (#4927). each(shared ? kdpoints : [pick(hoverPoint, kdpoints[0])], function drawPointCrosshair(point) { // #5269 each(chart.axes, function drawAxisCrosshair(axis) { // In case of snap = false, point is undefined, and we draw the crosshair anyway (#5066) if (!point || point.series && point.series[axis.coll] === axis) { // #5658 axis.drawCrosshair(e, point); } }); }); }, /** * Reset the tracking by hiding the tooltip, the hover series state and the hover point * * @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible */ reset: function(allowMove, delay) { var pointer = this, chart = pointer.chart, hoverSeries = chart.hoverSeries, hoverPoint = chart.hoverPoint, hoverPoints = chart.hoverPoints, tooltip = chart.tooltip, tooltipPoints = tooltip && tooltip.shared ? hoverPoints : hoverPoint; // Check if the points have moved outside the plot area (#1003, #4736, #5101) if (allowMove && tooltipPoints) { each(splat(tooltipPoints), function(point) { if (point.series.isCartesian && point.plotX === undefined) { allowMove = false; } }); } // Just move the tooltip, #349 if (allowMove) { if (tooltip && tooltipPoints) { tooltip.refresh(tooltipPoints); if (hoverPoint) { // #2500 hoverPoint.setState(hoverPoint.state, true); each(chart.axes, function(axis) { if (axis.crosshair) { axis.drawCrosshair(null, hoverPoint); } }); } } // Full reset } else { if (hoverPoint) { hoverPoint.onMouseOut(); } if (hoverPoints) { each(hoverPoints, function(point) { point.setState(); }); } if (hoverSeries) { hoverSeries.onMouseOut(); } if (tooltip) { tooltip.hide(delay); } if (pointer._onDocumentMouseMove) { removeEvent(doc, 'mousemove', pointer._onDocumentMouseMove); pointer._onDocumentMouseMove = null; } // Remove crosshairs each(chart.axes, function(axis) { axis.hideCrosshair(); }); pointer.hoverX = pointer.prevKDPoint = chart.hoverPoints = chart.hoverPoint = null; } }, /** * Scale series groups to a certain scale and translation */ scaleGroups: function(attribs, clip) { var chart = this.chart, seriesAttribs; // Scale each series each(chart.series, function(series) { seriesAttribs = attribs || series.getPlotBox(); // #1701 if (series.xAxis && series.xAxis.zoomEnabled && series.group) { series.group.attr(seriesAttribs); if (series.markerGroup) { series.markerGroup.attr(seriesAttribs); series.markerGroup.clip(clip ? chart.clipRect : null); } if (series.dataLabelsGroup) { series.dataLabelsGroup.attr(seriesAttribs); } } }); // Clip chart.clipRect.attr(clip || chart.clipBox); }, /** * Start a drag operation */ dragStart: function(e) { var chart = this.chart; // Record the start position chart.mouseIsDown = e.type; chart.cancelClick = false; chart.mouseDownX = this.mouseDownX = e.chartX; chart.mouseDownY = this.mouseDownY = e.chartY; }, /** * Perform a drag operation in response to a mousemove event while the mouse is down */ drag: function(e) { var chart = this.chart, chartOptions = chart.options.chart, chartX = e.chartX, chartY = e.chartY, zoomHor = this.zoomHor, zoomVert = this.zoomVert, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, clickedInside, size, selectionMarker = this.selectionMarker, mouseDownX = this.mouseDownX, mouseDownY = this.mouseDownY, panKey = chartOptions.panKey && e[chartOptions.panKey + 'Key']; // If the device supports both touch and mouse (like IE11), and we are touch-dragging // inside the plot area, don't handle the mouse event. #4339. if (selectionMarker && selectionMarker.touch) { return; } // If the mouse is outside the plot area, adjust to cooordinates // inside to prevent the selection marker from going outside if (chartX < plotLeft) { chartX = plotLeft; } else if (chartX > plotLeft + plotWidth) { chartX = plotLeft + plotWidth; } if (chartY < plotTop) { chartY = plotTop; } else if (chartY > plotTop + plotHeight) { chartY = plotTop + plotHeight; } // determine if the mouse has moved more than 10px this.hasDragged = Math.sqrt( Math.pow(mouseDownX - chartX, 2) + Math.pow(mouseDownY - chartY, 2) ); if (this.hasDragged > 10) { clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop); // make a selection if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside && !panKey) { if (!selectionMarker) { this.selectionMarker = selectionMarker = chart.renderer.rect( plotLeft, plotTop, zoomHor ? 1 : plotWidth, zoomVert ? 1 : plotHeight, 0 ) .attr({ 'class': 'highcharts-selection-marker', 'zIndex': 7 }) .add(); } } // adjust the width of the selection marker if (selectionMarker && zoomHor) { size = chartX - mouseDownX; selectionMarker.attr({ width: Math.abs(size), x: (size > 0 ? 0 : size) + mouseDownX }); } // adjust the height of the selection marker if (selectionMarker && zoomVert) { size = chartY - mouseDownY; selectionMarker.attr({ height: Math.abs(size), y: (size > 0 ? 0 : size) + mouseDownY }); } // panning if (clickedInside && !selectionMarker && chartOptions.panning) { chart.pan(e, chartOptions.panning); } } }, /** * On mouse up or touch end across the entire document, drop the selection. */ drop: function(e) { var pointer = this, chart = this.chart, hasPinched = this.hasPinched; if (this.selectionMarker) { var selectionData = { originalEvent: e, // #4890 xAxis: [], yAxis: [] }, selectionBox = this.selectionMarker, selectionLeft = selectionBox.attr ? selectionBox.attr('x') : selectionBox.x, selectionTop = selectionBox.attr ? selectionBox.attr('y') : selectionBox.y, selectionWidth = selectionBox.attr ? selectionBox.attr('width') : selectionBox.width, selectionHeight = selectionBox.attr ? selectionBox.attr('height') : selectionBox.height, runZoom; // a selection has been made if (this.hasDragged || hasPinched) { // record each axis' min and max each(chart.axes, function(axis) { if (axis.zoomEnabled && defined(axis.min) && (hasPinched || pointer[{ xAxis: 'zoomX', yAxis: 'zoomY' }[axis.coll]])) { // #859, #3569 var horiz = axis.horiz, minPixelPadding = e.type === 'touchend' ? axis.minPixelPadding : 0, // #1207, #3075 selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop) + minPixelPadding), selectionMax = axis.toValue((horiz ? selectionLeft + selectionWidth : selectionTop + selectionHeight) - minPixelPadding); selectionData[axis.coll].push({ axis: axis, min: Math.min(selectionMin, selectionMax), // for reversed axes max: Math.max(selectionMin, selectionMax) }); runZoom = true; } }); if (runZoom) { fireEvent(chart, 'selection', selectionData, function(args) { chart.zoom(extend(args, hasPinched ? { animation: false } : null)); }); } } this.selectionMarker = this.selectionMarker.destroy(); // Reset scaling preview if (hasPinched) { this.scaleGroups(); } } // Reset all if (chart) { // it may be destroyed on mouse up - #877 css(chart.container, { cursor: chart._cursor }); chart.cancelClick = this.hasDragged > 10; // #370 chart.mouseIsDown = this.hasDragged = this.hasPinched = false; this.pinchDown = []; } }, onContainerMouseDown: function(e) { e = this.normalize(e); this.zoomOption(); // issue #295, dragging not always working in Firefox if (e.preventDefault) { e.preventDefault(); } this.dragStart(e); }, onDocumentMouseUp: function(e) { if (charts[H.hoverChartIndex]) { charts[H.hoverChartIndex].pointer.drop(e); } }, /** * Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea. * Issue #149 workaround. The mouseleave event does not always fire. */ onDocumentMouseMove: function(e) { var chart = this.chart, chartPosition = this.chartPosition; e = this.normalize(e, chartPosition); // If we're outside, hide the tooltip if (chartPosition && !this.inClass(e.target, 'highcharts-tracker') && !chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { this.reset(); } }, /** * When mouse leaves the container, hide the tooltip. */ onContainerMouseLeave: function(e) { var chart = charts[H.hoverChartIndex]; if (chart && (e.relatedTarget || e.toElement)) { // #4886, MS Touch end fires mouseleave but with no related target chart.pointer.reset(); chart.pointer.chartPosition = null; // also reset the chart position, used in #149 fix } }, // The mousemove, touchmove and touchstart event handler onContainerMouseMove: function(e) { var chart = this.chart; if (!defined(H.hoverChartIndex) || !charts[H.hoverChartIndex] || !charts[H.hoverChartIndex].mouseIsDown) { H.hoverChartIndex = chart.index; } e = this.normalize(e); e.returnValue = false; // #2251, #3224 if (chart.mouseIsDown === 'mousedown') { this.drag(e); } // Show the tooltip and run mouse over events (#977) if ((this.inClass(e.target, 'highcharts-tracker') || chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) { this.runPointActions(e); } }, /** * Utility to detect whether an element has, or has a parent with, a specific * class name. Used on detection of tracker objects and on deciding whether * hovering the tooltip should cause the active series to mouse out. */ inClass: function(element, className) { var elemClassName; while (element) { elemClassName = attr(element, 'class'); if (elemClassName) { if (elemClassName.indexOf(className) !== -1) { return true; } if (elemClassName.indexOf('highcharts-container') !== -1) { return false; } } element = element.parentNode; } }, onTrackerMouseOut: function(e) { var series = this.chart.hoverSeries, relatedTarget = e.relatedTarget || e.toElement; if (series && relatedTarget && !series.options.stickyTracking && !this.inClass(relatedTarget, 'highcharts-tooltip') && (!this.inClass(relatedTarget, 'highcharts-series-' + series.index) || // #2499, #4465 !this.inClass(relatedTarget, 'highcharts-tracker') // #5553 ) ) { series.onMouseOut(); } }, onContainerClick: function(e) { var chart = this.chart, hoverPoint = chart.hoverPoint, plotLeft = chart.plotLeft, plotTop = chart.plotTop; e = this.normalize(e); if (!chart.cancelClick) { // On tracker click, fire the series and point events. #783, #1583 if (hoverPoint && this.inClass(e.target, 'highcharts-tracker')) { // the series click event fireEvent(hoverPoint.series, 'click', extend(e, { point: hoverPoint })); // the point click event if (chart.hoverPoint) { // it may be destroyed (#1844) hoverPoint.firePointEvent('click', e); } // When clicking outside a tracker, fire a chart event } else { extend(e, this.getCoordinates(e)); // fire a click event in the chart if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) { fireEvent(chart, 'click', e); } } } }, /** * Set the JS DOM events on the container and document. This method should contain * a one-to-one assignment between methods and their handlers. Any advanced logic should * be moved to the handler reflecting the event's name. */ setDOMEvents: function() { var pointer = this, container = pointer.chart.container; container.onmousedown = function(e) { pointer.onContainerMouseDown(e); }; container.onmousemove = function(e) { pointer.onContainerMouseMove(e); }; container.onclick = function(e) { pointer.onContainerClick(e); }; addEvent(container, 'mouseleave', pointer.onContainerMouseLeave); if (H.chartCount === 1) { addEvent(doc, 'mouseup', pointer.onDocumentMouseUp); } if (H.hasTouch) { container.ontouchstart = function(e) { pointer.onContainerTouchStart(e); }; container.ontouchmove = function(e) { pointer.onContainerTouchMove(e); }; if (H.chartCount === 1) { addEvent(doc, 'touchend', pointer.onDocumentTouchEnd); } } }, /** * Destroys the Pointer object and disconnects DOM events. */ destroy: function() { var prop; removeEvent(this.chart.container, 'mouseleave', this.onContainerMouseLeave); if (!H.chartCount) { removeEvent(doc, 'mouseup', this.onDocumentMouseUp); removeEvent(doc, 'touchend', this.onDocumentTouchEnd); } // memory and CPU leak clearInterval(this.tooltipTimeout); for (prop in this) { this[prop] = null; } } }; }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var charts = H.charts, each = H.each, extend = H.extend, map = H.map, noop = H.noop, pick = H.pick, Pointer = H.Pointer; /* Support for touch devices */ extend(Pointer.prototype, { /** * Run translation operations */ pinchTranslate: function(pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) { if (this.zoomHor || this.pinchHor) { this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } if (this.zoomVert || this.pinchVert) { this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } }, /** * Run translation operations for each direction (horizontal and vertical) independently */ pinchTranslateDirection: function(horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, forcedScale) { var chart = this.chart, xy = horiz ? 'x' : 'y', XY = horiz ? 'X' : 'Y', sChartXY = 'chart' + XY, wh = horiz ? 'width' : 'height', plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')], selectionWH, selectionXY, clipXY, scale = forcedScale || 1, inverted = chart.inverted, bounds = chart.bounds[horiz ? 'h' : 'v'], singleTouch = pinchDown.length === 1, touch0Start = pinchDown[0][sChartXY], touch0Now = touches[0][sChartXY], touch1Start = !singleTouch && pinchDown[1][sChartXY], touch1Now = !singleTouch && touches[1][sChartXY], outOfBounds, transformScale, scaleKey, setScale = function() { // Don't zoom if fingers are too close on this axis if (!singleTouch && Math.abs(touch0Start - touch1Start) > 20) { scale = forcedScale || Math.abs(touch0Now - touch1Now) / Math.abs(touch0Start - touch1Start); } clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start; selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale; }; // Set the scale, first pass setScale(); selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not // Out of bounds if (selectionXY < bounds.min) { selectionXY = bounds.min; outOfBounds = true; } else if (selectionXY + selectionWH > bounds.max) { selectionXY = bounds.max - selectionWH; outOfBounds = true; } // Is the chart dragged off its bounds, determined by dataMin and dataMax? if (outOfBounds) { // Modify the touchNow position in order to create an elastic drag movement. This indicates // to the user that the chart is responsive but can't be dragged further. touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]); if (!singleTouch) { touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]); } // Set the scale, second pass to adapt to the modified touchNow positions setScale(); } else { lastValidTouch[xy] = [touch0Now, touch1Now]; } // Set geometry for clipping, selection and transformation if (!inverted) { clip[xy] = clipXY - plotLeftTop; clip[wh] = selectionWH; } scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY; transformScale = inverted ? 1 / scale : scale; selectionMarker[wh] = selectionWH; selectionMarker[xy] = selectionXY; transform[scaleKey] = scale; transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start)); }, /** * Handle touch events with two touches */ pinch: function(e) { var self = this, chart = self.chart, pinchDown = self.pinchDown, touches = e.touches, touchesLength = touches.length, lastValidTouch = self.lastValidTouch, hasZoom = self.hasZoom, selectionMarker = self.selectionMarker, transform = {}, fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, 'highcharts-tracker') && chart.runTrackerClick) || self.runChartClick), clip = {}; // Don't initiate panning until the user has pinched. This prevents us from // blocking page scrolling as users scroll down a long page (#4210). if (touchesLength > 1) { self.initiated = true; } // On touch devices, only proceed to trigger click if a handler is defined if (hasZoom && self.initiated && !fireClickEvent) { e.preventDefault(); } // Normalize each touch map(touches, function(e) { return self.normalize(e); }); // Register the touch start position if (e.type === 'touchstart') { each(touches, function(e, i) { pinchDown[i] = { chartX: e.chartX, chartY: e.chartY }; }); lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX]; lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY]; // Identify the data bounds in pixels each(chart.axes, function(axis) { if (axis.zoomEnabled) { var bounds = chart.bounds[axis.horiz ? 'h' : 'v'], minPixelPadding = axis.minPixelPadding, min = axis.toPixels(pick(axis.options.min, axis.dataMin)), max = axis.toPixels(pick(axis.options.max, axis.dataMax)), absMin = Math.min(min, max), absMax = Math.max(min, max); // Store the bounds for use in the touchmove handler bounds.min = Math.min(axis.pos, absMin - minPixelPadding); bounds.max = Math.max(axis.pos + axis.len, absMax + minPixelPadding); } }); self.res = true; // reset on next move // Event type is touchmove, handle panning and pinching } else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first // Set the marker if (!selectionMarker) { self.selectionMarker = selectionMarker = extend({ destroy: noop, touch: true }, chart.plotBox); } self.pinchTranslate(pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); self.hasPinched = hasZoom; // Scale and translate the groups to provide visual feedback during pinching self.scaleGroups(transform, clip); // Optionally move the tooltip on touchmove if (!hasZoom && self.followTouchMove && touchesLength === 1) { this.runPointActions(self.normalize(e)); } else if (self.res) { self.res = false; this.reset(false, 0); } } }, /** * General touch handler shared by touchstart and touchmove. */ touch: function(e, start) { var chart = this.chart, hasMoved, pinchDown; H.hoverChartIndex = chart.index; if (e.touches.length === 1) { e = this.normalize(e); if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop) && !chart.openMenu) { // Run mouse events and display tooltip etc if (start) { this.runPointActions(e); } // Android fires touchmove events after the touchstart even if the // finger hasn't moved, or moved only a pixel or two. In iOS however, // the touchmove doesn't fire unless the finger moves more than ~4px. // So we emulate this behaviour in Android by checking how much it // moved, and cancelling on small distances. #3450. if (e.type === 'touchmove') { pinchDown = this.pinchDown; hasMoved = pinchDown[0] ? Math.sqrt( // #5266 Math.pow(pinchDown[0].chartX - e.chartX, 2) + Math.pow(pinchDown[0].chartY - e.chartY, 2) ) >= 4 : false; } if (pick(hasMoved, true)) { this.pinch(e); } } else if (start) { // Hide the tooltip on touching outside the plot area (#1203) this.reset(); } } else if (e.touches.length === 2) { this.pinch(e); } }, onContainerTouchStart: function(e) { this.zoomOption(); this.touch(e, true); }, onContainerTouchMove: function(e) { this.touch(e); }, onDocumentTouchEnd: function(e) { if (charts[H.hoverChartIndex]) { charts[H.hoverChartIndex].pointer.drop(e); } } }); }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var addEvent = H.addEvent, charts = H.charts, css = H.css, doc = H.doc, extend = H.extend, noop = H.noop, Pointer = H.Pointer, removeEvent = H.removeEvent, win = H.win, wrap = H.wrap; if (win.PointerEvent || win.MSPointerEvent) { // The touches object keeps track of the points being touched at all times var touches = {}, hasPointerEvent = !!win.PointerEvent, getWebkitTouches = function() { var key, fake = []; fake.item = function(i) { return this[i]; }; for (key in touches) { if (touches.hasOwnProperty(key)) { fake.push({ pageX: touches[key].pageX, pageY: touches[key].pageY, target: touches[key].target }); } } return fake; }, translateMSPointer = function(e, method, wktype, func) { var p; if ((e.pointerType === 'touch' || e.pointerType === e.MSPOINTER_TYPE_TOUCH) && charts[H.hoverChartIndex]) { func(e); p = charts[H.hoverChartIndex].pointer; p[method]({ type: wktype, target: e.currentTarget, preventDefault: noop, touches: getWebkitTouches() }); } }; /** * Extend the Pointer prototype with methods for each event handler and more */ extend(Pointer.prototype, { onContainerPointerDown: function(e) { translateMSPointer(e, 'onContainerTouchStart', 'touchstart', function(e) { touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY, target: e.currentTarget }; }); }, onContainerPointerMove: function(e) { translateMSPointer(e, 'onContainerTouchMove', 'touchmove', function(e) { touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY }; if (!touches[e.pointerId].target) { touches[e.pointerId].target = e.currentTarget; } }); }, onDocumentPointerUp: function(e) { translateMSPointer(e, 'onDocumentTouchEnd', 'touchend', function(e) { delete touches[e.pointerId]; }); }, /** * Add or remove the MS Pointer specific events */ batchMSEvents: function(fn) { fn(this.chart.container, hasPointerEvent ? 'pointerdown' : 'MSPointerDown', this.onContainerPointerDown); fn(this.chart.container, hasPointerEvent ? 'pointermove' : 'MSPointerMove', this.onContainerPointerMove); fn(doc, hasPointerEvent ? 'pointerup' : 'MSPointerUp', this.onDocumentPointerUp); } }); // Disable default IE actions for pinch and such on chart element wrap(Pointer.prototype, 'init', function(proceed, chart, options) { proceed.call(this, chart, options); if (this.hasZoom) { // #4014 css(chart.container, { '-ms-touch-action': 'none', 'touch-action': 'none' }); } }); // Add IE specific touch events to chart wrap(Pointer.prototype, 'setDOMEvents', function(proceed) { proceed.apply(this); if (this.hasZoom || this.followTouchMove) { this.batchMSEvents(addEvent); } }); // Destroy MS events also wrap(Pointer.prototype, 'destroy', function(proceed) { this.batchMSEvents(removeEvent); proceed.call(this); }); } }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var Legend, addEvent = H.addEvent, css = H.css, discardElement = H.discardElement, defined = H.defined, each = H.each, extend = H.extend, isFirefox = H.isFirefox, marginNames = H.marginNames, merge = H.merge, pick = H.pick, setAnimation = H.setAnimation, stableSort = H.stableSort, win = H.win, wrap = H.wrap; /** * The overview of the chart's series */ Legend = H.Legend = function(chart, options) { this.init(chart, options); }; Legend.prototype = { /** * Initialize the legend */ init: function(chart, options) { this.chart = chart; this.setOptions(options); if (options.enabled) { // Render it this.render(); // move checkboxes addEvent(this.chart, 'endResize', function() { this.legend.positionCheckboxes(); }); } }, setOptions: function(options) { var padding = pick(options.padding, 8); this.options = options; this.itemMarginTop = options.itemMarginTop || 0; this.padding = padding; this.initialItemX = padding; this.initialItemY = padding - 5; // 5 is the number of pixels above the text this.maxItemWidth = 0; this.itemHeight = 0; this.symbolWidth = pick(options.symbolWidth, 16); this.pages = []; }, /** * Update the legend with new options. Equivalent to running chart.update with a legend * configuration option. * @param {Object} options Legend options * @param {Boolean} redraw Whether to redraw the chart, defaults to true. */ update: function(options, redraw) { var chart = this.chart; this.setOptions(merge(true, this.options, options)); this.destroy(); chart.isDirtyLegend = chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Set the colors for the legend item * @param {Object} item A Series or Point instance * @param {Object} visible Dimmed or colored */ colorizeItem: function(item, visible) { item.legendGroup[visible ? 'removeClass' : 'addClass']('highcharts-legend-item-hidden'); }, /** * Position the legend item * @param {Object} item A Series or Point instance */ positionItem: function(item) { var legend = this, options = legend.options, symbolPadding = options.symbolPadding, ltr = !options.rtl, legendItemPos = item._legendItemPos, itemX = legendItemPos[0], itemY = legendItemPos[1], checkbox = item.checkbox, legendGroup = item.legendGroup; if (legendGroup && legendGroup.element) { legendGroup.translate( ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4, itemY ); } if (checkbox) { checkbox.x = itemX; checkbox.y = itemY; } }, /** * Destroy a single legend item * @param {Object} item The series or point */ destroyItem: function(item) { var checkbox = item.checkbox; // destroy SVG elements each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function(key) { if (item[key]) { item[key] = item[key].destroy(); } }); if (checkbox) { discardElement(item.checkbox); } }, /** * Destroys the legend. */ destroy: function() { var legend = this, legendGroup = legend.group, box = legend.box; if (box) { legend.box = box.destroy(); } // Destroy items each(this.getAllItems(), function(item) { each(['legendItem', 'legendGroup'], function(key) { if (item[key]) { item[key] = item[key].destroy(); } }); }); if (legendGroup) { legend.group = legendGroup.destroy(); } }, /** * Position the checkboxes after the width is determined */ positionCheckboxes: function(scrollOffset) { var alignAttr = this.group.alignAttr, translateY, clipHeight = this.clipHeight || this.legendHeight, titleHeight = this.titleHeight; if (alignAttr) { translateY = alignAttr.translateY; each(this.allItems, function(item) { var checkbox = item.checkbox, top; if (checkbox) { top = translateY + titleHeight + checkbox.y + (scrollOffset || 0) + 3; css(checkbox, { left: (alignAttr.translateX + item.checkboxOffset + checkbox.x - 20) + 'px', top: top + 'px', display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : 'none' }); } }); } }, /** * Render the legend title on top of the legend */ renderTitle: function() { var options = this.options, padding = this.padding, titleOptions = options.title, titleHeight = 0, bBox; if (titleOptions.text) { if (!this.title) { this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title') .attr({ zIndex: 1 }) .add(this.group); } bBox = this.title.getBBox(); titleHeight = bBox.height; this.offsetWidth = bBox.width; // #1717 this.contentGroup.attr({ translateY: titleHeight }); } this.titleHeight = titleHeight; }, /** * Set the legend item text */ setText: function(item) { var options = this.options; item.legendItem.attr({ text: options.labelFormat ? H.format(options.labelFormat, item) : options.labelFormatter.call(item) }); }, /** * Render a single specific legend item * @param {Object} item A series or point */ renderItem: function(item) { var legend = this, chart = legend.chart, renderer = chart.renderer, options = legend.options, horizontal = options.layout === 'horizontal', symbolWidth = legend.symbolWidth, symbolPadding = options.symbolPadding, padding = legend.padding, itemDistance = horizontal ? pick(options.itemDistance, 20) : 0, ltr = !options.rtl, itemHeight, widthOption = options.width, itemMarginBottom = options.itemMarginBottom || 0, itemMarginTop = legend.itemMarginTop, initialItemX = legend.initialItemX, bBox, itemWidth, li = item.legendItem, isSeries = !item.series, series = !isSeries && item.series.drawLegendSymbol ? item.series : item, seriesOptions = series.options, showCheckbox = legend.createCheckboxForItem && seriesOptions && seriesOptions.showCheckbox, useHTML = options.useHTML, fontSize = 12; if (!li) { // generate it once, later move it // Generate the group box // A group to hold the symbol and text. Text is to be appended in Legend class. item.legendGroup = renderer.g('legend-item') .addClass('highcharts-' + series.type + '-series highcharts-color-' + item.colorIndex + ' ' + (item.options.className || '') + (isSeries ? 'highcharts-series-' + item.index : '') ) .attr({ zIndex: 1 }) .add(legend.scrollGroup); // Generate the list item text and add it to the group item.legendItem = li = renderer.text( '', ltr ? symbolWidth + symbolPadding : -symbolPadding, legend.baseline || 0, useHTML ) .attr({ align: ltr ? 'left' : 'right', zIndex: 2 }) .add(item.legendGroup); // Get the baseline for the first item - the font size is equal for all if (!legend.baseline) { legend.fontMetrics = renderer.fontMetrics( fontSize, li ); legend.baseline = legend.fontMetrics.f + 3 + itemMarginTop; li.attr('y', legend.baseline); } // Draw the legend symbol inside the group box series.drawLegendSymbol(legend, item); if (legend.setItemEvents) { legend.setItemEvents(item, li, useHTML); } // add the HTML checkbox on top if (showCheckbox) { legend.createCheckboxForItem(item); } } // Colorize the items legend.colorizeItem(item, item.visible); // Always update the text legend.setText(item); // calculate the positions for the next line bBox = li.getBBox(); itemWidth = item.checkboxOffset = options.itemWidth || item.legendItemWidth || symbolWidth + symbolPadding + bBox.width + itemDistance + (showCheckbox ? 20 : 0); legend.itemHeight = itemHeight = Math.round(item.legendItemHeight || bBox.height); // if the item exceeds the width, start a new line if (horizontal && legend.itemX - initialItemX + itemWidth > (widthOption || (chart.chartWidth - 2 * padding - initialItemX - options.x))) { legend.itemX = initialItemX; legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom; legend.lastLineHeight = 0; // reset for next line (#915, #3976) } // If the item exceeds the height, start a new column /*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) { legend.itemY = legend.initialItemY; legend.itemX += legend.maxItemWidth; legend.maxItemWidth = 0; }*/ // Set the edge positions legend.maxItemWidth = Math.max(legend.maxItemWidth, itemWidth); legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom; legend.lastLineHeight = Math.max(itemHeight, legend.lastLineHeight); // #915 // cache the position of the newly generated or reordered items item._legendItemPos = [legend.itemX, legend.itemY]; // advance if (horizontal) { legend.itemX += itemWidth; } else { legend.itemY += itemMarginTop + itemHeight + itemMarginBottom; legend.lastLineHeight = itemHeight; } // the width of the widest item legend.offsetWidth = widthOption || Math.max( (horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding, legend.offsetWidth ); }, /** * Get all items, which is one item per series for normal series and one item per point * for pie series. */ getAllItems: function() { var allItems = []; each(this.chart.series, function(series) { var seriesOptions = series && series.options; // Handle showInLegend. If the series is linked to another series, defaults to false. if (series && pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? undefined : false, true)) { // Use points or series for the legend item depending on legendType allItems = allItems.concat( series.legendItems || (seriesOptions.legendType === 'point' ? series.data : series) ); } }); return allItems; }, /** * Adjust the chart margins by reserving space for the legend on only one side * of the chart. If the position is set to a corner, top or bottom is reserved * for horizontal legends and left or right for vertical ones. */ adjustMargins: function(margin, spacing) { var chart = this.chart, options = this.options, // Use the first letter of each alignment option in order to detect the side alignment = options.align.charAt(0) + options.verticalAlign.charAt(0) + options.layout.charAt(0); // #4189 - use charAt(x) notation instead of [x] for IE7 if (!options.floating) { each([ /(lth|ct|rth)/, /(rtv|rm|rbv)/, /(rbh|cb|lbh)/, /(lbv|lm|ltv)/ ], function(alignments, side) { if (alignments.test(alignment) && !defined(margin[side])) { // Now we have detected on which side of the chart we should reserve space for the legend chart[marginNames[side]] = Math.max( chart[marginNames[side]], chart.legend[(side + 1) % 2 ? 'legendHeight' : 'legendWidth'] + [1, -1, -1, 1][side] * options[(side % 2) ? 'x' : 'y'] + pick(options.margin, 12) + spacing[side] ); } }); } }, /** * Render the legend. This method can be called both before and after * chart.render. If called after, it will only rearrange items instead * of creating new ones. */ render: function() { var legend = this, chart = legend.chart, renderer = chart.renderer, legendGroup = legend.group, allItems, display, legendWidth, legendHeight, box = legend.box, options = legend.options, padding = legend.padding; legend.itemX = legend.initialItemX; legend.itemY = legend.initialItemY; legend.offsetWidth = 0; legend.lastItemY = 0; if (!legendGroup) { legend.group = legendGroup = renderer.g('legend') .attr({ zIndex: 7 }) .add(); legend.contentGroup = renderer.g() .attr({ zIndex: 1 }) // above background .add(legendGroup); legend.scrollGroup = renderer.g() .add(legend.contentGroup); } legend.renderTitle(); // add each series or point allItems = legend.getAllItems(); // sort by legendIndex stableSort(allItems, function(a, b) { return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0); }); // reversed legend if (options.reversed) { allItems.reverse(); } legend.allItems = allItems; legend.display = display = !!allItems.length; // render the items legend.lastLineHeight = 0; each(allItems, function(item) { legend.renderItem(item); }); // Get the box legendWidth = (options.width || legend.offsetWidth) + padding; legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight; legendHeight = legend.handleOverflow(legendHeight); legendHeight += padding; // Draw the border and/or background if (!box) { legend.box = box = renderer.rect() .addClass('highcharts-legend-box') .attr({ r: options.borderRadius }) .add(legendGroup); box.isNew = true; } if (legendWidth > 0 && legendHeight > 0) { box[box.isNew ? 'attr' : 'animate']( box.crisp({ x: 0, y: 0, width: legendWidth, height: legendHeight }, box.strokeWidth()) ); box.isNew = false; } // hide the border if no items box[display ? 'show' : 'hide'](); // Open for responsiveness if (legendGroup.getStyle('display') === 'none') { legendWidth = legendHeight = 0; } legend.legendWidth = legendWidth; legend.legendHeight = legendHeight; // Now that the legend width and height are established, put the items in the // final position each(allItems, function(item) { legend.positionItem(item); }); // 1.x compatibility: positioning based on style /*var props = ['left', 'right', 'top', 'bottom'], prop, i = 4; while (i--) { prop = props[i]; if (options.style[prop] && options.style[prop] !== 'auto') { options[i < 2 ? 'align' : 'verticalAlign'] = prop; options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1); } }*/ if (display) { legendGroup.align(extend({ width: legendWidth, height: legendHeight }, options), true, 'spacingBox'); } if (!chart.isResizing) { this.positionCheckboxes(); } }, /** * Set up the overflow handling by adding navigation with up and down arrows below the * legend. */ handleOverflow: function(legendHeight) { var legend = this, chart = this.chart, renderer = chart.renderer, options = this.options, optionsY = options.y, alignTop = options.verticalAlign === 'top', spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding, maxHeight = options.maxHeight, clipHeight, clipRect = this.clipRect, navOptions = options.navigation, animation = pick(navOptions.animation, true), arrowSize = navOptions.arrowSize || 12, nav = this.nav, pages = this.pages, padding = this.padding, lastY, allItems = this.allItems, clipToHeight = function(height) { clipRect.attr({ height: height }); // useHTML if (legend.contentGroup.div) { legend.contentGroup.div.style.clip = 'rect(' + padding + 'px,9999px,' + (padding + height) + 'px,0)'; } }; // Adjust the height if (options.layout === 'horizontal') { spaceHeight /= 2; } if (maxHeight) { spaceHeight = Math.min(spaceHeight, maxHeight); } // Reset the legend height and adjust the clipping rectangle pages.length = 0; if (legendHeight > spaceHeight && navOptions.enabled !== false) { this.clipHeight = clipHeight = Math.max(spaceHeight - 20 - this.titleHeight - padding, 0); this.currentPage = pick(this.currentPage, 1); this.fullHeight = legendHeight; // Fill pages with Y positions so that the top of each a legend item defines // the scroll top for each page (#2098) each(allItems, function(item, i) { var y = item._legendItemPos[1], h = Math.round(item.legendItem.getBBox().height), len = pages.length; if (!len || (y - pages[len - 1] > clipHeight && (lastY || y) !== pages[len - 1])) { pages.push(lastY || y); len++; } if (i === allItems.length - 1 && y + h - pages[len - 1] > clipHeight) { pages.push(y); } if (y !== lastY) { lastY = y; } }); // Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787) if (!clipRect) { clipRect = legend.clipRect = renderer.clipRect(0, padding, 9999, 0); legend.contentGroup.clip(clipRect); } clipToHeight(clipHeight); // Add navigation elements if (!nav) { this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group); this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize) .on('click', function() { legend.scroll(-1, animation); }) .add(nav); this.pager = renderer.text('', 15, 10) .addClass('highcharts-legend-navigation') .add(nav); this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize) .on('click', function() { legend.scroll(1, animation); }) .add(nav); } // Set initial position legend.scroll(0); legendHeight = spaceHeight; } else if (nav) { clipToHeight(chart.chartHeight); nav.hide(); this.scrollGroup.attr({ translateY: 1 }); this.clipHeight = 0; // #1379 } return legendHeight; }, /** * Scroll the legend by a number of pages * @param {Object} scrollBy * @param {Object} animation */ scroll: function(scrollBy, animation) { var pages = this.pages, pageCount = pages.length, currentPage = this.currentPage + scrollBy, clipHeight = this.clipHeight, navOptions = this.options.navigation, pager = this.pager, padding = this.padding, scrollOffset; // When resizing while looking at the last page if (currentPage > pageCount) { currentPage = pageCount; } if (currentPage > 0) { if (animation !== undefined) { setAnimation(animation, this.chart); } this.nav.attr({ translateX: padding, translateY: clipHeight + this.padding + 7 + this.titleHeight, visibility: 'visible' }); this.up.attr({ 'class': currentPage === 1 ? 'highcharts-legend-nav-inactive' : 'highcharts-legend-nav-active' }); pager.attr({ text: currentPage + '/' + pageCount }); this.down.attr({ 'x': 18 + this.pager.getBBox().width, // adjust to text width 'class': currentPage === pageCount ? 'highcharts-legend-nav-inactive' : 'highcharts-legend-nav-active' }); scrollOffset = -pages[currentPage - 1] + this.initialItemY; this.scrollGroup.animate({ translateY: scrollOffset }); this.currentPage = currentPage; this.positionCheckboxes(scrollOffset); } } }; /* * LegendSymbolMixin */ H.LegendSymbolMixin = { /** * Get the series' symbol in the legend * * @param {Object} legend The legend object * @param {Object} item The series (this) or point */ drawRectangle: function(legend, item) { var options = legend.options, symbolHeight = options.symbolHeight || legend.fontMetrics.f, square = options.squareSymbol, symbolWidth = square ? symbolHeight : legend.symbolWidth; item.legendSymbol = this.chart.renderer.rect( square ? (legend.symbolWidth - symbolHeight) / 2 : 0, legend.baseline - symbolHeight + 1, // #3988 symbolWidth, symbolHeight, pick(legend.options.symbolRadius, symbolHeight / 2) ) .addClass('highcharts-point') .attr({ zIndex: 3 }).add(item.legendGroup); }, /** * Get the series' symbol in the legend. This method should be overridable to create custom * symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols. * * @param {Object} legend The legend object */ drawLineMarker: function(legend) { var options = this.options, markerOptions = options.marker, radius, legendSymbol, symbolWidth = legend.symbolWidth, renderer = this.chart.renderer, legendItemGroup = this.legendGroup, verticalCenter = legend.baseline - Math.round(legend.fontMetrics.b * 0.3), attr = {}; // Draw the line this.legendLine = renderer.path([ 'M', 0, verticalCenter, 'L', symbolWidth, verticalCenter ]) .addClass('highcharts-graph') .attr(attr) .add(legendItemGroup); // Draw the marker if (markerOptions && markerOptions.enabled !== false) { radius = this.symbol.indexOf('url') === 0 ? 0 : markerOptions.radius; this.legendSymbol = legendSymbol = renderer.symbol( this.symbol, (symbolWidth / 2) - radius, verticalCenter - radius, 2 * radius, 2 * radius, markerOptions ) .addClass('highcharts-point') .add(legendItemGroup); legendSymbol.isMarker = true; } } }; // Workaround for #2030, horizontal legend items not displaying in IE11 Preview, // and for #2580, a similar drawing flaw in Firefox 26. // Explore if there's a general cause for this. The problem may be related // to nested group elements, as the legend item texts are within 4 group elements. if (/Trident\/7\.0/.test(win.navigator.userAgent) || isFirefox) { wrap(Legend.prototype, 'positionItem', function(proceed, item) { var legend = this, runPositionItem = function() { // If chart destroyed in sync, this is undefined (#2030) if (item._legendItemPos) { proceed.call(legend, item); } }; // Do it now, for export and to get checkbox placement runPositionItem(); // Do it after to work around the core issue setTimeout(runPositionItem); }); } }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var addEvent = H.addEvent, animate = H.animate, animObject = H.animObject, attr = H.attr, doc = H.doc, Axis = H.Axis, // @todo add as requirement createElement = H.createElement, defaultOptions = H.defaultOptions, discardElement = H.discardElement, charts = H.charts, css = H.css, defined = H.defined, each = H.each, error = H.error, extend = H.extend, fireEvent = H.fireEvent, getStyle = H.getStyle, grep = H.grep, isNumber = H.isNumber, isObject = H.isObject, isString = H.isString, Legend = H.Legend, // @todo add as requirement marginNames = H.marginNames, merge = H.merge, Pointer = H.Pointer, // @todo add as requirement pick = H.pick, pInt = H.pInt, removeEvent = H.removeEvent, seriesTypes = H.seriesTypes, splat = H.splat, svg = H.svg, syncTimeout = H.syncTimeout, win = H.win, Renderer = H.Renderer; /** * The Chart class * @param {String|Object} renderTo The DOM element to render to, or its id * @param {Object} options * @param {Function} callback Function to run when the chart has loaded */ var Chart = H.Chart = function() { this.getArgs.apply(this, arguments); }; H.chart = function(a, b, c) { return new Chart(a, b, c); }; Chart.prototype = { /** * Hook for modules */ callbacks: [], /** * Handle the arguments passed to the constructor * @returns {Array} Arguments without renderTo */ getArgs: function() { var args = [].slice.call(arguments); // Remove the optional first argument, renderTo, and // set it on this. if (isString(args[0]) || args[0].nodeName) { this.renderTo = args.shift(); } this.init(args[0], args[1]); }, /** * Initialize the chart */ init: function(userOptions, callback) { // Handle regular options var options, seriesOptions = userOptions.series; // skip merging data points to increase performance userOptions.series = null; options = merge(defaultOptions, userOptions); // do the merge options.series = userOptions.series = seriesOptions; // set back the series data this.userOptions = userOptions; this.respRules = []; var optionsChart = options.chart; var chartEvents = optionsChart.events; this.margin = []; this.spacing = []; //this.runChartClick = chartEvents && !!chartEvents.click; this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom this.callback = callback; this.isResizing = 0; this.options = options; //chartTitleOptions = undefined; //chartSubtitleOptions = undefined; this.axes = []; this.series = []; this.hasCartesianSeries = optionsChart.showAxes; //this.axisOffset = undefined; //this.inverted = undefined; //this.loadingShown = undefined; //this.container = undefined; //this.chartWidth = undefined; //this.chartHeight = undefined; //this.marginRight = undefined; //this.marginBottom = undefined; //this.containerWidth = undefined; //this.containerHeight = undefined; //this.oldChartWidth = undefined; //this.oldChartHeight = undefined; //this.renderTo = undefined; //this.renderToClone = undefined; //this.spacingBox = undefined //this.legend = undefined; // Elements //this.chartBackground = undefined; //this.plotBackground = undefined; //this.plotBGImage = undefined; //this.plotBorder = undefined; //this.loadingDiv = undefined; //this.loadingSpan = undefined; var chart = this, eventType; // Add the chart to the global lookup chart.index = charts.length; charts.push(chart); H.chartCount++; // Chart event handlers if (chartEvents) { for (eventType in chartEvents) { addEvent(chart, eventType, chartEvents[eventType]); } } chart.xAxis = []; chart.yAxis = []; chart.pointCount = chart.colorCounter = chart.symbolCounter = 0; chart.firstRender(); }, /** * Initialize an individual series, called internally before render time */ initSeries: function(options) { var chart = this, optionsChart = chart.options.chart, type = options.type || optionsChart.type || optionsChart.defaultSeriesType, series, Constr = seriesTypes[type]; // No such series type if (!Constr) { error(17, true); } series = new Constr(); series.init(this, options); return series; }, /** * Check whether a given point is within the plot area * * @param {Number} plotX Pixel x relative to the plot area * @param {Number} plotY Pixel y relative to the plot area * @param {Boolean} inverted Whether the chart is inverted */ isInsidePlot: function(plotX, plotY, inverted) { var x = inverted ? plotY : plotX, y = inverted ? plotX : plotY; return x >= 0 && x <= this.plotWidth && y >= 0 && y <= this.plotHeight; }, /** * Redraw legend, axes or series based on updated data * * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ redraw: function(animation) { var chart = this, axes = chart.axes, series = chart.series, pointer = chart.pointer, legend = chart.legend, redrawLegend = chart.isDirtyLegend, hasStackedSeries, hasDirtyStacks, hasCartesianSeries = chart.hasCartesianSeries, isDirtyBox = chart.isDirtyBox, seriesLength = series.length, i = seriesLength, serie, renderer = chart.renderer, isHiddenChart = renderer.isHidden(), afterRedraw = []; H.setAnimation(animation, chart); if (isHiddenChart) { chart.cloneRenderTo(); } // Adjust title layout (reflow multiline text) chart.layOutTitles(); // link stacked series while (i--) { serie = series[i]; if (serie.options.stacking) { hasStackedSeries = true; if (serie.isDirty) { hasDirtyStacks = true; break; } } } if (hasDirtyStacks) { // mark others as dirty i = seriesLength; while (i--) { serie = series[i]; if (serie.options.stacking) { serie.isDirty = true; } } } // Handle updated data in the series each(series, function(serie) { if (serie.isDirty) { if (serie.options.legendType === 'point') { if (serie.updateTotals) { serie.updateTotals(); } redrawLegend = true; } } if (serie.isDirtyData) { fireEvent(serie, 'updatedData'); } }); // handle added or removed series if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed // draw legend graphics legend.render(); chart.isDirtyLegend = false; } // reset stacks if (hasStackedSeries) { chart.getStacks(); } if (hasCartesianSeries) { // set axes scales each(axes, function(axis) { axis.updateNames(); axis.setScale(); }); } chart.getMargins(); // #3098 if (hasCartesianSeries) { // If one axis is dirty, all axes must be redrawn (#792, #2169) each(axes, function(axis) { if (axis.isDirty) { isDirtyBox = true; } }); // redraw axes each(axes, function(axis) { // Fire 'afterSetExtremes' only if extremes are set var key = axis.min + ',' + axis.max; if (axis.extKey !== key) { // #821, #4452 axis.extKey = key; afterRedraw.push(function() { // prevent a recursive call to chart.redraw() (#1119) fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751 delete axis.eventArgs; }); } if (isDirtyBox || hasStackedSeries) { axis.redraw(); } }); } // the plot areas size has changed if (isDirtyBox) { chart.drawChartBox(); } // redraw affected series each(series, function(serie) { if ((isDirtyBox || serie.isDirty) && serie.visible) { serie.redraw(); } }); // move tooltip or reset if (pointer) { pointer.reset(true); } // redraw if canvas renderer.draw(); // fire the event fireEvent(chart, 'redraw'); if (isHiddenChart) { chart.cloneRenderTo(true); } // Fire callbacks that are put on hold until after the redraw each(afterRedraw, function(callback) { callback.call(); }); }, /** * Get an axis, series or point object by id. * @param id {String} The id as given in the configuration options */ get: function(id) { var chart = this, axes = chart.axes, series = chart.series; var i, j, points; // search axes for (i = 0; i < axes.length; i++) { if (axes[i].options.id === id) { return axes[i]; } } // search series for (i = 0; i < series.length; i++) { if (series[i].options.id === id) { return series[i]; } } // search points for (i = 0; i < series.length; i++) { points = series[i].points || []; for (j = 0; j < points.length; j++) { if (points[j].id === id) { return points[j]; } } } return null; }, /** * Create the Axis instances based on the config options */ getAxes: function() { var chart = this, options = this.options, xAxisOptions = options.xAxis = splat(options.xAxis || {}), yAxisOptions = options.yAxis = splat(options.yAxis || {}), optionsArray; // make sure the options are arrays and add some members each(xAxisOptions, function(axis, i) { axis.index = i; axis.isX = true; }); each(yAxisOptions, function(axis, i) { axis.index = i; }); // concatenate all axis options into one array optionsArray = xAxisOptions.concat(yAxisOptions); each(optionsArray, function(axisOptions) { new Axis(chart, axisOptions); // eslint-disable-line no-new }); }, /** * Get the currently selected points from all series */ getSelectedPoints: function() { var points = []; each(this.series, function(serie) { points = points.concat(grep(serie.points || [], function(point) { return point.selected; })); }); return points; }, /** * Get the currently selected series */ getSelectedSeries: function() { return grep(this.series, function(serie) { return serie.selected; }); }, /** * Show the title and subtitle of the chart * * @param titleOptions {Object} New title options * @param subtitleOptions {Object} New subtitle options * */ setTitle: function(titleOptions, subtitleOptions, redraw) { var chart = this, options = chart.options, chartTitleOptions, chartSubtitleOptions; chartTitleOptions = options.title = merge(options.title, titleOptions); chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions); // add title and subtitle each([ ['title', titleOptions, chartTitleOptions], ['subtitle', subtitleOptions, chartSubtitleOptions] ], function(arr, i) { var name = arr[0], title = chart[name], titleOptions = arr[1], chartTitleOptions = arr[2]; if (title && titleOptions) { chart[name] = title = title.destroy(); // remove old } if (chartTitleOptions && chartTitleOptions.text && !title) { chart[name] = chart.renderer.text( chartTitleOptions.text, 0, 0, chartTitleOptions.useHTML ) .attr({ align: chartTitleOptions.align, 'class': 'highcharts-' + name, zIndex: chartTitleOptions.zIndex || 4 }) .add(); // Update methods, shortcut to Chart.setTitle chart[name].update = function(o) { chart.setTitle(!i && o, i && o); }; } }); chart.layOutTitles(redraw); }, /** * Lay out the chart titles and cache the full offset height for use in getMargins */ layOutTitles: function(redraw) { var titleOffset = 0, requiresDirtyBox, renderer = this.renderer, spacingBox = this.spacingBox; // Lay out the title and the subtitle respectively each(['title', 'subtitle'], function(key) { var title = this[key], titleOptions = this.options[key], titleSize; if (title) { titleSize = renderer.fontMetrics(titleSize, title).b; title .css({ width: (titleOptions.width || spacingBox.width + titleOptions.widthAdjust) + 'px' }) .align(extend({ y: titleOffset + titleSize + (key === 'title' ? -3 : 2) }, titleOptions), false, 'spacingBox'); if (!titleOptions.floating && !titleOptions.verticalAlign) { titleOffset = Math.ceil(titleOffset + title.getBBox().height); } } }, this); requiresDirtyBox = this.titleOffset !== titleOffset; this.titleOffset = titleOffset; // used in getMargins if (!this.isDirtyBox && requiresDirtyBox) { this.isDirtyBox = requiresDirtyBox; // Redraw if necessary (#2719, #2744) if (this.hasRendered && pick(redraw, true) && this.isDirtyBox) { this.redraw(); } } }, /** * Get chart width and height according to options and container size */ getChartSize: function() { var chart = this, optionsChart = chart.options.chart, widthOption = optionsChart.width, heightOption = optionsChart.height, renderTo = chart.renderToClone || chart.renderTo; // Get inner width and height if (!defined(widthOption)) { chart.containerWidth = getStyle(renderTo, 'width'); } if (!defined(heightOption)) { chart.containerHeight = getStyle(renderTo, 'height'); } chart.chartWidth = Math.max(0, widthOption || chart.containerWidth || 600); // #1393, 1460 chart.chartHeight = Math.max(0, pick(heightOption, // the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7: chart.containerHeight > 19 ? chart.containerHeight : 400)); }, /** * Create a clone of the chart's renderTo div and place it outside the viewport to allow * size computation on chart.render and chart.redraw */ cloneRenderTo: function(revert) { var clone = this.renderToClone, container = this.container; // Destroy the clone and bring the container back to the real renderTo div if (revert) { if (clone) { while (clone.childNodes.length) { // #5231 this.renderTo.appendChild(clone.firstChild); } discardElement(clone); delete this.renderToClone; } // Set up the clone } else { if (container && container.parentNode === this.renderTo) { this.renderTo.removeChild(container); // do not clone this } this.renderToClone = clone = this.renderTo.cloneNode(0); css(clone, { position: 'absolute', top: '-9999px', display: 'block' // #833 }); if (clone.style.setProperty) { // #2631 clone.style.setProperty('display', 'block', 'important'); } doc.body.appendChild(clone); if (container) { clone.appendChild(container); } } }, /** * Setter for the chart class name */ setClassName: function(className) { this.container.className = 'highcharts-container ' + (className || ''); }, /** * Get the containing element, determine the size and create the inner container * div to hold the chart */ getContainer: function() { var chart = this, container, options = chart.options, optionsChart = options.chart, chartWidth, chartHeight, renderTo = chart.renderTo, indexAttrName = 'data-highcharts-chart', oldChartIndex, Ren, containerId = 'highcharts-' + H.idCounter++, containerStyle, key; if (!renderTo) { chart.renderTo = renderTo = optionsChart.renderTo; } if (isString(renderTo)) { chart.renderTo = renderTo = doc.getElementById(renderTo); } // Display an error if the renderTo is wrong if (!renderTo) { error(13, true); } // If the container already holds a chart, destroy it. The check for hasRendered is there // because web pages that are saved to disk from the browser, will preserve the data-highcharts-chart // attribute and the SVG contents, but not an interactive chart. So in this case, // charts[oldChartIndex] will point to the wrong chart if any (#2609). oldChartIndex = pInt(attr(renderTo, indexAttrName)); if (isNumber(oldChartIndex) && charts[oldChartIndex] && charts[oldChartIndex].hasRendered) { charts[oldChartIndex].destroy(); } // Make a reference to the chart from the div attr(renderTo, indexAttrName, chart.index); // remove previous chart renderTo.innerHTML = ''; // If the container doesn't have an offsetWidth, it has or is a child of a node // that has display:none. We need to temporarily move it out to a visible // state to determine the size, else the legend and tooltips won't render // properly. The allowClone option is used in sparklines as a micro optimization, // saving about 1-2 ms each chart. if (!optionsChart.skipClone && !renderTo.offsetWidth) { chart.cloneRenderTo(); } // get the width and height chart.getChartSize(); chartWidth = chart.chartWidth; chartHeight = chart.chartHeight; // Create the inner container chart.container = container = createElement( 'div', { id: containerId }, containerStyle, chart.renderToClone || renderTo ); // cache the cursor (#1650) chart._cursor = container.style.cursor; // Initialize the renderer Ren = H[optionsChart.renderer] || Renderer; chart.renderer = new Ren( container, chartWidth, chartHeight, null, optionsChart.forExport, options.exporting && options.exporting.allowHTML ); chart.setClassName(optionsChart.className); // Initialize definitions for (key in options.defs) { this.renderer.definition(options.defs[key]); } // Add a reference to the charts index chart.renderer.chartIndex = chart.index; }, /** * Calculate margins by rendering axis labels in a preliminary position. Title, * subtitle and legend have already been rendered at this stage, but will be * moved into their final positions */ getMargins: function(skipAxes) { var chart = this, spacing = chart.spacing, margin = chart.margin, titleOffset = chart.titleOffset; chart.resetMargins(); // Adjust for title and subtitle if (titleOffset && !defined(margin[0])) { chart.plotTop = Math.max(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]); } // Adjust for legend if (chart.legend.display) { chart.legend.adjustMargins(margin, spacing); } // adjust for scroller if (chart.extraBottomMargin) { chart.marginBottom += chart.extraBottomMargin; } if (chart.extraTopMargin) { chart.plotTop += chart.extraTopMargin; } if (!skipAxes) { this.getAxisMargins(); } }, getAxisMargins: function() { var chart = this, axisOffset = chart.axisOffset = [0, 0, 0, 0], // top, right, bottom, left margin = chart.margin; // pre-render axes to get labels offset width if (chart.hasCartesianSeries) { each(chart.axes, function(axis) { if (axis.visible) { axis.getOffset(); } }); } // Add the axis offsets each(marginNames, function(m, side) { if (!defined(margin[side])) { chart[m] += axisOffset[side]; } }); chart.setChartSize(); }, /** * Resize the chart to its container if size is not explicitly set */ reflow: function(e) { var chart = this, optionsChart = chart.options.chart, renderTo = chart.renderTo, hasUserWidth = defined(optionsChart.width), width = optionsChart.width || getStyle(renderTo, 'width'), height = optionsChart.height || getStyle(renderTo, 'height'), target = e ? e.target : win; // Width and height checks for display:none. Target is doc in IE8 and Opera, // win in Firefox, Chrome and IE9. if (!hasUserWidth && !chart.isPrinting && width && height && (target === win || target === doc)) { // #1093 if (width !== chart.containerWidth || height !== chart.containerHeight) { clearTimeout(chart.reflowTimeout); // When called from window.resize, e is set, else it's called directly (#2224) chart.reflowTimeout = syncTimeout(function() { if (chart.container) { // It may have been destroyed in the meantime (#1257) chart.setSize(undefined, undefined, false); } }, e ? 100 : 0); } chart.containerWidth = width; chart.containerHeight = height; } }, /** * Add the event handlers necessary for auto resizing */ initReflow: function() { var chart = this, reflow = function(e) { chart.reflow(e); }; addEvent(win, 'resize', reflow); addEvent(chart, 'destroy', function() { removeEvent(win, 'resize', reflow); }); // The following will add listeners to re-fit the chart before and after // printing (#2284). However it only works in WebKit. Should have worked // in Firefox, but not supported in IE. /* if (win.matchMedia) { win.matchMedia('print').addListener(function reflow() { chart.reflow(); }); } */ }, /** * Resize the chart to a given width and height * @param {Number} width * @param {Number} height * @param {Object|Boolean} animation */ setSize: function(width, height, animation) { var chart = this, renderer = chart.renderer, globalAnimation; // Handle the isResizing counter chart.isResizing += 1; // set the animation for the current process H.setAnimation(animation, chart); chart.oldChartHeight = chart.chartHeight; chart.oldChartWidth = chart.chartWidth; if (width !== undefined) { chart.options.chart.width = width; } if (height !== undefined) { chart.options.chart.height = height; } chart.getChartSize(); // Resize the container with the global animation applied if enabled (#2503) chart.setChartSize(true); renderer.setSize(chart.chartWidth, chart.chartHeight, animation); // handle axes each(chart.axes, function(axis) { axis.isDirty = true; axis.setScale(); }); chart.isDirtyLegend = true; // force legend redraw chart.isDirtyBox = true; // force redraw of plot and chart border chart.layOutTitles(); // #2857 chart.getMargins(); if (chart.setResponsive) { chart.setResponsive(false); } chart.redraw(animation); chart.oldChartHeight = null; fireEvent(chart, 'resize'); // Fire endResize and set isResizing back. If animation is disabled, fire without delay syncTimeout(function() { if (chart) { fireEvent(chart, 'endResize', null, function() { chart.isResizing -= 1; }); } }, animObject(globalAnimation).duration); }, /** * Set the public chart properties. This is done before and after the pre-render * to determine margin sizes */ setChartSize: function(skipAxes) { var chart = this, inverted = chart.inverted, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, optionsChart = chart.options.chart, spacing = chart.spacing, clipOffset = chart.clipOffset, clipX, clipY, plotLeft, plotTop, plotWidth, plotHeight, plotBorderWidth; chart.plotLeft = plotLeft = Math.round(chart.plotLeft); chart.plotTop = plotTop = Math.round(chart.plotTop); chart.plotWidth = plotWidth = Math.max(0, Math.round(chartWidth - plotLeft - chart.marginRight)); chart.plotHeight = plotHeight = Math.max(0, Math.round(chartHeight - plotTop - chart.marginBottom)); chart.plotSizeX = inverted ? plotHeight : plotWidth; chart.plotSizeY = inverted ? plotWidth : plotHeight; chart.plotBorderWidth = optionsChart.plotBorderWidth || 0; // Set boxes used for alignment chart.spacingBox = renderer.spacingBox = { x: spacing[3], y: spacing[0], width: chartWidth - spacing[3] - spacing[1], height: chartHeight - spacing[0] - spacing[2] }; chart.plotBox = renderer.plotBox = { x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight }; plotBorderWidth = 2 * Math.floor(chart.plotBorderWidth / 2); clipX = Math.ceil(Math.max(plotBorderWidth, clipOffset[3]) / 2); clipY = Math.ceil(Math.max(plotBorderWidth, clipOffset[0]) / 2); chart.clipBox = { x: clipX, y: clipY, width: Math.floor(chart.plotSizeX - Math.max(plotBorderWidth, clipOffset[1]) / 2 - clipX), height: Math.max(0, Math.floor(chart.plotSizeY - Math.max(plotBorderWidth, clipOffset[2]) / 2 - clipY)) }; if (!skipAxes) { each(chart.axes, function(axis) { axis.setAxisSize(); axis.setAxisTranslation(); }); } }, /** * Initial margins before auto size margins are applied */ resetMargins: function() { var chart = this, chartOptions = chart.options.chart; // Create margin and spacing array each(['margin', 'spacing'], function splashArrays(target) { var value = chartOptions[target], values = isObject(value) ? value : [value, value, value, value]; each(['Top', 'Right', 'Bottom', 'Left'], function(sideName, side) { chart[target][side] = pick(chartOptions[target + sideName], values[side]); }); }); // Set margin names like chart.plotTop, chart.plotLeft, chart.marginRight, chart.marginBottom. each(marginNames, function(m, side) { chart[m] = pick(chart.margin[side], chart.spacing[side]); }); chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left chart.clipOffset = [0, 0, 0, 0]; }, /** * Draw the borders and backgrounds for chart and plot area */ drawChartBox: function() { var chart = this, optionsChart = chart.options.chart, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, chartBackground = chart.chartBackground, plotBackground = chart.plotBackground, plotBorder = chart.plotBorder, chartBorderWidth, mgn, bgAttr, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, plotBox = chart.plotBox, clipRect = chart.clipRect, clipBox = chart.clipBox, verb = 'animate'; // Chart area if (!chartBackground) { chart.chartBackground = chartBackground = renderer.rect() .addClass('highcharts-background') .add(); verb = 'attr'; } chartBorderWidth = mgn = chartBackground.strokeWidth(); chartBackground[verb]({ x: mgn / 2, y: mgn / 2, width: chartWidth - mgn - chartBorderWidth % 2, height: chartHeight - mgn - chartBorderWidth % 2, r: optionsChart.borderRadius }); // Plot background verb = 'animate'; if (!plotBackground) { verb = 'attr'; chart.plotBackground = plotBackground = renderer.rect() .addClass('highcharts-plot-background') .add(); } plotBackground[verb](plotBox); // Plot clip if (!clipRect) { chart.clipRect = renderer.clipRect(clipBox); } else { clipRect.animate({ width: clipBox.width, height: clipBox.height }); } // Plot area border verb = 'animate'; if (!plotBorder) { verb = 'attr'; chart.plotBorder = plotBorder = renderer.rect() .addClass('highcharts-plot-border') .attr({ zIndex: 1 // Above the grid }) .add(); } plotBorder[verb](plotBorder.crisp({ x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight }, -plotBorder.strokeWidth())); //#3282 plotBorder should be negative; // reset chart.isDirtyBox = false; }, /** * Detect whether a certain chart property is needed based on inspecting its options * and series. This mainly applies to the chart.inverted property, and in extensions to * the chart.angular and chart.polar properties. */ propFromSeries: function() { var chart = this, optionsChart = chart.options.chart, klass, seriesOptions = chart.options.series, i, value; each(['inverted', 'angular', 'polar'], function(key) { // The default series type's class klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType]; // Get the value from available chart-wide properties value = optionsChart[key] || // It is set in the options (klass && klass.prototype[key]); // The default series class requires it // 4. Check if any the chart's series require it i = seriesOptions && seriesOptions.length; while (!value && i--) { klass = seriesTypes[seriesOptions[i].type]; if (klass && klass.prototype[key]) { value = true; } } // Set the chart property chart[key] = value; }); }, /** * Link two or more series together. This is done initially from Chart.render, * and after Chart.addSeries and Series.remove. */ linkSeries: function() { var chart = this, chartSeries = chart.series; // Reset links each(chartSeries, function(series) { series.linkedSeries.length = 0; }); // Apply new links each(chartSeries, function(series) { var linkedTo = series.options.linkedTo; if (isString(linkedTo)) { if (linkedTo === ':previous') { linkedTo = chart.series[series.index - 1]; } else { linkedTo = chart.get(linkedTo); } if (linkedTo && linkedTo.linkedParent !== series) { // #3341 avoid mutual linking linkedTo.linkedSeries.push(series); series.linkedParent = linkedTo; series.visible = pick(series.options.visible, linkedTo.options.visible, series.visible); // #3879 } } }); }, /** * Render series for the chart */ renderSeries: function() { each(this.series, function(serie) { serie.translate(); serie.render(); }); }, /** * Render labels for the chart */ renderLabels: function() { var chart = this, labels = chart.options.labels; if (labels.items) { each(labels.items, function(label) { var style = extend(labels.style, label.style), x = pInt(style.left) + chart.plotLeft, y = pInt(style.top) + chart.plotTop + 12; // delete to prevent rewriting in IE delete style.left; delete style.top; chart.renderer.text( label.html, x, y ) .attr({ zIndex: 2 }) .css(style) .add(); }); } }, /** * Render all graphics for the chart */ render: function() { var chart = this, axes = chart.axes, renderer = chart.renderer, options = chart.options, tempWidth, tempHeight, redoHorizontal, redoVertical; // Title chart.setTitle(); // Legend chart.legend = new Legend(chart, options.legend); // Get stacks if (chart.getStacks) { chart.getStacks(); } // Get chart margins chart.getMargins(true); chart.setChartSize(); // Record preliminary dimensions for later comparison tempWidth = chart.plotWidth; tempHeight = chart.plotHeight = chart.plotHeight - 21; // 21 is the most common correction for X axis labels // Get margins by pre-rendering axes each(axes, function(axis) { axis.setScale(); }); chart.getAxisMargins(); // If the plot area size has changed significantly, calculate tick positions again redoHorizontal = tempWidth / chart.plotWidth > 1.1; redoVertical = tempHeight / chart.plotHeight > 1.05; // Height is more sensitive if (redoHorizontal || redoVertical) { each(axes, function(axis) { if ((axis.horiz && redoHorizontal) || (!axis.horiz && redoVertical)) { axis.setTickInterval(true); // update to reflect the new margins } }); chart.getMargins(); // second pass to check for new labels } // Draw the borders and backgrounds chart.drawChartBox(); // Axes if (chart.hasCartesianSeries) { each(axes, function(axis) { if (axis.visible) { axis.render(); } }); } // The series if (!chart.seriesGroup) { chart.seriesGroup = renderer.g('series-group') .attr({ zIndex: 3 }) .add(); } chart.renderSeries(); // Labels chart.renderLabels(); // Credits chart.addCredits(); // Handle responsiveness if (chart.setResponsive) { chart.setResponsive(); } // Set flag chart.hasRendered = true; }, /** * Show chart credits based on config options */ addCredits: function(credits) { var chart = this; credits = merge(true, this.options.credits, credits); if (credits.enabled && !this.credits) { this.credits = this.renderer.text( credits.text + (this.mapCredits || ''), 0, 0 ) .addClass('highcharts-credits') .on('click', function() { if (credits.href) { win.location.href = credits.href; } }) .attr({ align: credits.position.align, zIndex: 8 }) .add() .align(credits.position); // Dynamically update this.credits.update = function(options) { chart.credits = chart.credits.destroy(); chart.addCredits(options); }; } }, /** * Clean up memory usage */ destroy: function() { var chart = this, axes = chart.axes, series = chart.series, container = chart.container, i, parentNode = container && container.parentNode; // fire the chart.destoy event fireEvent(chart, 'destroy'); // Delete the chart from charts lookup array charts[chart.index] = undefined; H.chartCount--; chart.renderTo.removeAttribute('data-highcharts-chart'); // remove events removeEvent(chart); // ==== Destroy collections: // Destroy axes i = axes.length; while (i--) { axes[i] = axes[i].destroy(); } // Destroy scroller & scroller series before destroying base series if (this.scroller && this.scroller.destroy) { this.scroller.destroy(); } // Destroy each series i = series.length; while (i--) { series[i] = series[i].destroy(); } // ==== Destroy chart properties: each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage', 'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer' ], function(name) { var prop = chart[name]; if (prop && prop.destroy) { chart[name] = prop.destroy(); } }); // remove container and all SVG if (container) { // can break in IE when destroyed before finished loading container.innerHTML = ''; removeEvent(container); if (parentNode) { discardElement(container); } } // clean it all up for (i in chart) { delete chart[i]; } }, /** * VML namespaces can't be added until after complete. Listening * for Perini's doScroll hack is not enough. */ isReadyToRender: function() { var chart = this; // Note: win == win.top is required if ((!svg && (win == win.top && doc.readyState !== 'complete'))) { // eslint-disable-line eqeqeq doc.attachEvent('onreadystatechange', function() { doc.detachEvent('onreadystatechange', chart.firstRender); if (doc.readyState === 'complete') { chart.firstRender(); } }); return false; } return true; }, /** * Prepare for first rendering after all data are loaded */ firstRender: function() { var chart = this, options = chart.options; // Check whether the chart is ready to render if (!chart.isReadyToRender()) { return; } // Create the container chart.getContainer(); // Run an early event after the container and renderer are established fireEvent(chart, 'init'); chart.resetMargins(); chart.setChartSize(); // Set the common chart properties (mainly invert) from the given series chart.propFromSeries(); // get axes chart.getAxes(); // Initialize the series each(options.series || [], function(serieOptions) { chart.initSeries(serieOptions); }); chart.linkSeries(); // Run an event after axes and series are initialized, but before render. At this stage, // the series data is indexed and cached in the xData and yData arrays, so we can access // those before rendering. Used in Highstock. fireEvent(chart, 'beforeRender'); // depends on inverted and on margins being set if (Pointer) { chart.pointer = new Pointer(chart, options); } chart.render(); // add canvas chart.renderer.draw(); // Fire the load event if there are no external images if (!chart.renderer.imgCount && chart.onload) { chart.onload(); } // If the chart was rendered outside the top container, put it back in (#3679) chart.cloneRenderTo(true); }, /** * On chart load */ onload: function() { // Run callbacks each([this.callback].concat(this.callbacks), function(fn) { if (fn && this.index !== undefined) { // Chart destroyed in its own callback (#3600) fn.apply(this, [this]); } }, this); fireEvent(this, 'load'); // Set up auto resize if (this.options.chart.reflow !== false) { this.initReflow(); } // Don't run again this.onload = null; } }; // end Chart }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var Point, each = H.each, extend = H.extend, erase = H.erase, fireEvent = H.fireEvent, format = H.format, isArray = H.isArray, isNumber = H.isNumber, pick = H.pick, removeEvent = H.removeEvent; /** * The Point object and prototype. Inheritable and used as base for PiePoint */ Point = H.Point = function() {}; Point.prototype = { /** * Initialize the point * @param {Object} series The series object containing this point * @param {Object} options The data in either number, array or object format */ init: function(series, options, x) { var point = this, colors, colorCount = series.chart.options.chart.colorCount, colorIndex; point.series = series; point.applyOptions(options, x); if (series.options.colorByPoint) { colorIndex = series.colorCounter; series.colorCounter++; // loop back to zero if (series.colorCounter === colorCount) { series.colorCounter = 0; } } else { colorIndex = series.colorIndex; } point.colorIndex = pick(point.colorIndex, colorIndex); series.chart.pointCount++; return point; }, /** * Apply the options containing the x and y data and possible some extra properties. * This is called on point init or from point.update. * * @param {Object} options */ applyOptions: function(options, x) { var point = this, series = point.series, pointValKey = series.options.pointValKey || series.pointValKey; options = Point.prototype.optionsToObject.call(this, options); // copy options directly to point extend(point, options); point.options = point.options ? extend(point.options, options) : options; // Since options are copied into the Point instance, some accidental options must be shielded (#5681) if (options.group) { delete point.group; } // For higher dimension series types. For instance, for ranges, point.y is mapped to point.low. if (pointValKey) { point.y = point[pointValKey]; } point.isNull = pick( point.isValid && !point.isValid(), point.x === null || !isNumber(point.y, true) ); // #3571, check for NaN // The point is initially selected by options (#5777) if (point.selected) { point.state = 'select'; } // If no x is set by now, get auto incremented value. All points must have an // x value, however the y value can be null to create a gap in the series if ('name' in point && x === undefined && series.xAxis && series.xAxis.hasNames) { point.x = series.xAxis.nameToX(point); } if (point.x === undefined && series) { if (x === undefined) { point.x = series.autoIncrement(point); } else { point.x = x; } } return point; }, /** * Transform number or array configs into objects */ optionsToObject: function(options) { var ret = {}, series = this.series, keys = series.options.keys, pointArrayMap = keys || series.pointArrayMap || ['y'], valueCount = pointArrayMap.length, firstItemType, i = 0, j = 0; if (isNumber(options) || options === null) { ret[pointArrayMap[0]] = options; } else if (isArray(options)) { // with leading x value if (!keys && options.length > valueCount) { firstItemType = typeof options[0]; if (firstItemType === 'string') { ret.name = options[0]; } else if (firstItemType === 'number') { ret.x = options[0]; } i++; } while (j < valueCount) { if (!keys || options[i] !== undefined) { // Skip undefined positions for keys ret[pointArrayMap[j]] = options[i]; } i++; j++; } } else if (typeof options === 'object') { ret = options; // This is the fastest way to detect if there are individual point dataLabels that need // to be considered in drawDataLabels. These can only occur in object configs. if (options.dataLabels) { series._hasPointLabels = true; } // Same approach as above for markers if (options.marker) { series._hasPointMarkers = true; } } return ret; }, /** * Get the CSS class names for individual points * @returns {String} The class name */ getClassName: function() { return 'highcharts-point' + (this.selected ? ' highcharts-point-select' : '') + (this.negative ? ' highcharts-negative' : '') + (this.isNull ? ' highcharts-null-point' : '') + (this.colorIndex !== undefined ? ' highcharts-color-' + this.colorIndex : '') + (this.options.className ? ' ' + this.options.className : ''); }, /** * Return the zone that the point belongs to */ getZone: function() { var series = this.series, zones = series.zones, zoneAxis = series.zoneAxis || 'y', i = 0, zone; zone = zones[i]; while (this[zoneAxis] >= zone.value) { zone = zones[++i]; } if (zone && zone.color && !this.options.color) { this.color = zone.color; } return zone; }, /** * Destroy a point to clear memory. Its reference still stays in series.data. */ destroy: function() { var point = this, series = point.series, chart = series.chart, hoverPoints = chart.hoverPoints, prop; chart.pointCount--; if (hoverPoints) { point.setState(); erase(hoverPoints, point); if (!hoverPoints.length) { chart.hoverPoints = null; } } if (point === chart.hoverPoint) { point.onMouseOut(); } // remove all events if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive removeEvent(point); point.destroyElements(); } if (point.legendItem) { // pies have legend items chart.legend.destroyItem(point); } for (prop in point) { point[prop] = null; } }, /** * Destroy SVG elements associated with the point */ destroyElements: function() { var point = this, props = ['graphic', 'dataLabel', 'dataLabelUpper', 'connector', 'shadowGroup'], prop, i = 6; while (i--) { prop = props[i]; if (point[prop]) { point[prop] = point[prop].destroy(); } } }, /** * Return the configuration hash needed for the data label and tooltip formatters */ getLabelConfig: function() { return { x: this.category, y: this.y, color: this.color, key: this.name || this.category, series: this.series, point: this, percentage: this.percentage, total: this.total || this.stackTotal }; }, /** * Extendable method for formatting each point's tooltip line * * @return {String} A string to be concatenated in to the common tooltip text */ tooltipFormatter: function(pointFormat) { // Insert options for valueDecimals, valuePrefix, and valueSuffix var series = this.series, seriesTooltipOptions = series.tooltipOptions, valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''), valuePrefix = seriesTooltipOptions.valuePrefix || '', valueSuffix = seriesTooltipOptions.valueSuffix || ''; // Loop over the point array map and replace unformatted values with sprintf formatting markup each(series.pointArrayMap || ['y'], function(key) { key = '{point.' + key; // without the closing bracket if (valuePrefix || valueSuffix) { pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix); } pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}'); }); return format(pointFormat, { point: this, series: this.series }); }, /** * Fire an event on the Point object. * @param {String} eventType * @param {Object} eventArgs Additional event arguments * @param {Function} defaultFunction Default event handler */ firePointEvent: function(eventType, eventArgs, defaultFunction) { var point = this, series = this.series, seriesOptions = series.options; // load event handlers on demand to save time on mouseover/out if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) { this.importEvents(); } // add default handler if in selection mode if (eventType === 'click' && seriesOptions.allowPointSelect) { defaultFunction = function(event) { // Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera if (point.select) { // Could be destroyed by prior event handlers (#2911) point.select(null, event.ctrlKey || event.metaKey || event.shiftKey); } }; } fireEvent(this, eventType, eventArgs, defaultFunction); }, visible: true }; }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var addEvent = H.addEvent, animObject = H.animObject, arrayMax = H.arrayMax, arrayMin = H.arrayMin, correctFloat = H.correctFloat, Date = H.Date, defaultOptions = H.defaultOptions, defaultPlotOptions = H.defaultPlotOptions, defined = H.defined, each = H.each, erase = H.erase, error = H.error, extend = H.extend, fireEvent = H.fireEvent, grep = H.grep, isArray = H.isArray, isNumber = H.isNumber, isString = H.isString, LegendSymbolMixin = H.LegendSymbolMixin, // @todo add as a requirement merge = H.merge, pick = H.pick, Point = H.Point, // @todo add as a requirement removeEvent = H.removeEvent, splat = H.splat, stableSort = H.stableSort, SVGElement = H.SVGElement, syncTimeout = H.syncTimeout, win = H.win; /** * @classDescription The base function which all other series types inherit from. The data in the series is stored * in various arrays. * * - First, series.options.data contains all the original config options for * each point whether added by options or methods like series.addPoint. * - Next, series.data contains those values converted to points, but in case the series data length * exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It * only contains the points that have been created on demand. * - Then there's series.points that contains all currently visible point objects. In case of cropping, * the cropped-away points are not part of this array. The series.points array starts at series.cropStart * compared to series.data and series.options.data. If however the series data is grouped, these can't * be correlated one to one. * - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points. * - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points. * * @param {Object} chart * @param {Object} options */ H.Series = H.seriesType('line', null, { // base series options allowPointSelect: false, showCheckbox: false, animation: { duration: 1000 }, //clip: true, //connectNulls: false, //enableMouseTracking: true, events: {}, //legendIndex: 0, // stacking: null, marker: { //enabled: true, //symbol: null, radius: 4, states: { // states for a single point hover: { animation: { duration: 50 }, enabled: true, radiusPlus: 2 } } }, point: { events: {} }, dataLabels: { align: 'center', // defer: true, // enabled: false, formatter: function() { return this.y === null ? '' : H.numberFormat(this.y, -1); }, /*style: { color: 'contrast', textShadow: '0 0 6px contrast, 0 0 3px contrast' },*/ verticalAlign: 'bottom', // above singular point x: 0, y: 0, // borderRadius: undefined, padding: 5 }, cropThreshold: 300, // draw points outside the plot area when the number of points is less than this pointRange: 0, //pointStart: 0, //pointInterval: 1, //showInLegend: null, // auto: true for standalone series, false for linked series softThreshold: true, states: { // states for the entire series hover: { //enabled: false, lineWidthPlus: 1, marker: { // lineWidth: base + 1, // radius: base + 1 }, halo: { size: 10 } }, select: { marker: {} } }, stickyTracking: true, //tooltip: { //pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b>' //valueDecimals: null, //xDateFormat: '%A, %b %e, %Y', //valuePrefix: '', //ySuffix: '' //} turboThreshold: 1000 // zIndex: null // Prototype properties }, { isCartesian: true, pointClass: Point, sorted: true, // requires the data to be sorted requireSorting: true, directTouch: false, axisTypes: ['xAxis', 'yAxis'], colorCounter: 0, parallelArrays: ['x', 'y'], // each point's x and y values are stored in this.xData and this.yData coll: 'series', init: function(chart, options) { var series = this, eventType, events, chartSeries = chart.series, sortByIndex = function(a, b) { return pick(a.options.index, a._i) - pick(b.options.index, b._i); }; series.chart = chart; series.options = options = series.setOptions(options); // merge with plotOptions series.linkedSeries = []; // bind the axes series.bindAxes(); // set some variables extend(series, { name: options.name, state: '', visible: options.visible !== false, // true by default selected: options.selected === true // false by default }); // register event listeners events = options.events; for (eventType in events) { addEvent(series, eventType, events[eventType]); } if ( (events && events.click) || (options.point && options.point.events && options.point.events.click) || options.allowPointSelect ) { chart.runTrackerClick = true; } series.getColor(); series.getSymbol(); // Set the data each(series.parallelArrays, function(key) { series[key + 'Data'] = []; }); series.setData(options.data, false); // Mark cartesian if (series.isCartesian) { chart.hasCartesianSeries = true; } // Register it in the chart chartSeries.push(series); series._i = chartSeries.length - 1; // Sort series according to index option (#248, #1123, #2456) stableSort(chartSeries, sortByIndex); if (this.yAxis) { stableSort(this.yAxis.series, sortByIndex); } each(chartSeries, function(series, i) { series.index = i; series.name = series.name || 'Series ' + (i + 1); }); }, /** * Set the xAxis and yAxis properties of cartesian series, and register the series * in the axis.series array */ bindAxes: function() { var series = this, seriesOptions = series.options, chart = series.chart, axisOptions; each(series.axisTypes || [], function(AXIS) { // repeat for xAxis and yAxis each(chart[AXIS], function(axis) { // loop through the chart's axis objects axisOptions = axis.options; // apply if the series xAxis or yAxis option mathches the number of the // axis, or if undefined, use the first axis if ((seriesOptions[AXIS] === axisOptions.index) || (seriesOptions[AXIS] !== undefined && seriesOptions[AXIS] === axisOptions.id) || (seriesOptions[AXIS] === undefined && axisOptions.index === 0)) { // register this series in the axis.series lookup axis.series.push(series); // set this series.xAxis or series.yAxis reference series[AXIS] = axis; // mark dirty for redraw axis.isDirty = true; } }); // The series needs an X and an Y axis if (!series[AXIS] && series.optionalAxis !== AXIS) { error(18, true); } }); }, /** * For simple series types like line and column, the data values are held in arrays like * xData and yData for quick lookup to find extremes and more. For multidimensional series * like bubble and map, this can be extended with arrays like zData and valueData by * adding to the series.parallelArrays array. */ updateParallelArrays: function(point, i) { var series = point.series, args = arguments, fn = isNumber(i) ? // Insert the value in the given position function(key) { var val = key === 'y' && series.toYData ? series.toYData(point) : point[key]; series[key + 'Data'][i] = val; } : // Apply the method specified in i with the following arguments as arguments function(key) { Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2)); }; each(series.parallelArrays, fn); }, /** * Return an auto incremented x value based on the pointStart and pointInterval options. * This is only used if an x value is not given for the point that calls autoIncrement. */ autoIncrement: function() { var options = this.options, xIncrement = this.xIncrement, date, pointInterval, pointIntervalUnit = options.pointIntervalUnit; xIncrement = pick(xIncrement, options.pointStart, 0); this.pointInterval = pointInterval = pick(this.pointInterval, options.pointInterval, 1); // Added code for pointInterval strings if (pointIntervalUnit) { date = new Date(xIncrement); if (pointIntervalUnit === 'day') { date = +date[Date.hcSetDate](date[Date.hcGetDate]() + pointInterval); } else if (pointIntervalUnit === 'month') { date = +date[Date.hcSetMonth](date[Date.hcGetMonth]() + pointInterval); } else if (pointIntervalUnit === 'year') { date = +date[Date.hcSetFullYear](date[Date.hcGetFullYear]() + pointInterval); } pointInterval = date - xIncrement; } this.xIncrement = xIncrement + pointInterval; return xIncrement; }, /** * Set the series options by merging from the options tree * @param {Object} itemOptions */ setOptions: function(itemOptions) { var chart = this.chart, chartOptions = chart.options, plotOptions = chartOptions.plotOptions, userOptions = chart.userOptions || {}, userPlotOptions = userOptions.plotOptions || {}, typeOptions = plotOptions[this.type], options, zones; this.userOptions = itemOptions; // General series options take precedence over type options because otherwise, default // type options like column.animation would be overwritten by the general option. // But issues have been raised here (#3881), and the solution may be to distinguish // between default option and userOptions like in the tooltip below. options = merge( typeOptions, plotOptions.series, itemOptions ); // The tooltip options are merged between global and series specific options this.tooltipOptions = merge( defaultOptions.tooltip, defaultOptions.plotOptions[this.type].tooltip, userOptions.tooltip, userPlotOptions.series && userPlotOptions.series.tooltip, userPlotOptions[this.type] && userPlotOptions[this.type].tooltip, itemOptions.tooltip ); // Delete marker object if not allowed (#1125) if (typeOptions.marker === null) { delete options.marker; } // Handle color zones this.zoneAxis = options.zoneAxis; zones = this.zones = (options.zones || []).slice(); if ((options.negativeColor || options.negativeFillColor) && !options.zones) { zones.push({ value: options[this.zoneAxis + 'Threshold'] || options.threshold || 0, className: 'highcharts-negative' }); } if (zones.length) { // Push one extra zone for the rest if (defined(zones[zones.length - 1].value)) { zones.push({ }); } } return options; }, getCyclic: function(prop, value, defaults) { var i, userOptions = this.userOptions, indexName = prop + 'Index', counterName = prop + 'Counter', len = defaults ? defaults.length : pick(this.chart.options.chart[prop + 'Count'], this.chart[prop + 'Count']), setting; if (!value) { // Pick up either the colorIndex option, or the _colorIndex after Series.update() setting = pick(userOptions[indexName], userOptions['_' + indexName]); if (defined(setting)) { // after Series.update() i = setting; } else { userOptions['_' + indexName] = i = this.chart[counterName] % len; this.chart[counterName] += 1; } if (defaults) { value = defaults[i]; } } // Set the colorIndex if (i !== undefined) { this[indexName] = i; } this[prop] = value; }, /** * Get the series' color */ getColor: function() { this.getCyclic('color'); }, /** * Get the series' symbol */ getSymbol: function() { var seriesMarkerOption = this.options.marker; this.getCyclic('symbol', seriesMarkerOption.symbol, this.chart.options.symbols); }, drawLegendSymbol: LegendSymbolMixin.drawLineMarker, /** * Replace the series data with a new set of data * @param {Object} data * @param {Object} redraw */ setData: function(data, redraw, animation, updatePoints) { var series = this, oldData = series.points, oldDataLength = (oldData && oldData.length) || 0, dataLength, options = series.options, chart = series.chart, firstPoint = null, xAxis = series.xAxis, i, turboThreshold = options.turboThreshold, pt, xData = this.xData, yData = this.yData, pointArrayMap = series.pointArrayMap, valueCount = pointArrayMap && pointArrayMap.length; data = data || []; dataLength = data.length; redraw = pick(redraw, true); // If the point count is the same as is was, just run Point.update which is // cheaper, allows animation, and keeps references to points. if (updatePoints !== false && dataLength && oldDataLength === dataLength && !series.cropped && !series.hasGroupedData && series.visible) { each(data, function(point, i) { // .update doesn't exist on a linked, hidden series (#3709) if (oldData[i].update && point !== options.data[i]) { oldData[i].update(point, false, null, false); } }); } else { // Reset properties series.xIncrement = null; series.colorCounter = 0; // for series with colorByPoint (#1547) // Update parallel arrays each(this.parallelArrays, function(key) { series[key + 'Data'].length = 0; }); // In turbo mode, only one- or twodimensional arrays of numbers are allowed. The // first value is tested, and we assume that all the rest are defined the same // way. Although the 'for' loops are similar, they are repeated inside each // if-else conditional for max performance. if (turboThreshold && dataLength > turboThreshold) { // find the first non-null point i = 0; while (firstPoint === null && i < dataLength) { firstPoint = data[i]; i++; } if (isNumber(firstPoint)) { // assume all points are numbers for (i = 0; i < dataLength; i++) { xData[i] = this.autoIncrement(); yData[i] = data[i]; } } else if (isArray(firstPoint)) { // assume all points are arrays if (valueCount) { // [x, low, high] or [x, o, h, l, c] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt.slice(1, valueCount + 1); } } else { // [x, y] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt[1]; } } } else { error(12); // Highcharts expects configs to be numbers or arrays in turbo mode } } else { for (i = 0; i < dataLength; i++) { if (data[i] !== undefined) { // stray commas in oldIE pt = { series: series }; series.pointClass.prototype.applyOptions.apply(pt, [data[i]]); series.updateParallelArrays(pt, i); } } } // Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON if (isString(yData[0])) { error(14, true); } series.data = []; series.options.data = series.userOptions.data = data; // destroy old points i = oldDataLength; while (i--) { if (oldData[i] && oldData[i].destroy) { oldData[i].destroy(); } } // reset minRange (#878) if (xAxis) { xAxis.minRange = xAxis.userMinRange; } // redraw series.isDirty = chart.isDirtyBox = true; series.isDirtyData = !!oldData; animation = false; } // Typically for pie series, points need to be processed and generated // prior to rendering the legend if (options.legendType === 'point') { this.processData(); this.generatePoints(); } if (redraw) { chart.redraw(animation); } }, /** * Process the data by cropping away unused data points if the series is longer * than the crop threshold. This saves computing time for lage series. */ processData: function(force) { var series = this, processedXData = series.xData, // copied during slice operation below processedYData = series.yData, dataLength = processedXData.length, croppedData, cropStart = 0, cropped, distance, closestPointRange, xAxis = series.xAxis, i, // loop variable options = series.options, cropThreshold = options.cropThreshold, getExtremesFromAll = series.getExtremesFromAll || options.getExtremesFromAll, // #4599 isCartesian = series.isCartesian, xExtremes, val2lin = xAxis && xAxis.val2lin, isLog = xAxis && xAxis.isLog, min, max; // If the series data or axes haven't changed, don't go through this. Return false to pass // the message on to override methods like in data grouping. if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) { return false; } if (xAxis) { xExtremes = xAxis.getExtremes(); // corrected for log axis (#3053) min = xExtremes.min; max = xExtremes.max; } // optionally filter out points outside the plot area if (isCartesian && series.sorted && !getExtremesFromAll && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) { // it's outside current extremes if (processedXData[dataLength - 1] < min || processedXData[0] > max) { processedXData = []; processedYData = []; // only crop if it's actually spilling out } else if (processedXData[0] < min || processedXData[dataLength - 1] > max) { croppedData = this.cropData(series.xData, series.yData, min, max); processedXData = croppedData.xData; processedYData = croppedData.yData; cropStart = croppedData.start; cropped = true; } } // Find the closest distance between processed points i = processedXData.length || 1; while (--i) { distance = isLog ? val2lin(processedXData[i]) - val2lin(processedXData[i - 1]) : processedXData[i] - processedXData[i - 1]; if (distance > 0 && (closestPointRange === undefined || distance < closestPointRange)) { closestPointRange = distance; // Unsorted data is not supported by the line tooltip, as well as data grouping and // navigation in Stock charts (#725) and width calculation of columns (#1900) } else if (distance < 0 && series.requireSorting) { error(15); } } // Record the properties series.cropped = cropped; // undefined or true series.cropStart = cropStart; series.processedXData = processedXData; series.processedYData = processedYData; series.closestPointRange = closestPointRange; }, /** * Iterate over xData and crop values between min and max. Returns object containing crop start/end * cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range */ cropData: function(xData, yData, min, max) { var dataLength = xData.length, cropStart = 0, cropEnd = dataLength, cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside i, j; // iterate up to find slice start for (i = 0; i < dataLength; i++) { if (xData[i] >= min) { cropStart = Math.max(0, i - cropShoulder); break; } } // proceed to find slice end for (j = i; j < dataLength; j++) { if (xData[j] > max) { cropEnd = j + cropShoulder; break; } } return { xData: xData.slice(cropStart, cropEnd), yData: yData.slice(cropStart, cropEnd), start: cropStart, end: cropEnd }; }, /** * Generate the data point after the data has been processed by cropping away * unused points and optionally grouped in Highcharts Stock. */ generatePoints: function() { var series = this, options = series.options, dataOptions = options.data, data = series.data, dataLength, processedXData = series.processedXData, processedYData = series.processedYData, PointClass = series.pointClass, processedDataLength = processedXData.length, cropStart = series.cropStart || 0, cursor, hasGroupedData = series.hasGroupedData, point, points = [], i; if (!data && !hasGroupedData) { var arr = []; arr.length = dataOptions.length; data = series.data = arr; } for (i = 0; i < processedDataLength; i++) { cursor = cropStart + i; if (!hasGroupedData) { if (data[cursor]) { point = data[cursor]; } else if (dataOptions[cursor] !== undefined) { // #970 data[cursor] = point = (new PointClass()).init(series, dataOptions[cursor], processedXData[i]); } points[i] = point; } else { // splat the y data in case of ohlc data array points[i] = (new PointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i]))); points[i].dataGroup = series.groupMap[i]; } points[i].index = cursor; // For faster access in Point.update } // Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when // swithching view from non-grouped data to grouped data (#637) if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) { for (i = 0; i < dataLength; i++) { if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points i += processedDataLength; } if (data[i]) { data[i].destroyElements(); data[i].plotX = undefined; // #1003 } } } series.data = data; series.points = points; }, /** * Calculate Y extremes for visible data */ getExtremes: function(yData) { var xAxis = this.xAxis, yAxis = this.yAxis, xData = this.processedXData, yDataLength, activeYData = [], activeCounter = 0, xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis xMin = xExtremes.min, xMax = xExtremes.max, validValue, withinRange, x, y, i, j; yData = yData || this.stackedYData || this.processedYData || []; yDataLength = yData.length; for (i = 0; i < yDataLength; i++) { x = xData[i]; y = yData[i]; // For points within the visible range, including the first point outside the // visible range, consider y extremes validValue = (isNumber(y, true) || isArray(y)) && (!yAxis.isLog || (y.length || y > 0)); withinRange = this.getExtremesFromAll || this.options.getExtremesFromAll || this.cropped || ((xData[i + 1] || x) >= xMin && (xData[i - 1] || x) <= xMax); if (validValue && withinRange) { j = y.length; if (j) { // array, like ohlc or range data while (j--) { if (y[j] !== null) { activeYData[activeCounter++] = y[j]; } } } else { activeYData[activeCounter++] = y; } } } this.dataMin = arrayMin(activeYData); this.dataMax = arrayMax(activeYData); }, /** * Translate data points from raw data values to chart specific positioning data * needed later in drawPoints, drawGraph and drawTracker. */ translate: function() { if (!this.processedXData) { // hidden series this.processData(); } this.generatePoints(); var series = this, options = series.options, stacking = options.stacking, xAxis = series.xAxis, categories = xAxis.categories, yAxis = series.yAxis, points = series.points, dataLength = points.length, hasModifyValue = !!series.modifyValue, i, pointPlacement = options.pointPlacement, dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement), threshold = options.threshold, stackThreshold = options.startFromThreshold ? threshold : 0, plotX, plotY, lastPlotX, stackIndicator, closestPointRangePx = Number.MAX_VALUE; // Translate each point for (i = 0; i < dataLength; i++) { var point = points[i], xValue = point.x, yValue = point.y, yBottom = point.low, stack = stacking && yAxis.stacks[(series.negStacks && yValue < (stackThreshold ? 0 : threshold) ? '-' : '') + series.stackKey], pointStack, stackValues; // Discard disallowed y values for log axes (#3434) if (yAxis.isLog && yValue !== null && yValue <= 0) { point.isNull = true; } // Get the plotX translation point.plotX = plotX = correctFloat( // #5236 Math.min(Math.max(-1e5, xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags')), 1e5) // #3923 ); // Calculate the bottom y value for stacked series if (stacking && series.visible && !point.isNull && stack && stack[xValue]) { stackIndicator = series.getStackIndicator(stackIndicator, xValue, series.index); pointStack = stack[xValue]; stackValues = pointStack.points[stackIndicator.key]; yBottom = stackValues[0]; yValue = stackValues[1]; if (yBottom === stackThreshold && stackIndicator.key === stack[xValue].base) { yBottom = pick(threshold, yAxis.min); } if (yAxis.isLog && yBottom <= 0) { // #1200, #1232 yBottom = null; } point.total = point.stackTotal = pointStack.total; point.percentage = pointStack.total && (point.y / pointStack.total * 100); point.stackY = yValue; // Place the stack label pointStack.setOffset(series.pointXOffset || 0, series.barW || 0); } // Set translated yBottom or remove it point.yBottom = defined(yBottom) ? yAxis.translate(yBottom, 0, 1, 0, 1) : null; // general hook, used for Highstock compare mode if (hasModifyValue) { yValue = series.modifyValue(yValue, point); } // Set the the plotY value, reset it for redraws point.plotY = plotY = (typeof yValue === 'number' && yValue !== Infinity) ? Math.min(Math.max(-1e5, yAxis.translate(yValue, 0, 1, 0, 1)), 1e5) : // #3201 undefined; point.isInside = plotY !== undefined && plotY >= 0 && plotY <= yAxis.len && // #3519 plotX >= 0 && plotX <= xAxis.len; // Set client related positions for mouse tracking point.clientX = dynamicallyPlaced ? correctFloat(xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement)) : plotX; // #1514, #5383, #5518 point.negative = point.y < (threshold || 0); // some API data point.category = categories && categories[point.x] !== undefined ? categories[point.x] : point.x; // Determine auto enabling of markers (#3635, #5099) if (!point.isNull) { if (lastPlotX !== undefined) { closestPointRangePx = Math.min(closestPointRangePx, Math.abs(plotX - lastPlotX)); } lastPlotX = plotX; } } series.closestPointRangePx = closestPointRangePx; }, /** * Return the series points with null points filtered out */ getValidPoints: function(points, insideOnly) { var chart = this.chart; return grep(points || this.points || [], function isValidPoint(point) { // #3916, #5029 if (insideOnly && !chart.isInsidePlot(point.plotX, point.plotY, chart.inverted)) { // #5085 return false; } return !point.isNull; }); }, /** * Set the clipping for the series. For animated series it is called twice, first to initiate * animating the clip then the second time without the animation to set the final clip. */ setClip: function(animation) { var chart = this.chart, options = this.options, renderer = chart.renderer, inverted = chart.inverted, seriesClipBox = this.clipBox, clipBox = seriesClipBox || chart.clipBox, sharedClipKey = this.sharedClipKey || ['_sharedClip', animation && animation.duration, animation && animation.easing, clipBox.height, options.xAxis, options.yAxis].join(','), // #4526 clipRect = chart[sharedClipKey], markerClipRect = chart[sharedClipKey + 'm']; // If a clipping rectangle with the same properties is currently present in the chart, use that. if (!clipRect) { // When animation is set, prepare the initial positions if (animation) { clipBox.width = 0; chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect(-99, // include the width of the first marker inverted ? -chart.plotLeft : -chart.plotTop, 99, inverted ? chart.chartWidth : chart.chartHeight ); } chart[sharedClipKey] = clipRect = renderer.clipRect(clipBox); // Create hashmap for series indexes clipRect.count = { length: 0 }; } if (animation) { if (!clipRect.count[this.index]) { clipRect.count[this.index] = true; clipRect.count.length += 1; } } if (options.clip !== false) { this.group.clip(animation || seriesClipBox ? clipRect : chart.clipRect); this.markerGroup.clip(markerClipRect); this.sharedClipKey = sharedClipKey; } // Remove the shared clipping rectangle when all series are shown if (!animation) { if (clipRect.count[this.index]) { delete clipRect.count[this.index]; clipRect.count.length -= 1; } if (clipRect.count.length === 0 && sharedClipKey && chart[sharedClipKey]) { if (!seriesClipBox) { chart[sharedClipKey] = chart[sharedClipKey].destroy(); } if (chart[sharedClipKey + 'm']) { chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy(); } } } }, /** * Animate in the series */ animate: function(init) { var series = this, chart = series.chart, clipRect, animation = animObject(series.options.animation), sharedClipKey; // Initialize the animation. Set up the clipping rectangle. if (init) { series.setClip(animation); // Run the animation } else { sharedClipKey = this.sharedClipKey; clipRect = chart[sharedClipKey]; if (clipRect) { clipRect.animate({ width: chart.plotSizeX }, animation); } if (chart[sharedClipKey + 'm']) { chart[sharedClipKey + 'm'].animate({ width: chart.plotSizeX + 99 }, animation); } // Delete this function to allow it only once series.animate = null; } }, /** * This runs after animation to land on the final plot clipping */ afterAnimate: function() { this.setClip(); fireEvent(this, 'afterAnimate'); }, /** * Draw the markers */ drawPoints: function() { var series = this, points = series.points, chart = series.chart, plotY, i, point, symbol, graphic, options = series.options, seriesMarkerOptions = options.marker, pointMarkerOptions, hasPointMarker, enabled, isInside, markerGroup = series.markerGroup, xAxis = series.xAxis, markerAttribs, globallyEnabled = pick( seriesMarkerOptions.enabled, xAxis.isRadial ? true : null, series.closestPointRangePx > 2 * seriesMarkerOptions.radius ); if (seriesMarkerOptions.enabled !== false || series._hasPointMarkers) { i = points.length; while (i--) { point = points[i]; plotY = point.plotY; graphic = point.graphic; pointMarkerOptions = point.marker || {}; hasPointMarker = !!point.marker; enabled = (globallyEnabled && pointMarkerOptions.enabled === undefined) || pointMarkerOptions.enabled; isInside = point.isInside; // only draw the point if y is defined if (enabled && isNumber(plotY) && point.y !== null) { // Shortcuts symbol = pick(pointMarkerOptions.symbol, series.symbol); point.hasImage = symbol.indexOf('url') === 0; markerAttribs = series.markerAttribs( point, point.selected && 'select' ); if (graphic) { // update graphic[isInside ? 'show' : 'hide'](true) // Since the marker group isn't clipped, each individual marker must be toggled .animate(markerAttribs); } else if (isInside && (markerAttribs.width > 0 || point.hasImage)) { point.graphic = graphic = chart.renderer.symbol( symbol, markerAttribs.x, markerAttribs.y, markerAttribs.width, markerAttribs.height, hasPointMarker ? pointMarkerOptions : seriesMarkerOptions ) .add(markerGroup); } if (graphic) { graphic.addClass(point.getClassName(), true); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } } } }, /** * Get non-presentational attributes for the point. */ markerAttribs: function(point, state) { var seriesMarkerOptions = this.options.marker, seriesStateOptions, pointOptions = point && point.options, pointMarkerOptions = (pointOptions && pointOptions.marker) || {}, pointStateOptions, radius = pick( pointMarkerOptions.radius, seriesMarkerOptions.radius ), attribs; // Handle hover and select states if (state) { seriesStateOptions = seriesMarkerOptions.states[state]; pointStateOptions = pointMarkerOptions.states && pointMarkerOptions.states[state]; radius = pick( pointStateOptions && pointStateOptions.radius, seriesStateOptions && seriesStateOptions.radius, radius + (seriesStateOptions && seriesStateOptions.radiusPlus || 0) ); } if (point.hasImage) { radius = 0; // and subsequently width and height is not set } attribs = { x: Math.floor(point.plotX) - radius, // Math.floor for #1843 y: point.plotY - radius }; if (radius) { attribs.width = attribs.height = 2 * radius; } return attribs; }, /** * Clear DOM objects and free up memory */ destroy: function() { var series = this, chart = series.chart, issue134 = /AppleWebKit\/533/.test(win.navigator.userAgent), destroy, i, data = series.data || [], point, prop, axis; // add event hook fireEvent(series, 'destroy'); // remove all events removeEvent(series); // erase from axes each(series.axisTypes || [], function(AXIS) { axis = series[AXIS]; if (axis && axis.series) { erase(axis.series, series); axis.isDirty = axis.forceRedraw = true; } }); // remove legend items if (series.legendItem) { series.chart.legend.destroyItem(series); } // destroy all points with their elements i = data.length; while (i--) { point = data[i]; if (point && point.destroy) { point.destroy(); } } series.points = null; // Clear the animation timeout if we are destroying the series during initial animation clearTimeout(series.animationTimeout); // Destroy all SVGElements associated to the series for (prop in series) { if (series[prop] instanceof SVGElement && !series[prop].survive) { // Survive provides a hook for not destroying // issue 134 workaround destroy = issue134 && prop === 'group' ? 'hide' : 'destroy'; series[prop][destroy](); } } // remove from hoverSeries if (chart.hoverSeries === series) { chart.hoverSeries = null; } erase(chart.series, series); // clear all members for (prop in series) { delete series[prop]; } }, /** * Get the graph path */ getGraphPath: function(points, nullsAsZeroes, connectCliffs) { var series = this, options = series.options, step = options.step, reversed, graphPath = [], xMap = [], gap; points = points || series.points; // Bottom of a stack is reversed reversed = points.reversed; if (reversed) { points.reverse(); } // Reverse the steps (#5004) step = { right: 1, center: 2 }[step] || (step && 3); if (step && reversed) { step = 4 - step; } // Remove invalid points, especially in spline (#5015) if (options.connectNulls && !nullsAsZeroes && !connectCliffs) { points = this.getValidPoints(points); } // Build the line each(points, function(point, i) { var plotX = point.plotX, plotY = point.plotY, lastPoint = points[i - 1], pathToPoint; // the path to this point from the previous if ((point.leftCliff || (lastPoint && lastPoint.rightCliff)) && !connectCliffs) { gap = true; // ... and continue } // Line series, nullsAsZeroes is not handled if (point.isNull && !defined(nullsAsZeroes) && i > 0) { gap = !options.connectNulls; // Area series, nullsAsZeroes is set } else if (point.isNull && !nullsAsZeroes) { gap = true; } else { if (i === 0 || gap) { pathToPoint = ['M', point.plotX, point.plotY]; } else if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object pathToPoint = series.getPointSpline(points, point, i); } else if (step) { if (step === 1) { // right pathToPoint = [ 'L', lastPoint.plotX, plotY ]; } else if (step === 2) { // center pathToPoint = [ 'L', (lastPoint.plotX + plotX) / 2, lastPoint.plotY, 'L', (lastPoint.plotX + plotX) / 2, plotY ]; } else { pathToPoint = [ 'L', plotX, lastPoint.plotY ]; } pathToPoint.push('L', plotX, plotY); } else { // normal line to next point pathToPoint = [ 'L', plotX, plotY ]; } // Prepare for animation. When step is enabled, there are two path nodes for each x value. xMap.push(point.x); if (step) { xMap.push(point.x); } graphPath.push.apply(graphPath, pathToPoint); gap = false; } }); graphPath.xMap = xMap; series.graphPath = graphPath; return graphPath; }, /** * Draw the actual graph */ drawGraph: function() { var series = this, options = this.options, graphPath = (this.gappedPath || this.getGraphPath).call(this), props = [ [ 'graph', 'highcharts-graph' ] ]; // Add the zone properties if any each(this.zones, function(zone, i) { props.push([ 'zone-graph-' + i, 'highcharts-graph highcharts-zone-graph-' + i + ' ' + (zone.className || '') ]); }); // Draw the graph each(props, function(prop, i) { var graphKey = prop[0], graph = series[graphKey], attribs; if (graph) { graph.endX = graphPath.xMap; graph.animate({ d: graphPath }); } else if (graphPath.length) { // #1487 series[graphKey] = series.chart.renderer.path(graphPath) .addClass(prop[1]) .attr({ zIndex: 1 }) // #1069 .add(series.group); } // Helpers for animation if (graph) { graph.startX = graphPath.xMap; //graph.shiftUnit = options.step ? 2 : 1; graph.isArea = graphPath.isArea; // For arearange animation } }); }, /** * Clip the graphs into the positive and negative coloured graphs */ applyZones: function() { var series = this, chart = this.chart, renderer = chart.renderer, zones = this.zones, translatedFrom, translatedTo, clips = this.clips || [], clipAttr, graph = this.graph, area = this.area, chartSizeMax = Math.max(chart.chartWidth, chart.chartHeight), axis = this[(this.zoneAxis || 'y') + 'Axis'], extremes, reversed, inverted = chart.inverted, horiz, pxRange, pxPosMin, pxPosMax, ignoreZones = false; if (zones.length && (graph || area) && axis && axis.min !== undefined) { reversed = axis.reversed; horiz = axis.horiz; // The use of the Color Threshold assumes there are no gaps // so it is safe to hide the original graph and area if (graph) { graph.hide(); } if (area) { area.hide(); } // Create the clips extremes = axis.getExtremes(); each(zones, function(threshold, i) { translatedFrom = reversed ? (horiz ? chart.plotWidth : 0) : (horiz ? 0 : axis.toPixels(extremes.min)); translatedFrom = Math.min(Math.max(pick(translatedTo, translatedFrom), 0), chartSizeMax); translatedTo = Math.min(Math.max(Math.round(axis.toPixels(pick(threshold.value, extremes.max), true)), 0), chartSizeMax); if (ignoreZones) { translatedFrom = translatedTo = axis.toPixels(extremes.max); } pxRange = Math.abs(translatedFrom - translatedTo); pxPosMin = Math.min(translatedFrom, translatedTo); pxPosMax = Math.max(translatedFrom, translatedTo); if (axis.isXAxis) { clipAttr = { x: inverted ? pxPosMax : pxPosMin, y: 0, width: pxRange, height: chartSizeMax }; if (!horiz) { clipAttr.x = chart.plotHeight - clipAttr.x; } } else { clipAttr = { x: 0, y: inverted ? pxPosMax : pxPosMin, width: chartSizeMax, height: pxRange }; if (horiz) { clipAttr.y = chart.plotWidth - clipAttr.y; } } if (clips[i]) { clips[i].animate(clipAttr); } else { clips[i] = renderer.clipRect(clipAttr); if (graph) { series['zone-graph-' + i].clip(clips[i]); } if (area) { series['zone-area-' + i].clip(clips[i]); } } // if this zone extends out of the axis, ignore the others ignoreZones = threshold.value > extremes.max; }); this.clips = clips; } }, /** * Initialize and perform group inversion on series.group and series.markerGroup */ invertGroups: function(inverted) { var series = this, chart = series.chart; // Pie, go away (#1736) if (!series.xAxis) { return; } // A fixed size is needed for inversion to work function setInvert() { var size = { width: series.yAxis.len, height: series.xAxis.len }; each(['group', 'markerGroup'], function(groupName) { if (series[groupName]) { series[groupName].attr(size).invert(inverted); } }); } addEvent(chart, 'resize', setInvert); // do it on resize addEvent(series, 'destroy', function() { removeEvent(chart, 'resize', setInvert); }); // Do it now setInvert(inverted); // do it now // On subsequent render and redraw, just do setInvert without setting up events again series.invertGroups = setInvert; }, /** * General abstraction for creating plot groups like series.group, series.dataLabelsGroup and * series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size. */ plotGroup: function(prop, name, visibility, zIndex, parent) { var group = this[prop], isNew = !group; // Generate it on first call if (isNew) { this[prop] = group = this.chart.renderer.g(name) .attr({ zIndex: zIndex || 0.1 // IE8 and pointer logic use this }) .add(parent); group.addClass('highcharts-series-' + this.index + ' highcharts-' + this.type + '-series highcharts-color-' + this.colorIndex + ' ' + (this.options.className || '')); } // Place it on first and subsequent (redraw) calls group.attr({ visibility: visibility })[isNew ? 'attr' : 'animate'](this.getPlotBox()); return group; }, /** * Get the translation and scale for the plot area of this series */ getPlotBox: function() { var chart = this.chart, xAxis = this.xAxis, yAxis = this.yAxis; // Swap axes for inverted (#2339) if (chart.inverted) { xAxis = yAxis; yAxis = this.xAxis; } return { translateX: xAxis ? xAxis.left : chart.plotLeft, translateY: yAxis ? yAxis.top : chart.plotTop, scaleX: 1, // #1623 scaleY: 1 }; }, /** * Render the graph and markers */ render: function() { var series = this, chart = series.chart, group, options = series.options, // Animation doesn't work in IE8 quirks when the group div is hidden, // and looks bad in other oldIE animDuration = !!series.animate && chart.renderer.isSVG && animObject(options.animation).duration, visibility = series.visible ? 'inherit' : 'hidden', // #2597 zIndex = options.zIndex, hasRendered = series.hasRendered, chartSeriesGroup = chart.seriesGroup, inverted = chart.inverted; // the group group = series.plotGroup( 'group', 'series', visibility, zIndex, chartSeriesGroup ); series.markerGroup = series.plotGroup( 'markerGroup', 'markers', visibility, zIndex, chartSeriesGroup ); // initiate the animation if (animDuration) { series.animate(true); } // SVGRenderer needs to know this before drawing elements (#1089, #1795) group.inverted = series.isCartesian ? inverted : false; // draw the graph if any if (series.drawGraph) { series.drawGraph(); series.applyZones(); } /* each(series.points, function (point) { if (point.redraw) { point.redraw(); } });*/ // draw the data labels (inn pies they go before the points) if (series.drawDataLabels) { series.drawDataLabels(); } // draw the points if (series.visible) { series.drawPoints(); } // draw the mouse tracking area if (series.drawTracker && series.options.enableMouseTracking !== false) { series.drawTracker(); } // Handle inverted series and tracker groups series.invertGroups(inverted); // Initial clipping, must be defined after inverting groups for VML. Applies to columns etc. (#3839). if (options.clip !== false && !series.sharedClipKey && !hasRendered) { group.clip(chart.clipRect); } // Run the animation if (animDuration) { series.animate(); } // Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option // which should be available to the user). if (!hasRendered) { series.animationTimeout = syncTimeout(function() { series.afterAnimate(); }, animDuration); } series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see // (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see series.hasRendered = true; }, /** * Redraw the series after an update in the axes. */ redraw: function() { var series = this, chart = series.chart, wasDirty = series.isDirty || series.isDirtyData, // cache it here as it is set to false in render, but used after group = series.group, xAxis = series.xAxis, yAxis = series.yAxis; // reposition on resize if (group) { if (chart.inverted) { group.attr({ width: chart.plotWidth, height: chart.plotHeight }); } group.animate({ translateX: pick(xAxis && xAxis.left, chart.plotLeft), translateY: pick(yAxis && yAxis.top, chart.plotTop) }); } series.translate(); series.render(); if (wasDirty) { // #3868, #3945 delete this.kdTree; } }, /** * KD Tree && PointSearching Implementation */ kdDimensions: 1, kdAxisArray: ['clientX', 'plotY'], searchPoint: function(e, compareX) { var series = this, xAxis = series.xAxis, yAxis = series.yAxis, inverted = series.chart.inverted; return this.searchKDTree({ clientX: inverted ? xAxis.len - e.chartY + xAxis.pos : e.chartX - xAxis.pos, plotY: inverted ? yAxis.len - e.chartX + yAxis.pos : e.chartY - yAxis.pos }, compareX); }, buildKDTree: function() { var series = this, dimensions = series.kdDimensions; // Internal function function _kdtree(points, depth, dimensions) { var axis, median, length = points && points.length; if (length) { // alternate between the axis axis = series.kdAxisArray[depth % dimensions]; // sort point array points.sort(function(a, b) { return a[axis] - b[axis]; }); median = Math.floor(length / 2); // build and return nod return { point: points[median], left: _kdtree(points.slice(0, median), depth + 1, dimensions), right: _kdtree(points.slice(median + 1), depth + 1, dimensions) }; } } // Start the recursive build process with a clone of the points array and null points filtered out (#3873) function startRecursive() { series.kdTree = _kdtree( series.getValidPoints( null, !series.directTouch // For line-type series restrict to plot area, but column-type series not (#3916, #4511) ), dimensions, dimensions ); } delete series.kdTree; // For testing tooltips, don't build async syncTimeout(startRecursive, series.options.kdNow ? 0 : 1); }, searchKDTree: function(point, compareX) { var series = this, kdX = this.kdAxisArray[0], kdY = this.kdAxisArray[1], kdComparer = compareX ? 'distX' : 'dist'; // Set the one and two dimensional distance on the point object function setDistance(p1, p2) { var x = (defined(p1[kdX]) && defined(p2[kdX])) ? Math.pow(p1[kdX] - p2[kdX], 2) : null, y = (defined(p1[kdY]) && defined(p2[kdY])) ? Math.pow(p1[kdY] - p2[kdY], 2) : null, r = (x || 0) + (y || 0); p2.dist = defined(r) ? Math.sqrt(r) : Number.MAX_VALUE; p2.distX = defined(x) ? Math.sqrt(x) : Number.MAX_VALUE; } function _search(search, tree, depth, dimensions) { var point = tree.point, axis = series.kdAxisArray[depth % dimensions], tdist, sideA, sideB, ret = point, nPoint1, nPoint2; setDistance(search, point); // Pick side based on distance to splitting point tdist = search[axis] - point[axis]; sideA = tdist < 0 ? 'left' : 'right'; sideB = tdist < 0 ? 'right' : 'left'; // End of tree if (tree[sideA]) { nPoint1 = _search(search, tree[sideA], depth + 1, dimensions); ret = (nPoint1[kdComparer] < ret[kdComparer] ? nPoint1 : point); } if (tree[sideB]) { // compare distance to current best to splitting point to decide wether to check side B or not if (Math.sqrt(tdist * tdist) < ret[kdComparer]) { nPoint2 = _search(search, tree[sideB], depth + 1, dimensions); ret = (nPoint2[kdComparer] < ret[kdComparer] ? nPoint2 : ret); } } return ret; } if (!this.kdTree) { this.buildKDTree(); } if (this.kdTree) { return _search(point, this.kdTree, this.kdDimensions, this.kdDimensions); } } }); // end Series prototype }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var addEvent = H.addEvent, animate = H.animate, Axis = H.Axis, Chart = H.Chart, createElement = H.createElement, css = H.css, defined = H.defined, each = H.each, erase = H.erase, extend = H.extend, fireEvent = H.fireEvent, inArray = H.inArray, isNumber = H.isNumber, isObject = H.isObject, merge = H.merge, pick = H.pick, Point = H.Point, Series = H.Series, seriesTypes = H.seriesTypes, setAnimation = H.setAnimation, splat = H.splat; // Extend the Chart prototype for dynamic methods extend(Chart.prototype, { /** * Add a series dynamically after time * * @param {Object} options The config options * @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * * @return {Object} series The newly created series object */ addSeries: function(options, redraw, animation) { var series, chart = this; if (options) { redraw = pick(redraw, true); // defaults to true fireEvent(chart, 'addSeries', { options: options }, function() { series = chart.initSeries(options); chart.isDirtyLegend = true; // the series array is out of sync with the display chart.linkSeries(); if (redraw) { chart.redraw(animation); } }); } return series; }, /** * Add an axis to the chart * @param {Object} options The axis option * @param {Boolean} isX Whether it is an X axis or a value axis */ addAxis: function(options, isX, redraw, animation) { var key = isX ? 'xAxis' : 'yAxis', chartOptions = this.options, userOptions = merge(options, { index: this[key].length, isX: isX }); new Axis(this, userOptions); // eslint-disable-line no-new // Push the new axis options to the chart options chartOptions[key] = splat(chartOptions[key] || {}); chartOptions[key].push(userOptions); if (pick(redraw, true)) { this.redraw(animation); } }, /** * Dim the chart and show a loading text or symbol * @param {String} str An optional text to show in the loading label instead of the default one */ showLoading: function(str) { var chart = this, options = chart.options, loadingDiv = chart.loadingDiv, loadingOptions = options.loading, setLoadingSize = function() { if (loadingDiv) { css(loadingDiv, { left: chart.plotLeft + 'px', top: chart.plotTop + 'px', width: chart.plotWidth + 'px', height: chart.plotHeight + 'px' }); } }; // create the layer at the first call if (!loadingDiv) { chart.loadingDiv = loadingDiv = createElement('div', { className: 'highcharts-loading highcharts-loading-hidden' }, null, chart.container); chart.loadingSpan = createElement( 'span', { className: 'highcharts-loading-inner' }, null, loadingDiv ); addEvent(chart, 'redraw', setLoadingSize); // #1080 } loadingDiv.className = 'highcharts-loading'; // Update text chart.loadingSpan.innerHTML = str || options.lang.loading; chart.loadingShown = true; setLoadingSize(); }, /** * Hide the loading layer */ hideLoading: function() { var options = this.options, loadingDiv = this.loadingDiv; if (loadingDiv) { loadingDiv.className = 'highcharts-loading highcharts-loading-hidden'; } this.loadingShown = false; }, /** * These properties cause isDirtyBox to be set to true when updating. Can be extended from plugins. */ propsRequireDirtyBox: ['backgroundColor', 'borderColor', 'borderWidth', 'margin', 'marginTop', 'marginRight', 'marginBottom', 'marginLeft', 'spacing', 'spacingTop', 'spacingRight', 'spacingBottom', 'spacingLeft', 'borderRadius', 'plotBackgroundColor', 'plotBackgroundImage', 'plotBorderColor', 'plotBorderWidth', 'plotShadow', 'shadow' ], /** * These properties cause all series to be updated when updating. Can be extended from plugins. */ propsRequireUpdateSeries: ['chart.polar', 'chart.ignoreHiddenSeries', 'chart.type', 'colors', 'plotOptions'], /** * Chart.update function that takes the whole options stucture. */ update: function(options, redraw) { var key, adders = { credits: 'addCredits', title: 'setTitle', subtitle: 'setSubtitle' }, optionsChart = options.chart, updateAllAxes, updateAllSeries, newWidth, newHeight; // If the top-level chart option is present, some special updates are required if (optionsChart) { merge(true, this.options.chart, optionsChart); // Setter function if ('className' in optionsChart) { this.setClassName(optionsChart.className); } if ('inverted' in optionsChart || 'polar' in optionsChart) { this.propFromSeries(); // Parses options.chart.inverted and options.chart.polar together with the available series updateAllAxes = true; } for (key in optionsChart) { if (optionsChart.hasOwnProperty(key)) { if (inArray('chart.' + key, this.propsRequireUpdateSeries) !== -1) { updateAllSeries = true; } // Only dirty box if (inArray(key, this.propsRequireDirtyBox) !== -1) { this.isDirtyBox = true; } } } } // Some option stuctures correspond one-to-one to chart objects that have // update methods, for example // options.credits => chart.credits // options.legend => chart.legend // options.title => chart.title // options.tooltip => chart.tooltip // options.subtitle => chart.subtitle // options.navigator => chart.navigator // options.scrollbar => chart.scrollbar for (key in options) { if (this[key] && typeof this[key].update === 'function') { this[key].update(options[key], false); // If a one-to-one object does not exist, look for an adder function } else if (typeof this[adders[key]] === 'function') { this[adders[key]](options[key]); } if (key !== 'chart' && inArray(key, this.propsRequireUpdateSeries) !== -1) { updateAllSeries = true; } } if (options.plotOptions) { merge(true, this.options.plotOptions, options.plotOptions); } // Setters for collections. For axes and series, each item is referred by an id. If the // id is not found, it defaults to the first item in the collection, so setting series // without an id, will update the first series in the chart. each(['xAxis', 'yAxis', 'series'], function(coll) { if (options[coll]) { each(splat(options[coll]), function(newOptions) { var item = (defined(newOptions.id) && this.get(newOptions.id)) || this[coll][0]; if (item && item.coll === coll) { item.update(newOptions, false); } }, this); } }, this); if (updateAllAxes) { each(this.axes, function(axis) { axis.update({}, false); }); } // Certain options require the whole series structure to be thrown away // and rebuilt if (updateAllSeries) { each(this.series, function(series) { series.update({}, false); }); } // For loading, just update the options, do not redraw if (options.loading) { merge(true, this.options.loading, options.loading); } // Update size. Redraw is forced. newWidth = optionsChart && optionsChart.width; newHeight = optionsChart && optionsChart.height; if ((isNumber(newWidth) && newWidth !== this.chartWidth) || (isNumber(newHeight) && newHeight !== this.chartHeight)) { this.setSize(newWidth, newHeight); } else if (pick(redraw, true)) { this.redraw(); } }, /** * Setter function to allow use from chart.update */ setSubtitle: function(options) { this.setTitle(undefined, options); } }); // extend the Point prototype for dynamic methods extend(Point.prototype, { /** * Point.update with new options (typically x/y data) and optionally redraw the series. * * @param {Object} options Point options as defined in the series.data array * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ update: function(options, redraw, animation, runEvent) { var point = this, series = point.series, graphic = point.graphic, i, chart = series.chart, seriesOptions = series.options; redraw = pick(redraw, true); function update() { point.applyOptions(options); // Update visuals if (point.y === null && graphic) { // #4146 point.graphic = graphic.destroy(); } if (isObject(options, true)) { // Destroy so we can get new elements if (graphic && graphic.element) { if (options && options.marker && options.marker.symbol) { point.graphic = graphic.destroy(); } } if (options && options.dataLabels && point.dataLabel) { // #2468 point.dataLabel = point.dataLabel.destroy(); } } // record changes in the parallel arrays i = point.index; series.updateParallelArrays(point, i); // Record the options to options.data. If there is an object from before, // use point options, otherwise use raw options. (#4701) seriesOptions.data[i] = isObject(seriesOptions.data[i], true) ? point.options : options; // redraw series.isDirty = series.isDirtyData = true; if (!series.fixedBox && series.hasCartesianSeries) { // #1906, #2320 chart.isDirtyBox = true; } if (seriesOptions.legendType === 'point') { // #1831, #1885 chart.isDirtyLegend = true; } if (redraw) { chart.redraw(animation); } } // Fire the event with a default handler of doing the update if (runEvent === false) { // When called from setData update(); } else { point.firePointEvent('update', { options: options }, update); } }, /** * Remove a point and optionally redraw the series and if necessary the axes * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function(redraw, animation) { this.series.removePoint(inArray(this, this.series.data), redraw, animation); } }); // Extend the series prototype for dynamic methods extend(Series.prototype, { /** * Add a point dynamically after chart load time * @param {Object} options Point options as given in series.data * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean} shift If shift is true, a point is shifted off the start * of the series as one is appended to the end. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ addPoint: function(options, redraw, shift, animation) { var series = this, seriesOptions = series.options, data = series.data, chart = series.chart, names = series.xAxis && series.xAxis.names, dataOptions = seriesOptions.data, point, isInTheMiddle, xData = series.xData, i, x; // Optional redraw, defaults to true redraw = pick(redraw, true); // Get options and push the point to xData, yData and series.options. In series.generatePoints // the Point instance will be created on demand and pushed to the series.data array. point = { series: series }; series.pointClass.prototype.applyOptions.apply(point, [options]); x = point.x; // Get the insertion point i = xData.length; if (series.requireSorting && x < xData[i - 1]) { isInTheMiddle = true; while (i && xData[i - 1] > x) { i--; } } series.updateParallelArrays(point, 'splice', i, 0, 0); // insert undefined item series.updateParallelArrays(point, i); // update it if (names && point.name) { names[x] = point.name; } dataOptions.splice(i, 0, options); if (isInTheMiddle) { series.data.splice(i, 0, null); series.processData(); } // Generate points to be added to the legend (#1329) if (seriesOptions.legendType === 'point') { series.generatePoints(); } // Shift the first point off the parallel arrays if (shift) { if (data[0] && data[0].remove) { data[0].remove(false); } else { data.shift(); series.updateParallelArrays(point, 'shift'); dataOptions.shift(); } } // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(animation); // Animation is set anyway on redraw, #5665 } }, /** * Remove a point (rendered or not), by index */ removePoint: function(i, redraw, animation) { var series = this, data = series.data, point = data[i], points = series.points, chart = series.chart, remove = function() { if (points && points.length === data.length) { // #4935 points.splice(i, 1); } data.splice(i, 1); series.options.data.splice(i, 1); series.updateParallelArrays(point || { series: series }, 'splice', i, 1); if (point) { point.destroy(); } // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(); } }; setAnimation(animation, chart); redraw = pick(redraw, true); // Fire the event with a default handler of removing the point if (point) { point.firePointEvent('remove', null, remove); } else { remove(); } }, /** * Remove a series and optionally redraw the chart * * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function(redraw, animation, withEvent) { var series = this, chart = series.chart; function remove() { // Destroy elements series.destroy(); // Redraw chart.isDirtyLegend = chart.isDirtyBox = true; chart.linkSeries(); if (pick(redraw, true)) { chart.redraw(animation); } } // Fire the event with a default handler of removing the point if (withEvent !== false) { fireEvent(series, 'remove', null, remove); } else { remove(); } }, /** * Series.update with a new set of options */ update: function(newOptions, redraw) { var series = this, chart = this.chart, // must use user options when changing type because this.options is merged // in with type specific plotOptions oldOptions = this.userOptions, oldType = this.type, newType = newOptions.type || oldOptions.type || chart.options.chart.type, proto = seriesTypes[oldType].prototype, preserve = ['group', 'markerGroup', 'dataLabelsGroup'], n; // If we're changing type or zIndex, create new groups (#3380, #3404) if ((newType && newType !== oldType) || newOptions.zIndex !== undefined) { preserve.length = 0; } // Make sure groups are not destroyed (#3094) each(preserve, function(prop) { preserve[prop] = series[prop]; delete series[prop]; }); // Do the merge, with some forced options newOptions = merge(oldOptions, { animation: false, index: this.index, pointStart: this.xData[0] // when updating after addPoint }, { data: this.options.data }, newOptions); // Destroy the series and delete all properties. Reinsert all methods // and properties from the new type prototype (#2270, #3719) this.remove(false, null, false); for (n in proto) { this[n] = undefined; } extend(this, seriesTypes[newType || oldType].prototype); // Re-register groups (#3094) each(preserve, function(prop) { series[prop] = preserve[prop]; }); this.init(chart, newOptions); chart.linkSeries(); // Links are lost in this.remove (#3028) if (pick(redraw, true)) { chart.redraw(false); } } }); // Extend the Axis.prototype for dynamic methods extend(Axis.prototype, { /** * Axis.update with a new options structure */ update: function(newOptions, redraw) { var chart = this.chart; newOptions = chart.options[this.coll][this.options.index] = merge(this.userOptions, newOptions); this.destroy(true); this.init(chart, extend(newOptions, { events: undefined })); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Remove the axis from the chart */ remove: function(redraw) { var chart = this.chart, key = this.coll, // xAxis or yAxis axisSeries = this.series, i = axisSeries.length; // Remove associated series (#2687) while (i--) { if (axisSeries[i]) { axisSeries[i].remove(false); } } // Remove the axis erase(chart.axes, this); erase(chart[key], this); chart.options[key].splice(this.options.index, 1); each(chart[key], function(axis, i) { // Re-index, #1706 axis.options.index = i; }); this.destroy(); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Update the axis title by options */ setTitle: function(newTitleOptions, redraw) { this.update({ title: newTitleOptions }, redraw); }, /** * Set new axis categories and optionally redraw * @param {Array} categories * @param {Boolean} redraw */ setCategories: function(categories, redraw) { this.update({ categories: categories }, redraw); } }); }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var animObject = H.animObject, color = H.color, each = H.each, extend = H.extend, isNumber = H.isNumber, LegendSymbolMixin = H.LegendSymbolMixin, merge = H.merge, noop = H.noop, pick = H.pick, Series = H.Series, seriesType = H.seriesType, stop = H.stop, svg = H.svg; /** * The column series type */ seriesType('column', 'line', { borderRadius: 0, //colorByPoint: undefined, groupPadding: 0.2, //grouping: true, marker: null, // point options are specified in the base options pointPadding: 0.1, //pointWidth: null, minPointLength: 0, cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories states: { hover: { halo: false } }, dataLabels: { align: null, // auto verticalAlign: null, // auto y: null }, softThreshold: false, startFromThreshold: true, // false doesn't work well: http://jsfiddle.net/highcharts/hz8fopan/14/ stickyTracking: false, tooltip: { distance: 6 }, threshold: 0, // Prototype members }, { cropShoulder: 0, directTouch: true, // When tooltip is not shared, this series (and derivatives) requires direct touch/hover. KD-tree does not apply. trackerGroups: ['group', 'dataLabelsGroup'], negStacks: true, // use separate negative stacks, unlike area stacks where a negative // point is substracted from previous (#1910) /** * Initialize the series */ init: function() { Series.prototype.init.apply(this, arguments); var series = this, chart = series.chart; // if the series is added dynamically, force redraw of other // series affected by a new column if (chart.hasRendered) { each(chart.series, function(otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } }, /** * Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding, * pointWidth etc. */ getColumnMetrics: function() { var series = this, options = series.options, xAxis = series.xAxis, yAxis = series.yAxis, reversedXAxis = xAxis.reversed, stackKey, stackGroups = {}, columnCount = 0; // Get the total number of column type series. // This is called on every series. Consider moving this logic to a // chart.orderStacks() function and call it on init, addSeries and removeSeries if (options.grouping === false) { columnCount = 1; } else { each(series.chart.series, function(otherSeries) { var otherOptions = otherSeries.options, otherYAxis = otherSeries.yAxis, columnIndex; if (otherSeries.type === series.type && otherSeries.visible && yAxis.len === otherYAxis.len && yAxis.pos === otherYAxis.pos) { // #642, #2086 if (otherOptions.stacking) { stackKey = otherSeries.stackKey; if (stackGroups[stackKey] === undefined) { stackGroups[stackKey] = columnCount++; } columnIndex = stackGroups[stackKey]; } else if (otherOptions.grouping !== false) { // #1162 columnIndex = columnCount++; } otherSeries.columnIndex = columnIndex; } }); } var categoryWidth = Math.min( Math.abs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || xAxis.tickInterval || 1), // #2610 xAxis.len // #1535 ), groupPadding = categoryWidth * options.groupPadding, groupWidth = categoryWidth - 2 * groupPadding, pointOffsetWidth = groupWidth / columnCount, pointWidth = Math.min( options.maxPointWidth || xAxis.len, pick(options.pointWidth, pointOffsetWidth * (1 - 2 * options.pointPadding)) ), pointPadding = (pointOffsetWidth - pointWidth) / 2, colIndex = (series.columnIndex || 0) + (reversedXAxis ? 1 : 0), // #1251, #3737 pointXOffset = pointPadding + (groupPadding + colIndex * pointOffsetWidth - (categoryWidth / 2)) * (reversedXAxis ? -1 : 1); // Save it for reading in linked series (Error bars particularly) series.columnMetrics = { width: pointWidth, offset: pointXOffset }; return series.columnMetrics; }, /** * Make the columns crisp. The edges are rounded to the nearest full pixel. */ crispCol: function(x, y, w, h) { var chart = this.chart, borderWidth = this.borderWidth, xCrisp = -(borderWidth % 2 ? 0.5 : 0), yCrisp = borderWidth % 2 ? 0.5 : 1, right, bottom, fromTop; if (chart.inverted && chart.renderer.isVML) { yCrisp += 1; } // Horizontal. We need to first compute the exact right edge, then round it // and compute the width from there. right = Math.round(x + w) + xCrisp; x = Math.round(x) + xCrisp; w = right - x; // Vertical bottom = Math.round(y + h) + yCrisp; fromTop = Math.abs(y) <= 0.5 && bottom > 0.5; // #4504, #4656 y = Math.round(y) + yCrisp; h = bottom - y; // Top edges are exceptions if (fromTop && h) { // #5146 y -= 1; h += 1; } return { x: x, y: y, width: w, height: h }; }, /** * Translate each point to the plot area coordinate system and find shape positions */ translate: function() { var series = this, chart = series.chart, options = series.options, dense = series.dense = series.closestPointRange * series.xAxis.transA < 2, borderWidth = series.borderWidth = pick( options.borderWidth, dense ? 0 : 1 // #3635 ), yAxis = series.yAxis, threshold = options.threshold, translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold), minPointLength = pick(options.minPointLength, 5), metrics = series.getColumnMetrics(), pointWidth = metrics.width, seriesBarW = series.barW = Math.max(pointWidth, 1 + 2 * borderWidth), // postprocessed for border width pointXOffset = series.pointXOffset = metrics.offset; if (chart.inverted) { translatedThreshold -= 0.5; // #3355 } // When the pointPadding is 0, we want the columns to be packed tightly, so we allow individual // columns to have individual sizes. When pointPadding is greater, we strive for equal-width // columns (#2694). if (options.pointPadding) { seriesBarW = Math.ceil(seriesBarW); } Series.prototype.translate.apply(series); // Record the new values each(series.points, function(point) { var yBottom = pick(point.yBottom, translatedThreshold), safeDistance = 999 + Math.abs(yBottom), plotY = Math.min(Math.max(-safeDistance, point.plotY), yAxis.len + safeDistance), // Don't draw too far outside plot area (#1303, #2241, #4264) barX = point.plotX + pointXOffset, barW = seriesBarW, barY = Math.min(plotY, yBottom), up, barH = Math.max(plotY, yBottom) - barY; // Handle options.minPointLength if (Math.abs(barH) < minPointLength) { if (minPointLength) { barH = minPointLength; up = (!yAxis.reversed && !point.negative) || (yAxis.reversed && point.negative); barY = Math.abs(barY - translatedThreshold) > minPointLength ? // stacked yBottom - minPointLength : // keep position translatedThreshold - (up ? minPointLength : 0); // #1485, #4051 } } // Cache for access in polar point.barX = barX; point.pointWidth = pointWidth; // Fix the tooltip on center of grouped columns (#1216, #424, #3648) point.tooltipPos = chart.inverted ? [yAxis.len + yAxis.pos - chart.plotLeft - plotY, series.xAxis.len - barX - barW / 2, barH] : [barX + barW / 2, plotY + yAxis.pos - chart.plotTop, barH]; // Register shape type and arguments to be used in drawPoints point.shapeType = 'rect'; point.shapeArgs = series.crispCol.apply( series, point.isNull ? [point.plotX, yAxis.len / 2, 0, 0] : // #3169, drilldown from null must have a position to work from [barX, barY, barW, barH] ); }); }, getSymbol: noop, /** * Use a solid rectangle like the area series types */ drawLegendSymbol: LegendSymbolMixin.drawRectangle, /** * Columns have no graph */ drawGraph: function() { this.group[this.dense ? 'addClass' : 'removeClass']('highcharts-dense-data'); }, /** * Draw the columns. For bars, the series.group is rotated, so the same coordinates * apply for columns and bars. This method is inherited by scatter series. * */ drawPoints: function() { var series = this, chart = this.chart, options = series.options, renderer = chart.renderer, animationLimit = options.animationLimit || 250, shapeArgs; // draw the columns each(series.points, function(point) { var plotY = point.plotY, graphic = point.graphic; if (isNumber(plotY) && point.y !== null) { shapeArgs = point.shapeArgs; if (graphic) { // update stop(graphic); graphic[chart.pointCount < animationLimit ? 'animate' : 'attr']( merge(shapeArgs) ); } else { point.graphic = graphic = renderer[point.shapeType](shapeArgs) .attr({ 'class': point.getClassName() }) .add(point.group || series.group); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } }); }, /** * Animate the column heights one by one from zero * @param {Boolean} init Whether to initialize the animation or run it */ animate: function(init) { var series = this, yAxis = this.yAxis, options = series.options, inverted = this.chart.inverted, attr = {}, translatedThreshold; if (svg) { // VML is too slow anyway if (init) { attr.scaleY = 0.001; translatedThreshold = Math.min(yAxis.pos + yAxis.len, Math.max(yAxis.pos, yAxis.toPixels(options.threshold))); if (inverted) { attr.translateX = translatedThreshold - yAxis.len; } else { attr.translateY = translatedThreshold; } series.group.attr(attr); } else { // run the animation attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos; series.group.animate(attr, extend(animObject(series.options.animation), { // Do the scale synchronously to ensure smooth updating (#5030) step: function(val, fx) { series.group.attr({ scaleY: Math.max(0.001, fx.pos) // #5250 }); } })); // delete this function to allow it only once series.animate = null; } } }, /** * Remove this series from the chart */ remove: function() { var series = this, chart = series.chart; // column and bar series affects other series of the same type // as they are either stacked or grouped if (chart.hasRendered) { each(chart.series, function(otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } Series.prototype.remove.apply(series, arguments); } }); }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var Series = H.Series, seriesType = H.seriesType; /** * The scatter series type */ seriesType('scatter', 'line', { lineWidth: 0, marker: { enabled: true // Overrides auto-enabling in line series (#3647) }, tooltip: { headerFormat: '<span style="color:{point.color}">\u25CF</span> <span style="font-size: 0.85em"> {series.name}</span><br/>', pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>' } // Prototype members }, { sorted: false, requireSorting: false, noSharedTooltip: true, trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'], takeOrdinalPosition: false, // #2342 kdDimensions: 2, drawGraph: function() { if (this.options.lineWidth) { Series.prototype.drawGraph.call(this); } } }); }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var addEvent = H.addEvent, arrayMax = H.arrayMax, defined = H.defined, each = H.each, extend = H.extend, format = H.format, map = H.map, merge = H.merge, noop = H.noop, pick = H.pick, relativeLength = H.relativeLength, Series = H.Series, seriesTypes = H.seriesTypes, stableSort = H.stableSort, stop = H.stop; /** * Generatl distribution algorithm for distributing labels of differing size along a * confined length in two dimensions. The algorithm takes an array of objects containing * a size, a target and a rank. It will place the labels as close as possible to their * targets, skipping the lowest ranked labels if necessary. */ H.distribute = function(boxes, len) { var i, overlapping = true, origBoxes = boxes, // Original array will be altered with added .pos restBoxes = [], // The outranked overshoot box, target, total = 0; function sortByTarget(a, b) { return a.target - b.target; } // If the total size exceeds the len, remove those boxes with the lowest rank i = boxes.length; while (i--) { total += boxes[i].size; } // Sort by rank, then slice away overshoot if (total > len) { stableSort(boxes, function(a, b) { return (b.rank || 0) - (a.rank || 0); }); i = 0; total = 0; while (total <= len) { total += boxes[i].size; i++; } restBoxes = boxes.splice(i - 1, boxes.length); } // Order by target stableSort(boxes, sortByTarget); // So far we have been mutating the original array. Now // create a copy with target arrays boxes = map(boxes, function(box) { return { size: box.size, targets: [box.target] }; }); while (overlapping) { // Initial positions: target centered in box i = boxes.length; while (i--) { box = boxes[i]; // Composite box, average of targets target = (Math.min.apply(0, box.targets) + Math.max.apply(0, box.targets)) / 2; box.pos = Math.min(Math.max(0, target - box.size / 2), len - box.size); } // Detect overlap and join boxes i = boxes.length; overlapping = false; while (i--) { if (i > 0 && boxes[i - 1].pos + boxes[i - 1].size > boxes[i].pos) { // Overlap boxes[i - 1].size += boxes[i].size; // Add this size to the previous box boxes[i - 1].targets = boxes[i - 1].targets.concat(boxes[i].targets); // Overlapping right, push left if (boxes[i - 1].pos + boxes[i - 1].size > len) { boxes[i - 1].pos = len - boxes[i - 1].size; } boxes.splice(i, 1); // Remove this item overlapping = true; } } } // Now the composite boxes are placed, we need to put the original boxes within them i = 0; each(boxes, function(box) { var posInCompositeBox = 0; each(box.targets, function() { origBoxes[i].pos = box.pos + posInCompositeBox; posInCompositeBox += origBoxes[i].size; i++; }); }); // Add the rest (hidden) boxes and sort by target origBoxes.push.apply(origBoxes, restBoxes); stableSort(origBoxes, sortByTarget); }; /** * Draw the data labels */ Series.prototype.drawDataLabels = function() { var series = this, seriesOptions = series.options, options = seriesOptions.dataLabels, points = series.points, pointOptions, generalOptions, hasRendered = series.hasRendered || 0, str, dataLabelsGroup, defer = pick(options.defer, true), renderer = series.chart.renderer; if (options.enabled || series._hasPointLabels) { // Process default alignment of data labels for columns if (series.dlProcessOptions) { series.dlProcessOptions(options); } // Create a separate group for the data labels to avoid rotation dataLabelsGroup = series.plotGroup( 'dataLabelsGroup', 'data-labels', defer && !hasRendered ? 'hidden' : 'visible', // #5133 options.zIndex || 6 ); if (defer) { dataLabelsGroup.attr({ opacity: +hasRendered }); // #3300 if (!hasRendered) { addEvent(series, 'afterAnimate', function() { if (series.visible) { // #2597, #3023, #3024 dataLabelsGroup.show(true); } dataLabelsGroup[seriesOptions.animation ? 'animate' : 'attr']({ opacity: 1 }, { duration: 200 }); }); } } // Make the labels for each point generalOptions = options; each(points, function(point) { var enabled, dataLabel = point.dataLabel, labelConfig, attr, name, rotation, connector = point.connector, isNew = true, style, moreStyle = {}; // Determine if each data label is enabled pointOptions = point.dlOptions || (point.options && point.options.dataLabels); // dlOptions is used in treemaps enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled) && point.y !== null; // #2282, #4641 // If the point is outside the plot area, destroy it. #678, #820 if (dataLabel && !enabled) { point.dataLabel = dataLabel.destroy(); // Individual labels are disabled if the are explicitly disabled // in the point options, or if they fall outside the plot area. } else if (enabled) { // Create individual options structure that can be extended without // affecting others options = merge(generalOptions, pointOptions); style = options.style; rotation = options.rotation; // Get the string labelConfig = point.getLabelConfig(); str = options.format ? format(options.format, labelConfig) : options.formatter.call(labelConfig, options); // update existing label if (dataLabel) { if (defined(str)) { dataLabel .attr({ text: str }); isNew = false; } else { // #1437 - the label is shown conditionally point.dataLabel = dataLabel = dataLabel.destroy(); if (connector) { point.connector = connector.destroy(); } } // create new label } else if (defined(str)) { attr = { //align: align, r: options.borderRadius || 0, rotation: rotation, padding: options.padding, zIndex: 1 }; // Remove unused attributes (#947) for (name in attr) { if (attr[name] === undefined) { delete attr[name]; } } dataLabel = point.dataLabel = renderer[rotation ? 'text' : 'label']( // labels don't support rotation str, 0, -9999, options.shape, null, null, options.useHTML, null, 'data-label' ) .attr(attr); dataLabel.addClass('highcharts-data-label-color-' + point.colorIndex + ' ' + (options.className || '')); dataLabel.add(dataLabelsGroup); } if (dataLabel) { // Now the data label is created and placed at 0,0, so we need to align it series.alignDataLabel(point, dataLabel, options, null, isNew); } } }); } }; /** * Align each individual data label */ Series.prototype.alignDataLabel = function(point, dataLabel, options, alignTo, isNew) { var chart = this.chart, inverted = chart.inverted, plotX = pick(point.plotX, -9999), plotY = pick(point.plotY, -9999), bBox = dataLabel.getBBox(), fontSize, baseline, rotation = options.rotation, normRotation, negRotation, align = options.align, rotCorr, // rotation correction // Math.round for rounding errors (#2683), alignTo to allow column labels (#2700) visible = this.visible && (point.series.forceDL || chart.isInsidePlot(plotX, Math.round(plotY), inverted) || (alignTo && chart.isInsidePlot(plotX, inverted ? alignTo.x + 1 : alignTo.y + alignTo.height - 1, inverted))), alignAttr, // the final position; justify = pick(options.overflow, 'justify') === 'justify'; if (visible) { baseline = chart.renderer.fontMetrics(fontSize, dataLabel).b; // The alignment box is a singular point alignTo = extend({ x: inverted ? chart.plotWidth - plotY : plotX, y: Math.round(inverted ? chart.plotHeight - plotX : plotY), width: 0, height: 0 }, alignTo); // Add the text size for alignment calculation extend(options, { width: bBox.width, height: bBox.height }); // Allow a hook for changing alignment in the last moment, then do the alignment if (rotation) { justify = false; // Not supported for rotated text rotCorr = chart.renderer.rotCorr(baseline, rotation); // #3723 alignAttr = { x: alignTo.x + options.x + alignTo.width / 2 + rotCorr.x, y: alignTo.y + options.y + { top: 0, middle: 0.5, bottom: 1 }[options.verticalAlign] * alignTo.height }; dataLabel[isNew ? 'attr' : 'animate'](alignAttr) .attr({ // #3003 align: align }); // Compensate for the rotated label sticking out on the sides normRotation = (rotation + 720) % 360; negRotation = normRotation > 180 && normRotation < 360; if (align === 'left') { alignAttr.y -= negRotation ? bBox.height : 0; } else if (align === 'center') { alignAttr.x -= bBox.width / 2; alignAttr.y -= bBox.height / 2; } else if (align === 'right') { alignAttr.x -= bBox.width; alignAttr.y -= negRotation ? 0 : bBox.height; } } else { dataLabel.align(options, null, alignTo); alignAttr = dataLabel.alignAttr; } // Handle justify or crop if (justify) { this.justifyDataLabel(dataLabel, options, alignAttr, bBox, alignTo, isNew); // Now check that the data label is within the plot area } else if (pick(options.crop, true)) { visible = chart.isInsidePlot(alignAttr.x, alignAttr.y) && chart.isInsidePlot(alignAttr.x + bBox.width, alignAttr.y + bBox.height); } // When we're using a shape, make it possible with a connector or an arrow pointing to thie point if (options.shape && !rotation) { dataLabel.attr({ anchorX: point.plotX, anchorY: point.plotY }); } } // Show or hide based on the final aligned position if (!visible) { stop(dataLabel); dataLabel.attr({ y: -9999 }); dataLabel.placed = false; // don't animate back in } }; /** * If data labels fall partly outside the plot area, align them back in, in a way that * doesn't hide the point. */ Series.prototype.justifyDataLabel = function(dataLabel, options, alignAttr, bBox, alignTo, isNew) { var chart = this.chart, align = options.align, verticalAlign = options.verticalAlign, off, justified, padding = dataLabel.box ? 0 : (dataLabel.padding || 0); // Off left off = alignAttr.x + padding; if (off < 0) { if (align === 'right') { options.align = 'left'; } else { options.x = -off; } justified = true; } // Off right off = alignAttr.x + bBox.width - padding; if (off > chart.plotWidth) { if (align === 'left') { options.align = 'right'; } else { options.x = chart.plotWidth - off; } justified = true; } // Off top off = alignAttr.y + padding; if (off < 0) { if (verticalAlign === 'bottom') { options.verticalAlign = 'top'; } else { options.y = -off; } justified = true; } // Off bottom off = alignAttr.y + bBox.height - padding; if (off > chart.plotHeight) { if (verticalAlign === 'top') { options.verticalAlign = 'bottom'; } else { options.y = chart.plotHeight - off; } justified = true; } if (justified) { dataLabel.placed = !isNew; dataLabel.align(options, null, alignTo); } }; /** * Override the base drawDataLabels method by pie specific functionality */ if (seriesTypes.pie) { seriesTypes.pie.prototype.drawDataLabels = function() { var series = this, data = series.data, point, chart = series.chart, options = series.options.dataLabels, connectorPadding = pick(options.connectorPadding, 10), connectorWidth = pick(options.connectorWidth, 1), plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, connector, distanceOption = options.distance, seriesCenter = series.center, radius = seriesCenter[2] / 2, centerY = seriesCenter[1], outside = distanceOption > 0, dataLabel, dataLabelWidth, labelPos, labelHeight, halves = [ // divide the points into right and left halves for anti collision [], // right [] // left ], x, y, visibility, j, overflow = [0, 0, 0, 0]; // top, right, bottom, left // get out if not enabled if (!series.visible || (!options.enabled && !series._hasPointLabels)) { return; } // run parent method Series.prototype.drawDataLabels.apply(series); each(data, function(point) { if (point.dataLabel && point.visible) { // #407, #2510 // Arrange points for detection collision halves[point.half].push(point); // Reset positions (#4905) point.dataLabel._pos = null; } }); /* Loop over the points in each half, starting from the top and bottom * of the pie to detect overlapping labels. */ each(halves, function(points, i) { var top, bottom, length = points.length, positions, naturalY, size; if (!length) { return; } // Sort by angle series.sortByAngle(points, i - 0.5); // Only do anti-collision when we are outside the pie and have connectors (#856) if (distanceOption > 0) { top = Math.max(0, centerY - radius - distanceOption); bottom = Math.min(centerY + radius + distanceOption, chart.plotHeight); positions = map(points, function(point) { if (point.dataLabel) { size = point.dataLabel.getBBox().height || 21; return { target: point.labelPos[1] - top + size / 2, size: size, rank: point.y }; } }); H.distribute(positions, bottom + size - top); } // now the used slots are sorted, fill them up sequentially for (j = 0; j < length; j++) { point = points[j]; labelPos = point.labelPos; dataLabel = point.dataLabel; visibility = point.visible === false ? 'hidden' : 'inherit'; naturalY = labelPos[1]; if (positions) { if (positions[j].pos === undefined) { visibility = 'hidden'; } else { labelHeight = positions[j].size; y = top + positions[j].pos; } } else { y = naturalY; } // get the x - use the natural x position for labels near the top and bottom, to prevent the top // and botton slice connectors from touching each other on either side if (options.justify) { x = seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption); } else { x = series.getX(y < top + 2 || y > bottom - 2 ? naturalY : y, i); } // Record the placement and visibility dataLabel._attr = { visibility: visibility, align: labelPos[6] }; dataLabel._pos = { x: x + options.x + ({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0), y: y + options.y - 10 // 10 is for the baseline (label vs text) }; labelPos.x = x; labelPos.y = y; // Detect overflowing data labels if (series.options.size === null) { dataLabelWidth = dataLabel.width; // Overflow left if (x - dataLabelWidth < connectorPadding) { overflow[3] = Math.max(Math.round(dataLabelWidth - x + connectorPadding), overflow[3]); // Overflow right } else if (x + dataLabelWidth > plotWidth - connectorPadding) { overflow[1] = Math.max(Math.round(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]); } // Overflow top if (y - labelHeight / 2 < 0) { overflow[0] = Math.max(Math.round(-y + labelHeight / 2), overflow[0]); // Overflow left } else if (y + labelHeight / 2 > plotHeight) { overflow[2] = Math.max(Math.round(y + labelHeight / 2 - plotHeight), overflow[2]); } } } // for each point }); // for each half // Do not apply the final placement and draw the connectors until we have verified // that labels are not spilling over. if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) { // Place the labels in the final position this.placeDataLabels(); // Draw the connectors if (outside && connectorWidth) { each(this.points, function(point) { var isNew; connector = point.connector; dataLabel = point.dataLabel; if (dataLabel && dataLabel._pos && point.visible) { visibility = dataLabel._attr.visibility; isNew = !connector; if (isNew) { point.connector = connector = chart.renderer.path() .addClass('highcharts-data-label-connector highcharts-color-' + point.colorIndex) .add(series.dataLabelsGroup); } connector[isNew ? 'attr' : 'animate']({ d: series.connectorPath(point.labelPos) }); connector.attr('visibility', visibility); } else if (connector) { point.connector = connector.destroy(); } }); } } }; /** * Extendable method for getting the path of the connector between the data label * and the pie slice. */ seriesTypes.pie.prototype.connectorPath = function(labelPos) { var x = labelPos.x, y = labelPos.y; return pick(this.options.softConnector, true) ? [ 'M', x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label 'C', x, y, // first break, next to the label 2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5], labelPos[2], labelPos[3], // second break 'L', labelPos[4], labelPos[5] // base ] : [ 'M', x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label 'L', labelPos[2], labelPos[3], // second break 'L', labelPos[4], labelPos[5] // base ]; }; /** * Perform the final placement of the data labels after we have verified that they * fall within the plot area. */ seriesTypes.pie.prototype.placeDataLabels = function() { each(this.points, function(point) { var dataLabel = point.dataLabel, _pos; if (dataLabel && point.visible) { _pos = dataLabel._pos; if (_pos) { dataLabel.attr(dataLabel._attr); dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos); dataLabel.moved = true; } else if (dataLabel) { dataLabel.attr({ y: -9999 }); } } }); }; seriesTypes.pie.prototype.alignDataLabel = noop; /** * Verify whether the data labels are allowed to draw, or we should run more translation and data * label positioning to keep them inside the plot area. Returns true when data labels are ready * to draw. */ seriesTypes.pie.prototype.verifyDataLabelOverflow = function(overflow) { var center = this.center, options = this.options, centerOption = options.center, minSize = options.minSize || 80, newSize = minSize, ret; // Handle horizontal size and center if (centerOption[0] !== null) { // Fixed center newSize = Math.max(center[2] - Math.max(overflow[1], overflow[3]), minSize); } else { // Auto center newSize = Math.max( center[2] - overflow[1] - overflow[3], // horizontal overflow minSize ); center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center } // Handle vertical size and center if (centerOption[1] !== null) { // Fixed center newSize = Math.max(Math.min(newSize, center[2] - Math.max(overflow[0], overflow[2])), minSize); } else { // Auto center newSize = Math.max( Math.min( newSize, center[2] - overflow[0] - overflow[2] // vertical overflow ), minSize ); center[1] += (overflow[0] - overflow[2]) / 2; // vertical center } // If the size must be decreased, we need to run translate and drawDataLabels again if (newSize < center[2]) { center[2] = newSize; center[3] = Math.min(relativeLength(options.innerSize || 0, newSize), newSize); // #3632 this.translate(center); if (this.drawDataLabels) { this.drawDataLabels(); } // Else, return true to indicate that the pie and its labels is within the plot area } else { ret = true; } return ret; }; } if (seriesTypes.column) { /** * Override the basic data label alignment by adjusting for the position of the column */ seriesTypes.column.prototype.alignDataLabel = function(point, dataLabel, options, alignTo, isNew) { var inverted = this.chart.inverted, series = point.series, dlBox = point.dlBox || point.shapeArgs, // data label box for alignment below = pick(point.below, point.plotY > pick(this.translatedThreshold, series.yAxis.len)), // point.below is used in range series inside = pick(options.inside, !!this.options.stacking), // draw it inside the box? overshoot; // Align to the column itself, or the top of it if (dlBox) { // Area range uses this method but not alignTo alignTo = merge(dlBox); if (alignTo.y < 0) { alignTo.height += alignTo.y; alignTo.y = 0; } overshoot = alignTo.y + alignTo.height - series.yAxis.len; if (overshoot > 0) { alignTo.height -= overshoot; } if (inverted) { alignTo = { x: series.yAxis.len - alignTo.y - alignTo.height, y: series.xAxis.len - alignTo.x - alignTo.width, width: alignTo.height, height: alignTo.width }; } // Compute the alignment box if (!inside) { if (inverted) { alignTo.x += below ? 0 : alignTo.width; alignTo.width = 0; } else { alignTo.y += below ? alignTo.height : 0; alignTo.height = 0; } } } // When alignment is undefined (typically columns and bars), display the individual // point below or above the point depending on the threshold options.align = pick( options.align, !inverted || inside ? 'center' : below ? 'right' : 'left' ); options.verticalAlign = pick( options.verticalAlign, inverted || inside ? 'middle' : below ? 'top' : 'bottom' ); // Call the parent method Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew); }; } }(Highcharts)); (function(H) { /** * (c) 2009-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; /** * Highcharts module to hide overlapping data labels. This module is included in Highcharts. */ var Chart = H.Chart, each = H.each, pick = H.pick, addEvent = H.addEvent; // Collect potensial overlapping data labels. Stack labels probably don't need to be // considered because they are usually accompanied by data labels that lie inside the columns. Chart.prototype.callbacks.push(function(chart) { function collectAndHide() { var labels = []; each(chart.series, function(series) { var dlOptions = series.options.dataLabels, collections = series.dataLabelCollections || ['dataLabel']; // Range series have two collections if ((dlOptions.enabled || series._hasPointLabels) && !dlOptions.allowOverlap && series.visible) { // #3866 each(collections, function(coll) { each(series.points, function(point) { if (point[coll]) { point[coll].labelrank = pick(point.labelrank, point.shapeArgs && point.shapeArgs.height); // #4118 labels.push(point[coll]); } }); }); } }); chart.hideOverlappingLabels(labels); } // Do it now ... collectAndHide(); // ... and after each chart redraw addEvent(chart, 'redraw', collectAndHide); }); /** * Hide overlapping labels. Labels are moved and faded in and out on zoom to provide a smooth * visual imression. */ Chart.prototype.hideOverlappingLabels = function(labels) { var len = labels.length, label, i, j, label1, label2, isIntersecting, pos1, pos2, parent1, parent2, padding, intersectRect = function(x1, y1, w1, h1, x2, y2, w2, h2) { return !( x2 > x1 + w1 || x2 + w2 < x1 || y2 > y1 + h1 || y2 + h2 < y1 ); }; // Mark with initial opacity for (i = 0; i < len; i++) { label = labels[i]; if (label) { label.oldOpacity = label.opacity; label.newOpacity = 1; } } // Prevent a situation in a gradually rising slope, that each label // will hide the previous one because the previous one always has // lower rank. labels.sort(function(a, b) { return (b.labelrank || 0) - (a.labelrank || 0); }); // Detect overlapping labels for (i = 0; i < len; i++) { label1 = labels[i]; for (j = i + 1; j < len; ++j) { label2 = labels[j]; if (label1 && label2 && label1.placed && label2.placed && label1.newOpacity !== 0 && label2.newOpacity !== 0) { pos1 = label1.alignAttr; pos2 = label2.alignAttr; parent1 = label1.parentGroup; // Different panes have different positions parent2 = label2.parentGroup; padding = 2 * (label1.box ? 0 : label1.padding); // Substract the padding if no background or border (#4333) isIntersecting = intersectRect( pos1.x + parent1.translateX, pos1.y + parent1.translateY, label1.width - padding, label1.height - padding, pos2.x + parent2.translateX, pos2.y + parent2.translateY, label2.width - padding, label2.height - padding ); if (isIntersecting) { (label1.labelrank < label2.labelrank ? label1 : label2).newOpacity = 0; } } } } // Hide or show each(labels, function(label) { var complete, newOpacity; if (label) { newOpacity = label.newOpacity; if (label.oldOpacity !== newOpacity && label.placed) { // Make sure the label is completely hidden to avoid catching clicks (#4362) if (newOpacity) { label.show(true); } else { complete = function() { label.hide(); }; } // Animate or set the opacity label.alignAttr.opacity = newOpacity; label[label.isOld ? 'animate' : 'attr'](label.alignAttr, null, complete); } label.isOld = true; } }); }; }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var Axis = H.Axis, each = H.each, pick = H.pick, wrap = H.wrap; /** * Override to use the extreme coordinates from the SVG shape, not the * data values */ wrap(Axis.prototype, 'getSeriesExtremes', function(proceed) { var isXAxis = this.isXAxis, dataMin, dataMax, xData = [], useMapGeometry; // Remove the xData array and cache it locally so that the proceed method doesn't use it if (isXAxis) { each(this.series, function(series, i) { if (series.useMapGeometry) { xData[i] = series.xData; series.xData = []; } }); } // Call base to reach normal cartesian series (like mappoint) proceed.call(this); // Run extremes logic for map and mapline if (isXAxis) { dataMin = pick(this.dataMin, Number.MAX_VALUE); dataMax = pick(this.dataMax, -Number.MAX_VALUE); each(this.series, function(series, i) { if (series.useMapGeometry) { dataMin = Math.min(dataMin, pick(series.minX, dataMin)); dataMax = Math.max(dataMax, pick(series.maxX, dataMin)); series.xData = xData[i]; // Reset xData array useMapGeometry = true; } }); if (useMapGeometry) { this.dataMin = dataMin; this.dataMax = dataMax; } } }); /** * Override axis translation to make sure the aspect ratio is always kept */ wrap(Axis.prototype, 'setAxisTranslation', function(proceed) { var chart = this.chart, mapRatio, plotRatio = chart.plotWidth / chart.plotHeight, adjustedAxisLength, xAxis = chart.xAxis[0], padAxis, fixTo, fixDiff, preserveAspectRatio; // Run the parent method proceed.call(this); // Check for map-like series if (this.coll === 'yAxis' && xAxis.transA !== undefined) { each(this.series, function(series) { if (series.preserveAspectRatio) { preserveAspectRatio = true; } }); } // On Y axis, handle both if (preserveAspectRatio) { // Use the same translation for both axes this.transA = xAxis.transA = Math.min(this.transA, xAxis.transA); mapRatio = plotRatio / ((xAxis.max - xAxis.min) / (this.max - this.min)); // What axis to pad to put the map in the middle padAxis = mapRatio < 1 ? this : xAxis; // Pad it adjustedAxisLength = (padAxis.max - padAxis.min) * padAxis.transA; padAxis.pixelPadding = padAxis.len - adjustedAxisLength; padAxis.minPixelPadding = padAxis.pixelPadding / 2; fixTo = padAxis.fixTo; if (fixTo) { fixDiff = fixTo[1] - padAxis.toValue(fixTo[0], true); fixDiff *= padAxis.transA; if (Math.abs(fixDiff) > padAxis.minPixelPadding || (padAxis.min === padAxis.dataMin && padAxis.max === padAxis.dataMax)) { // zooming out again, keep within restricted area fixDiff = 0; } padAxis.minPixelPadding -= fixDiff; } } }); /** * Override Axis.render in order to delete the fixTo prop */ wrap(Axis.prototype, 'render', function(proceed) { proceed.call(this); this.fixTo = null; }); }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var Axis = H.Axis, Chart = H.Chart, color = H.color, ColorAxis, each = H.each, extend = H.extend, isNumber = H.isNumber, Legend = H.Legend, LegendSymbolMixin = H.LegendSymbolMixin, noop = H.noop, merge = H.merge, pick = H.pick, wrap = H.wrap; /** * The ColorAxis object for inclusion in gradient legends */ ColorAxis = H.ColorAxis = function() { this.init.apply(this, arguments); }; extend(ColorAxis.prototype, Axis.prototype); extend(ColorAxis.prototype, { defaultColorAxisOptions: { lineWidth: 0, minPadding: 0, maxPadding: 0, gridLineWidth: 1, tickPixelInterval: 72, startOnTick: true, endOnTick: true, offset: 0, marker: { animation: { duration: 50 }, width: 0.01 }, labels: { overflow: 'justify' }, minColor: '#e6ebf5', maxColor: '#003399', tickLength: 5, showInLegend: true }, init: function(chart, userOptions) { var horiz = chart.options.legend.layout !== 'vertical', options; this.coll = 'colorAxis'; // Build the options options = merge(this.defaultColorAxisOptions, { side: horiz ? 2 : 1, reversed: !horiz }, userOptions, { opposite: !horiz, showEmpty: false, title: null }); Axis.prototype.init.call(this, chart, options); // Base init() pushes it to the xAxis array, now pop it again //chart[this.isXAxis ? 'xAxis' : 'yAxis'].pop(); // Prepare data classes if (userOptions.dataClasses) { this.initDataClasses(userOptions); } this.initStops(userOptions); // Override original axis properties this.horiz = horiz; this.zoomEnabled = false; // Add default values this.defaultLegendLength = 200; }, /* * Return an intermediate color between two colors, according to pos where 0 * is the from color and 1 is the to color. * NOTE: Changes here should be copied * to the same function in drilldown.src.js and solid-gauge-src.js. */ tweenColors: function(from, to, pos) { // Check for has alpha, because rgba colors perform worse due to lack of // support in WebKit. var hasAlpha, ret; // Unsupported color, return to-color (#3920) if (!to.rgba.length || !from.rgba.length) { ret = to.input || 'none'; // Interpolate } else { from = from.rgba; to = to.rgba; hasAlpha = (to[3] !== 1 || from[3] !== 1); ret = (hasAlpha ? 'rgba(' : 'rgb(') + Math.round(to[0] + (from[0] - to[0]) * (1 - pos)) + ',' + Math.round(to[1] + (from[1] - to[1]) * (1 - pos)) + ',' + Math.round(to[2] + (from[2] - to[2]) * (1 - pos)) + (hasAlpha ? (',' + (to[3] + (from[3] - to[3]) * (1 - pos))) : '') + ')'; } return ret; }, initDataClasses: function(userOptions) { var axis = this, chart = this.chart, dataClasses, colorCounter = 0, colorCount = chart.options.chart.colorCount, options = this.options, len = userOptions.dataClasses.length; this.dataClasses = dataClasses = []; this.legendItems = []; each(userOptions.dataClasses, function(dataClass, i) { var colors; dataClass = merge(dataClass); dataClasses.push(dataClass); if (!dataClass.color) { if (options.dataClassColor === 'category') { dataClass.colorIndex = colorCounter; // increase and loop back to zero colorCounter++; if (colorCounter === colorCount) { colorCounter = 0; } } else { dataClass.color = axis.tweenColors( color(options.minColor), color(options.maxColor), len < 2 ? 0.5 : i / (len - 1) // #3219 ); } } }); }, initStops: function(userOptions) { this.stops = userOptions.stops || [ [0, this.options.minColor], [1, this.options.maxColor] ]; each(this.stops, function(stop) { stop.color = color(stop[1]); }); }, /** * Extend the setOptions method to process extreme colors and color * stops. */ setOptions: function(userOptions) { Axis.prototype.setOptions.call(this, userOptions); this.options.crosshair = this.options.marker; }, setAxisSize: function() { var symbol = this.legendSymbol, chart = this.chart, legendOptions = chart.options.legend || {}, x, y, width, height; if (symbol) { this.left = x = symbol.attr('x'); this.top = y = symbol.attr('y'); this.width = width = symbol.attr('width'); this.height = height = symbol.attr('height'); this.right = chart.chartWidth - x - width; this.bottom = chart.chartHeight - y - height; this.len = this.horiz ? width : height; this.pos = this.horiz ? x : y; } else { // Fake length for disabled legend to avoid tick issues and such (#5205) this.len = (this.horiz ? legendOptions.symbolWidth : legendOptions.symbolHeight) || this.defaultLegendLength; } }, /** * Translate from a value to a color */ toColor: function(value, point) { var pos, stops = this.stops, from, to, color, dataClasses = this.dataClasses, dataClass, i; if (dataClasses) { i = dataClasses.length; while (i--) { dataClass = dataClasses[i]; from = dataClass.from; to = dataClass.to; if ((from === undefined || value >= from) && (to === undefined || value <= to)) { color = dataClass.color; if (point) { point.dataClass = i; point.colorIndex = dataClass.colorIndex; } break; } } } else { if (this.isLog) { value = this.val2lin(value); } pos = 1 - ((this.max - value) / ((this.max - this.min) || 1)); i = stops.length; while (i--) { if (pos > stops[i][0]) { break; } } from = stops[i] || stops[i + 1]; to = stops[i + 1] || from; // The position within the gradient pos = 1 - (to[0] - pos) / ((to[0] - from[0]) || 1); color = this.tweenColors( from.color, to.color, pos ); } return color; }, /** * Override the getOffset method to add the whole axis groups inside the legend. */ getOffset: function() { var group = this.legendGroup, sideOffset = this.chart.axisOffset[this.side]; if (group) { // Hook for the getOffset method to add groups to this parent group this.axisParent = group; // Call the base Axis.prototype.getOffset.call(this); // First time only if (!this.added) { this.added = true; this.labelLeft = 0; this.labelRight = this.width; } // Reset it to avoid color axis reserving space this.chart.axisOffset[this.side] = sideOffset; } }, /** * Create the color gradient */ setLegendColor: function() { var grad, horiz = this.horiz, options = this.options, reversed = this.reversed, one = reversed ? 1 : 0, zero = reversed ? 0 : 1; grad = horiz ? [one, 0, zero, 0] : [0, zero, 0, one]; // #3190 this.legendColor = { linearGradient: { x1: grad[0], y1: grad[1], x2: grad[2], y2: grad[3] }, stops: options.stops || [ [0, options.minColor], [1, options.maxColor] ] }; }, /** * The color axis appears inside the legend and has its own legend symbol */ drawLegendSymbol: function(legend, item) { var padding = legend.padding, legendOptions = legend.options, horiz = this.horiz, width = pick(legendOptions.symbolWidth, horiz ? this.defaultLegendLength : 12), height = pick(legendOptions.symbolHeight, horiz ? 12 : this.defaultLegendLength), labelPadding = pick(legendOptions.labelPadding, horiz ? 16 : 30), itemDistance = pick(legendOptions.itemDistance, 10); this.setLegendColor(); // Create the gradient item.legendSymbol = this.chart.renderer.rect( 0, legend.baseline - 11, width, height ).attr({ zIndex: 1 }).add(item.legendGroup); // Set how much space this legend item takes up this.legendItemWidth = width + padding + (horiz ? itemDistance : labelPadding); this.legendItemHeight = height + padding + (horiz ? labelPadding : 0); }, /** * Fool the legend */ setState: noop, visible: true, setVisible: noop, getSeriesExtremes: function() { var series; if (this.series.length) { series = this.series[0]; this.dataMin = series.valueMin; this.dataMax = series.valueMax; } }, drawCrosshair: function(e, point) { var plotX = point && point.plotX, plotY = point && point.plotY, crossPos, axisPos = this.pos, axisLen = this.len; if (point) { crossPos = this.toPixels(point[point.series.colorKey]); if (crossPos < axisPos) { crossPos = axisPos - 2; } else if (crossPos > axisPos + axisLen) { crossPos = axisPos + axisLen + 2; } point.plotX = crossPos; point.plotY = this.len - crossPos; Axis.prototype.drawCrosshair.call(this, e, point); point.plotX = plotX; point.plotY = plotY; if (this.cross) { this.cross .addClass('highcharts-coloraxis-marker') .add(this.legendGroup); } } }, getPlotLinePath: function(a, b, c, d, pos) { return isNumber(pos) ? // crosshairs only // #3969 pos can be 0 !! (this.horiz ? ['M', pos - 4, this.top - 6, 'L', pos + 4, this.top - 6, pos, this.top, 'Z'] : ['M', this.left, pos, 'L', this.left - 6, pos + 6, this.left - 6, pos - 6, 'Z']) : Axis.prototype.getPlotLinePath.call(this, a, b, c, d); }, update: function(newOptions, redraw) { var chart = this.chart, legend = chart.legend; each(this.series, function(series) { series.isDirtyData = true; // Needed for Axis.update when choropleth colors change }); // When updating data classes, destroy old items and make sure new ones are created (#3207) if (newOptions.dataClasses && legend.allItems) { each(legend.allItems, function(item) { if (item.isDataClass) { item.legendGroup.destroy(); } }); chart.isDirtyLegend = true; } // Keep the options structure updated for export. Unlike xAxis and yAxis, the colorAxis is // not an array. (#3207) chart.options[this.coll] = merge(this.userOptions, newOptions); Axis.prototype.update.call(this, newOptions, redraw); if (this.legendItem) { this.setLegendColor(); legend.colorizeItem(this, true); } }, /** * Get the legend item symbols for data classes */ getDataClassLegendSymbols: function() { var axis = this, chart = this.chart, legendItems = this.legendItems, legendOptions = chart.options.legend, valueDecimals = legendOptions.valueDecimals, valueSuffix = legendOptions.valueSuffix || '', name; if (!legendItems.length) { each(this.dataClasses, function(dataClass, i) { var vis = true, from = dataClass.from, to = dataClass.to; // Assemble the default name. This can be overridden by legend.options.labelFormatter name = ''; if (from === undefined) { name = '< '; } else if (to === undefined) { name = '> '; } if (from !== undefined) { name += H.numberFormat(from, valueDecimals) + valueSuffix; } if (from !== undefined && to !== undefined) { name += ' - '; } if (to !== undefined) { name += H.numberFormat(to, valueDecimals) + valueSuffix; } // Add a mock object to the legend items legendItems.push(extend({ chart: chart, name: name, options: {}, drawLegendSymbol: LegendSymbolMixin.drawRectangle, visible: true, setState: noop, isDataClass: true, setVisible: function() { vis = this.visible = !vis; each(axis.series, function(series) { each(series.points, function(point) { if (point.dataClass === i) { point.setVisible(vis); } }); }); chart.legend.colorizeItem(this, vis); } }, dataClass)); }); } return legendItems; }, name: '' // Prevents 'undefined' in legend in IE8 }); /** * Handle animation of the color attributes directly */ each(['fill', 'stroke'], function(prop) { H.Fx.prototype[prop + 'Setter'] = function() { this.elem.attr(prop, ColorAxis.prototype.tweenColors(color(this.start), color(this.end), this.pos)); }; }); /** * Extend the chart getAxes method to also get the color axis */ wrap(Chart.prototype, 'getAxes', function(proceed) { var options = this.options, colorAxisOptions = options.colorAxis; proceed.call(this); this.colorAxis = []; if (colorAxisOptions) { new ColorAxis(this, colorAxisOptions); // eslint-disable-line no-new } }); /** * Wrap the legend getAllItems method to add the color axis. This also removes the * axis' own series to prevent them from showing up individually. */ wrap(Legend.prototype, 'getAllItems', function(proceed) { var allItems = [], colorAxis = this.chart.colorAxis[0]; if (colorAxis && colorAxis.options) { if (colorAxis.options.showInLegend) { // Data classes if (colorAxis.options.dataClasses) { allItems = allItems.concat(colorAxis.getDataClassLegendSymbols()); // Gradient legend } else { // Add this axis on top allItems.push(colorAxis); } } // Don't add the color axis' series each(colorAxis.series, function(series) { series.options.showInLegend = false; }); } return allItems.concat(proceed.call(this)); }); wrap(Legend.prototype, 'colorizeItem', function(proceed, item, visible) { proceed.call(this, item, visible); if (visible && item.legendColor) { item.legendSymbol.attr({ fill: item.legendColor }); } }); }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var defined = H.defined, each = H.each, noop = H.noop, seriesTypes = H.seriesTypes; /** * Mixin for maps and heatmaps */ H.colorPointMixin = { /** * Color points have a value option that determines whether or not it is a null point */ isValid: function() { return this.value !== null; }, /** * Set the visibility of a single point */ setVisible: function(vis) { var point = this, method = vis ? 'show' : 'hide'; // Show and hide associated elements each(['graphic', 'dataLabel'], function(key) { if (point[key]) { point[key][method](); } }); } }; H.colorSeriesMixin = { pointArrayMap: ['value'], axisTypes: ['xAxis', 'yAxis', 'colorAxis'], optionalAxis: 'colorAxis', trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'], getSymbol: noop, parallelArrays: ['x', 'y', 'value'], colorKey: 'value', /** * In choropleth maps, the color is a result of the value, so this needs translation too */ translateColors: function() { var series = this, nullColor = this.options.nullColor, colorAxis = this.colorAxis, colorKey = this.colorKey; each(this.data, function(point) { var value = point[colorKey], color; color = point.options.color || (point.isNull ? nullColor : (colorAxis && value !== undefined) ? colorAxis.toColor(value, point) : point.color || series.color); if (color) { point.color = color; } }); }, /** * Get the color attibutes to apply on the graphic */ colorAttribs: function(point) { var ret = {}; if (defined(point.color)) { ret[this.colorProp || 'fill'] = point.color; } return ret; } }; }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var color = H.color, ColorAxis = H.ColorAxis, colorPointMixin = H.colorPointMixin, colorSeriesMixin = H.colorSeriesMixin, doc = H.doc, each = H.each, extend = H.extend, isNumber = H.isNumber, LegendSymbolMixin = H.LegendSymbolMixin, map = H.map, merge = H.merge, noop = H.noop, pick = H.pick, isArray = H.isArray, Point = H.Point, Series = H.Series, seriesType = H.seriesType, seriesTypes = H.seriesTypes, splat = H.splat; // The vector-effect attribute is not supported in IE <= 11 (at least), so we need // diffent logic (#3218) var supportsVectorEffect = doc.documentElement.style.vectorEffect !== undefined; /** * The MapAreaPoint object */ /** * Add the map series type */ seriesType('map', 'scatter', { allAreas: true, animation: false, // makes the complex shapes slow nullColor: '#f7f7f7', borderColor: '#cccccc', borderWidth: 1, marker: null, stickyTracking: false, joinBy: 'hc-key', dataLabels: { formatter: function() { // #2945 return this.point.value; }, inside: true, // for the color verticalAlign: 'middle', crop: false, overflow: false, padding: 0 }, turboThreshold: 0, tooltip: { followPointer: true, pointFormat: '{point.name}: {point.value}<br/>' }, states: { normal: { animation: true }, hover: { brightness: 0.2, halo: null }, select: { color: '#cccccc' } } // Prototype members }, merge(colorSeriesMixin, { type: 'map', supportsDrilldown: true, getExtremesFromAll: true, useMapGeometry: true, // get axis extremes from paths, not values forceDL: true, searchPoint: noop, directTouch: true, // When tooltip is not shared, this series (and derivatives) requires direct touch/hover. KD-tree does not apply. preserveAspectRatio: true, // X axis and Y axis must have same translation slope pointArrayMap: ['value'], /** * Get the bounding box of all paths in the map combined. */ getBox: function(paths) { var MAX_VALUE = Number.MAX_VALUE, maxX = -MAX_VALUE, minX = MAX_VALUE, maxY = -MAX_VALUE, minY = MAX_VALUE, minRange = MAX_VALUE, xAxis = this.xAxis, yAxis = this.yAxis, hasBox; // Find the bounding box each(paths || [], function(point) { if (point.path) { if (typeof point.path === 'string') { point.path = H.splitPath(point.path); } var path = point.path || [], i = path.length, even = false, // while loop reads from the end pointMaxX = -MAX_VALUE, pointMinX = MAX_VALUE, pointMaxY = -MAX_VALUE, pointMinY = MAX_VALUE, properties = point.properties; // The first time a map point is used, analyze its box if (!point._foundBox) { while (i--) { if (isNumber(path[i])) { if (even) { // even = x pointMaxX = Math.max(pointMaxX, path[i]); pointMinX = Math.min(pointMinX, path[i]); } else { // odd = Y pointMaxY = Math.max(pointMaxY, path[i]); pointMinY = Math.min(pointMinY, path[i]); } even = !even; } } // Cache point bounding box for use to position data labels, bubbles etc point._midX = pointMinX + (pointMaxX - pointMinX) * (point.middleX || (properties && properties['hc-middle-x']) || 0.5); // pick is slower and very marginally needed point._midY = pointMinY + (pointMaxY - pointMinY) * (point.middleY || (properties && properties['hc-middle-y']) || 0.5); point._maxX = pointMaxX; point._minX = pointMinX; point._maxY = pointMaxY; point._minY = pointMinY; point.labelrank = pick(point.labelrank, (pointMaxX - pointMinX) * (pointMaxY - pointMinY)); point._foundBox = true; } maxX = Math.max(maxX, point._maxX); minX = Math.min(minX, point._minX); maxY = Math.max(maxY, point._maxY); minY = Math.min(minY, point._minY); minRange = Math.min(point._maxX - point._minX, point._maxY - point._minY, minRange); hasBox = true; } }); // Set the box for the whole series if (hasBox) { this.minY = Math.min(minY, pick(this.minY, MAX_VALUE)); this.maxY = Math.max(maxY, pick(this.maxY, -MAX_VALUE)); this.minX = Math.min(minX, pick(this.minX, MAX_VALUE)); this.maxX = Math.max(maxX, pick(this.maxX, -MAX_VALUE)); // If no minRange option is set, set the default minimum zooming range to 5 times the // size of the smallest element if (xAxis && xAxis.options.minRange === undefined) { xAxis.minRange = Math.min(5 * minRange, (this.maxX - this.minX) / 5, xAxis.minRange || MAX_VALUE); } if (yAxis && yAxis.options.minRange === undefined) { yAxis.minRange = Math.min(5 * minRange, (this.maxY - this.minY) / 5, yAxis.minRange || MAX_VALUE); } } }, getExtremes: function() { // Get the actual value extremes for colors Series.prototype.getExtremes.call(this, this.valueData); // Recalculate box on updated data if (this.chart.hasRendered && this.isDirtyData) { this.getBox(this.options.data); } this.valueMin = this.dataMin; this.valueMax = this.dataMax; // Extremes for the mock Y axis this.dataMin = this.minY; this.dataMax = this.maxY; }, /** * Translate the path so that it automatically fits into the plot area box * @param {Object} path */ translatePath: function(path) { var series = this, even = false, // while loop reads from the end xAxis = series.xAxis, yAxis = series.yAxis, xMin = xAxis.min, xTransA = xAxis.transA, xMinPixelPadding = xAxis.minPixelPadding, yMin = yAxis.min, yTransA = yAxis.transA, yMinPixelPadding = yAxis.minPixelPadding, i, ret = []; // Preserve the original // Do the translation if (path) { i = path.length; while (i--) { if (isNumber(path[i])) { ret[i] = even ? (path[i] - xMin) * xTransA + xMinPixelPadding : (path[i] - yMin) * yTransA + yMinPixelPadding; even = !even; } else { ret[i] = path[i]; } } } return ret; }, /** * Extend setData to join in mapData. If the allAreas option is true, all areas * from the mapData are used, and those that don't correspond to a data value * are given null values. */ setData: function(data, redraw, animation, updatePoints) { var options = this.options, chartOptions = this.chart.options.chart, globalMapData = chartOptions && chartOptions.map, mapData = options.mapData, joinBy = options.joinBy, joinByNull = joinBy === null, pointArrayMap = options.keys || this.pointArrayMap, dataUsed = [], mapMap = {}, mapPoint, transform, mapTransforms = this.chart.mapTransforms, props, i; // Collect mapData from chart options if not defined on series if (!mapData && globalMapData) { mapData = typeof globalMapData === 'string' ? H.maps[globalMapData] : globalMapData; } if (joinByNull) { joinBy = '_i'; } joinBy = this.joinBy = splat(joinBy); if (!joinBy[1]) { joinBy[1] = joinBy[0]; } // Pick up numeric values, add index // Convert Array point definitions to objects using pointArrayMap if (data) { each(data, function(val, i) { var ix = 0; if (isNumber(val)) { data[i] = { value: val }; } else if (isArray(val)) { data[i] = {}; // Automatically copy first item to hc-key if there is an extra leading string if (!options.keys && val.length > pointArrayMap.length && typeof val[0] === 'string') { data[i]['hc-key'] = val[0]; ++ix; } // Run through pointArrayMap and what's left of the point data array in parallel, copying over the values for (var j = 0; j < pointArrayMap.length; ++j, ++ix) { if (pointArrayMap[j]) { data[i][pointArrayMap[j]] = val[ix]; } } } if (joinByNull) { data[i]._i = i; } }); } this.getBox(data); // Pick up transform definitions for chart this.chart.mapTransforms = mapTransforms = chartOptions && chartOptions.mapTransforms || mapData && mapData['hc-transform'] || mapTransforms; // Cache cos/sin of transform rotation angle if (mapTransforms) { for (transform in mapTransforms) { if (mapTransforms.hasOwnProperty(transform) && transform.rotation) { transform.cosAngle = Math.cos(transform.rotation); transform.sinAngle = Math.sin(transform.rotation); } } } if (mapData) { if (mapData.type === 'FeatureCollection') { this.mapTitle = mapData.title; mapData = H.geojson(mapData, this.type, this); } this.mapData = mapData; this.mapMap = {}; for (i = 0; i < mapData.length; i++) { mapPoint = mapData[i]; props = mapPoint.properties; mapPoint._i = i; // Copy the property over to root for faster access if (joinBy[0] && props && props[joinBy[0]]) { mapPoint[joinBy[0]] = props[joinBy[0]]; } mapMap[mapPoint[joinBy[0]]] = mapPoint; } this.mapMap = mapMap; // Registered the point codes that actually hold data if (data && joinBy[1]) { each(data, function(point) { if (mapMap[point[joinBy[1]]]) { dataUsed.push(mapMap[point[joinBy[1]]]); } }); } if (options.allAreas) { this.getBox(mapData); data = data || []; // Registered the point codes that actually hold data if (joinBy[1]) { each(data, function(point) { dataUsed.push(point[joinBy[1]]); }); } // Add those map points that don't correspond to data, which will be drawn as null points dataUsed = '|' + map(dataUsed, function(point) { return point && point[joinBy[0]]; }).join('|') + '|'; // String search is faster than array.indexOf each(mapData, function(mapPoint) { if (!joinBy[0] || dataUsed.indexOf('|' + mapPoint[joinBy[0]] + '|') === -1) { data.push(merge(mapPoint, { value: null })); updatePoints = false; // #5050 - adding all areas causes the update optimization of setData to kick in, even though the point order has changed } }); } else { this.getBox(dataUsed); // Issue #4784 } } Series.prototype.setData.call(this, data, redraw, animation, updatePoints); }, /** * No graph for the map series */ drawGraph: noop, /** * We need the points' bounding boxes in order to draw the data labels, so * we skip it now and call it from drawPoints instead. */ drawDataLabels: noop, /** * Allow a quick redraw by just translating the area group. Used for zooming and panning * in capable browsers. */ doFullTranslate: function() { return this.isDirtyData || this.chart.isResizing || this.chart.renderer.isVML || !this.baseTrans; }, /** * Add the path option for data points. Find the max value for color calculation. */ translate: function() { var series = this, xAxis = series.xAxis, yAxis = series.yAxis, doFullTranslate = series.doFullTranslate(); series.generatePoints(); each(series.data, function(point) { // Record the middle point (loosely based on centroid), determined // by the middleX and middleY options. point.plotX = xAxis.toPixels(point._midX, true); point.plotY = yAxis.toPixels(point._midY, true); if (doFullTranslate) { point.shapeType = 'path'; point.shapeArgs = { d: series.translatePath(point.path) }; } }); series.translateColors(); }, /** * Get presentational attributes */ pointAttribs: function(point, state) { var attr = seriesTypes.column.prototype.pointAttribs.call(this, point, state); // Prevent flickering whan called from setState if (point.isFading) { delete attr.fill; } // If vector-effect is not supported, we set the stroke-width on the group element // and let all point graphics inherit. That way we don't have to iterate over all // points to update the stroke-width on zooming. TODO: Check unstyled if (supportsVectorEffect) { attr['vector-effect'] = 'non-scaling-stroke'; } else { attr['stroke-width'] = 'inherit'; } return attr; }, /** * Use the drawPoints method of column, that is able to handle simple shapeArgs. * Extend it by assigning the tooltip position. */ drawPoints: function() { var series = this, xAxis = series.xAxis, yAxis = series.yAxis, group = series.group, chart = series.chart, renderer = chart.renderer, scaleX, scaleY, translateX, translateY, baseTrans = this.baseTrans; // Set a group that handles transform during zooming and panning in order to preserve clipping // on series.group if (!series.transformGroup) { series.transformGroup = renderer.g() .attr({ scaleX: 1, scaleY: 1 }) .add(group); series.transformGroup.survive = true; } // Draw the shapes again if (series.doFullTranslate()) { // Individual point actions. TODO: Check unstyled. // Draw them in transformGroup series.group = series.transformGroup; seriesTypes.column.prototype.drawPoints.apply(series); series.group = group; // Reset // Add class names each(series.points, function(point) { if (point.graphic) { if (point.name) { point.graphic.addClass('highcharts-name-' + point.name.replace(/ /g, '-').toLowerCase()); } if (point.properties && point.properties['hc-key']) { point.graphic.addClass('highcharts-key-' + point.properties['hc-key'].toLowerCase()); } } }); // Set the base for later scale-zooming. The originX and originY properties are the // axis values in the plot area's upper left corner. this.baseTrans = { originX: xAxis.min - xAxis.minPixelPadding / xAxis.transA, originY: yAxis.min - yAxis.minPixelPadding / yAxis.transA + (yAxis.reversed ? 0 : yAxis.len / yAxis.transA), transAX: xAxis.transA, transAY: yAxis.transA }; // Reset transformation in case we're doing a full translate (#3789) this.transformGroup.animate({ translateX: 0, translateY: 0, scaleX: 1, scaleY: 1 }); // Just update the scale and transform for better performance } else { scaleX = xAxis.transA / baseTrans.transAX; scaleY = yAxis.transA / baseTrans.transAY; translateX = xAxis.toPixels(baseTrans.originX, true); translateY = yAxis.toPixels(baseTrans.originY, true); // Handle rounding errors in normal view (#3789) if (scaleX > 0.99 && scaleX < 1.01 && scaleY > 0.99 && scaleY < 1.01) { scaleX = 1; scaleY = 1; translateX = Math.round(translateX); translateY = Math.round(translateY); } this.transformGroup.animate({ translateX: translateX, translateY: translateY, scaleX: scaleX, scaleY: scaleY }); } // Set the stroke-width directly on the group element so the children inherit it. We need to use // setAttribute directly, because the stroke-widthSetter method expects a stroke color also to be // set. if (!supportsVectorEffect) { series.group.element.setAttribute( 'stroke-width', series.options[ (series.pointAttrToOptions && series.pointAttrToOptions['stroke-width']) || 'borderWidth' ] / (scaleX || 1) ); } this.drawMapDataLabels(); }, /** * Draw the data labels. Special for maps is the time that the data labels are drawn (after points), * and the clipping of the dataLabelsGroup. */ drawMapDataLabels: function() { Series.prototype.drawDataLabels.call(this); if (this.dataLabelsGroup) { this.dataLabelsGroup.clip(this.chart.clipRect); } }, /** * Override render to throw in an async call in IE8. Otherwise it chokes on the US counties demo. */ render: function() { var series = this, render = Series.prototype.render; // Give IE8 some time to breathe. if (series.chart.renderer.isVML && series.data.length > 3000) { setTimeout(function() { render.call(series); }); } else { render.call(series); } }, /** * The initial animation for the map series. By default, animation is disabled. * Animation of map shapes is not at all supported in VML browsers. */ animate: function(init) { var chart = this.chart, animation = this.options.animation, group = this.group, xAxis = this.xAxis, yAxis = this.yAxis, left = xAxis.pos, top = yAxis.pos; if (chart.renderer.isSVG) { if (animation === true) { animation = { duration: 1000 }; } // Initialize the animation if (init) { // Scale down the group and place it in the center group.attr({ translateX: left + xAxis.len / 2, translateY: top + yAxis.len / 2, scaleX: 0.001, // #1499 scaleY: 0.001 }); // Run the animation } else { group.animate({ translateX: left, translateY: top, scaleX: 1, scaleY: 1 }, animation); // Delete this function to allow it only once this.animate = null; } } }, /** * Animate in the new series from the clicked point in the old series. * Depends on the drilldown.js module */ animateDrilldown: function(init) { var toBox = this.chart.plotBox, level = this.chart.drilldownLevels[this.chart.drilldownLevels.length - 1], fromBox = level.bBox, animationOptions = this.chart.options.drilldown.animation, scale; if (!init) { scale = Math.min(fromBox.width / toBox.width, fromBox.height / toBox.height); level.shapeArgs = { scaleX: scale, scaleY: scale, translateX: fromBox.x, translateY: fromBox.y }; each(this.points, function(point) { if (point.graphic) { point.graphic .attr(level.shapeArgs) .animate({ scaleX: 1, scaleY: 1, translateX: 0, translateY: 0 }, animationOptions); } }); this.animate = null; } }, drawLegendSymbol: LegendSymbolMixin.drawRectangle, /** * When drilling up, pull out the individual point graphics from the lower series * and animate them into the origin point in the upper series. */ animateDrillupFrom: function(level) { seriesTypes.column.prototype.animateDrillupFrom.call(this, level); }, /** * When drilling up, keep the upper series invisible until the lower series has * moved into place */ animateDrillupTo: function(init) { seriesTypes.column.prototype.animateDrillupTo.call(this, init); } // Point class }), extend({ /** * Extend the Point object to split paths */ applyOptions: function(options, x) { var point = Point.prototype.applyOptions.call(this, options, x), series = this.series, joinBy = series.joinBy, mapPoint; if (series.mapData) { mapPoint = point[joinBy[1]] !== undefined && series.mapMap[point[joinBy[1]]]; if (mapPoint) { // This applies only to bubbles if (series.xyFromShape) { point.x = mapPoint._midX; point.y = mapPoint._midY; } extend(point, mapPoint); // copy over properties } else { point.value = point.value || null; } } return point; }, /** * Stop the fade-out */ onMouseOver: function(e) { clearTimeout(this.colorInterval); if (this.value !== null) { Point.prototype.onMouseOver.call(this, e); } else { //#3401 Tooltip doesn't hide when hovering over null points this.series.onMouseOut(e); } }, /** * Zoom the chart to view a specific area point */ zoomTo: function() { var point = this, series = point.series; series.xAxis.setExtremes( point._minX, point._maxX, false ); series.yAxis.setExtremes( point._minY, point._maxY, false ); series.chart.redraw(); } }, colorPointMixin)); }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var addEvent = H.addEvent, Chart = H.Chart, doc = H.doc, each = H.each, extend = H.extend, merge = H.merge, pick = H.pick, wrap = H.wrap; function stopEvent(e) { if (e) { if (e.preventDefault) { e.preventDefault(); } if (e.stopPropagation) { e.stopPropagation(); } e.cancelBubble = true; } } // Add events to the Chart object itself extend(Chart.prototype, { renderMapNavigation: function() { var chart = this, options = this.options.mapNavigation, buttons = options.buttons, n, button, buttonOptions, attr, states, hoverStates, selectStates, outerHandler = function(e) { this.handler.call(chart, e); stopEvent(e); // Stop default click event (#4444) }; if (pick(options.enableButtons, options.enabled) && !chart.renderer.forExport) { chart.mapNavButtons = []; for (n in buttons) { if (buttons.hasOwnProperty(n)) { buttonOptions = merge(options.buttonOptions, buttons[n]); button = chart.renderer.button( buttonOptions.text, 0, 0, outerHandler, attr, hoverStates, selectStates, 0, n === 'zoomIn' ? 'topbutton' : 'bottombutton' ) .addClass('highcharts-map-navigation') .attr({ width: buttonOptions.width, height: buttonOptions.height, title: chart.options.lang[n], padding: buttonOptions.padding, zIndex: 5 }) .add(); button.handler = buttonOptions.onclick; button.align(extend(buttonOptions, { width: button.width, height: 2 * button.height }), null, buttonOptions.alignTo); addEvent(button.element, 'dblclick', stopEvent); // Stop double click event (#4444) chart.mapNavButtons.push(button); } } } }, /** * Fit an inner box to an outer. If the inner box overflows left or right, align it to the sides of the * outer. If it overflows both sides, fit it within the outer. This is a pattern that occurs more places * in Highcharts, perhaps it should be elevated to a common utility function. */ fitToBox: function(inner, outer) { each([ ['x', 'width'], ['y', 'height'] ], function(dim) { var pos = dim[0], size = dim[1]; if (inner[pos] + inner[size] > outer[pos] + outer[size]) { // right overflow if (inner[size] > outer[size]) { // the general size is greater, fit fully to outer inner[size] = outer[size]; inner[pos] = outer[pos]; } else { // align right inner[pos] = outer[pos] + outer[size] - inner[size]; } } if (inner[size] > outer[size]) { inner[size] = outer[size]; } if (inner[pos] < outer[pos]) { inner[pos] = outer[pos]; } }); return inner; }, /** * Zoom the map in or out by a certain amount. Less than 1 zooms in, greater than 1 zooms out. */ mapZoom: function(howMuch, centerXArg, centerYArg, mouseX, mouseY) { /*if (this.isMapZooming) { this.mapZoomQueue = arguments; return; }*/ var chart = this, xAxis = chart.xAxis[0], xRange = xAxis.max - xAxis.min, centerX = pick(centerXArg, xAxis.min + xRange / 2), newXRange = xRange * howMuch, yAxis = chart.yAxis[0], yRange = yAxis.max - yAxis.min, centerY = pick(centerYArg, yAxis.min + yRange / 2), newYRange = yRange * howMuch, fixToX = mouseX ? ((mouseX - xAxis.pos) / xAxis.len) : 0.5, fixToY = mouseY ? ((mouseY - yAxis.pos) / yAxis.len) : 0.5, newXMin = centerX - newXRange * fixToX, newYMin = centerY - newYRange * fixToY, newExt = chart.fitToBox({ x: newXMin, y: newYMin, width: newXRange, height: newYRange }, { x: xAxis.dataMin, y: yAxis.dataMin, width: xAxis.dataMax - xAxis.dataMin, height: yAxis.dataMax - yAxis.dataMin }), zoomOut = newExt.x <= xAxis.dataMin && newExt.width >= xAxis.dataMax - xAxis.dataMin && newExt.y <= yAxis.dataMin && newExt.height >= yAxis.dataMax - yAxis.dataMin; // When mousewheel zooming, fix the point under the mouse if (mouseX) { xAxis.fixTo = [mouseX - xAxis.pos, centerXArg]; } if (mouseY) { yAxis.fixTo = [mouseY - yAxis.pos, centerYArg]; } // Zoom if (howMuch !== undefined && !zoomOut) { xAxis.setExtremes(newExt.x, newExt.x + newExt.width, false); yAxis.setExtremes(newExt.y, newExt.y + newExt.height, false); // Reset zoom } else { xAxis.setExtremes(undefined, undefined, false); yAxis.setExtremes(undefined, undefined, false); } // Prevent zooming until this one is finished animating /*chart.holdMapZoom = true; setTimeout(function () { chart.holdMapZoom = false; }, 200);*/ /*delay = animation ? animation.duration || 500 : 0; if (delay) { chart.isMapZooming = true; setTimeout(function () { chart.isMapZooming = false; if (chart.mapZoomQueue) { chart.mapZoom.apply(chart, chart.mapZoomQueue); } chart.mapZoomQueue = null; }, delay); }*/ chart.redraw(); } }); /** * Extend the Chart.render method to add zooming and panning */ wrap(Chart.prototype, 'render', function(proceed) { var chart = this, mapNavigation = chart.options.mapNavigation; // Render the plus and minus buttons. Doing this before the shapes makes getBBox much quicker, at least in Chrome. chart.renderMapNavigation(); proceed.call(chart); // Add the double click event if (pick(mapNavigation.enableDoubleClickZoom, mapNavigation.enabled) || mapNavigation.enableDoubleClickZoomTo) { addEvent(chart.container, 'dblclick', function(e) { chart.pointer.onContainerDblClick(e); }); } // Add the mousewheel event if (pick(mapNavigation.enableMouseWheelZoom, mapNavigation.enabled)) { addEvent(chart.container, doc.onmousewheel === undefined ? 'DOMMouseScroll' : 'mousewheel', function(e) { chart.pointer.onContainerMouseWheel(e); stopEvent(e); // Issue #5011, returning false from non-jQuery event does not prevent default return false; }); } }); }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var extend = H.extend, pick = H.pick, Pointer = H.Pointer, wrap = H.wrap; // Extend the Pointer extend(Pointer.prototype, { /** * The event handler for the doubleclick event */ onContainerDblClick: function(e) { var chart = this.chart; e = this.normalize(e); if (chart.options.mapNavigation.enableDoubleClickZoomTo) { if (chart.pointer.inClass(e.target, 'highcharts-tracker') && chart.hoverPoint) { chart.hoverPoint.zoomTo(); } } else if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { chart.mapZoom( 0.5, chart.xAxis[0].toValue(e.chartX), chart.yAxis[0].toValue(e.chartY), e.chartX, e.chartY ); } }, /** * The event handler for the mouse scroll event */ onContainerMouseWheel: function(e) { var chart = this.chart, delta; e = this.normalize(e); // Firefox uses e.detail, WebKit and IE uses wheelDelta delta = e.detail || -(e.wheelDelta / 120); if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { chart.mapZoom( Math.pow(chart.options.mapNavigation.mouseWheelSensitivity, delta), chart.xAxis[0].toValue(e.chartX), chart.yAxis[0].toValue(e.chartY), e.chartX, e.chartY ); } } }); // Implement the pinchType option wrap(Pointer.prototype, 'zoomOption', function(proceed) { var mapNavigation = this.chart.options.mapNavigation; proceed.apply(this, [].slice.call(arguments, 1)); // Pinch status if (pick(mapNavigation.enableTouchZoom, mapNavigation.enabled)) { this.pinchX = this.pinchHor = this.pinchY = this.pinchVert = this.hasZoom = true; } }); // Extend the pinchTranslate method to preserve fixed ratio when zooming wrap(Pointer.prototype, 'pinchTranslate', function(proceed, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) { var xBigger; proceed.call(this, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); // Keep ratio if (this.chart.options.chart.type === 'map' && this.hasZoom) { xBigger = transform.scaleX > transform.scaleY; this.pinchTranslateDirection(!xBigger, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, xBigger ? transform.scaleX : transform.scaleY ); } }); }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var seriesType = H.seriesType, seriesTypes = H.seriesTypes; // The mapline series type seriesType('mapline', 'map', { }, { type: 'mapline', colorProp: 'stroke', drawLegendSymbol: seriesTypes.line.prototype.drawLegendSymbol }); }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var merge = H.merge, Point = H.Point, seriesType = H.seriesType; // The mappoint series type seriesType('mappoint', 'scatter', { dataLabels: { enabled: true, formatter: function() { // #2945 return this.point.name; }, crop: false, defer: false, overflow: false, style: { color: '#000000' } } // Prototype members }, { type: 'mappoint', forceDL: true // Point class }, { applyOptions: function(options, x) { var mergedOptions = options.lat !== undefined && options.lon !== undefined ? merge(options, this.series.chart.fromLatLonToPoint(options)) : options; return Point.prototype.applyOptions.call(this, mergedOptions, x); } }); }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var arrayMax = H.arrayMax, arrayMin = H.arrayMin, Axis = H.Axis, color = H.color, each = H.each, isNumber = H.isNumber, noop = H.noop, pick = H.pick, pInt = H.pInt, Point = H.Point, Series = H.Series, seriesType = H.seriesType, seriesTypes = H.seriesTypes; /* **************************************************************************** * Start Bubble series code * *****************************************************************************/ seriesType('bubble', 'scatter', { dataLabels: { formatter: function() { // #2945 return this.point.z; }, inside: true, verticalAlign: 'middle' }, // displayNegative: true, marker: { // Avoid offset in Point.setState radius: null, states: { hover: { radiusPlus: 0 } } }, minSize: 8, maxSize: '20%', // negativeColor: null, // sizeBy: 'area' softThreshold: false, states: { hover: { halo: { size: 5 } } }, tooltip: { pointFormat: '({point.x}, {point.y}), Size: {point.z}' }, turboThreshold: 0, zThreshold: 0, zoneAxis: 'z' // Prototype members }, { pointArrayMap: ['y', 'z'], parallelArrays: ['x', 'y', 'z'], trackerGroups: ['group', 'dataLabelsGroup'], bubblePadding: true, zoneAxis: 'z', /** * Get the radius for each point based on the minSize, maxSize and each point's Z value. This * must be done prior to Series.translate because the axis needs to add padding in * accordance with the point sizes. */ getRadii: function(zMin, zMax, minSize, maxSize) { var len, i, pos, zData = this.zData, radii = [], options = this.options, sizeByArea = options.sizeBy !== 'width', zThreshold = options.zThreshold, zRange = zMax - zMin, value, radius; // Set the shape type and arguments to be picked up in drawPoints for (i = 0, len = zData.length; i < len; i++) { value = zData[i]; // When sizing by threshold, the absolute value of z determines the size // of the bubble. if (options.sizeByAbsoluteValue && value !== null) { value = Math.abs(value - zThreshold); zMax = Math.max(zMax - zThreshold, Math.abs(zMin - zThreshold)); zMin = 0; } if (value === null) { radius = null; // Issue #4419 - if value is less than zMin, push a radius that's always smaller than the minimum size } else if (value < zMin) { radius = minSize / 2 - 1; } else { // Relative size, a number between 0 and 1 pos = zRange > 0 ? (value - zMin) / zRange : 0.5; if (sizeByArea && pos >= 0) { pos = Math.sqrt(pos); } radius = Math.ceil(minSize + pos * (maxSize - minSize)) / 2; } radii.push(radius); } this.radii = radii; }, /** * Perform animation on the bubbles */ animate: function(init) { var animation = this.options.animation; if (!init) { // run the animation each(this.points, function(point) { var graphic = point.graphic, shapeArgs = point.shapeArgs; if (graphic && shapeArgs) { // start values graphic.attr('r', 1); // animate graphic.animate({ r: shapeArgs.r }, animation); } }); // delete this function to allow it only once this.animate = null; } }, /** * Extend the base translate method to handle bubble size */ translate: function() { var i, data = this.data, point, radius, radii = this.radii; // Run the parent method seriesTypes.scatter.prototype.translate.call(this); // Set the shape type and arguments to be picked up in drawPoints i = data.length; while (i--) { point = data[i]; radius = radii ? radii[i] : 0; // #1737 if (isNumber(radius) && radius >= this.minPxSize / 2) { // Shape arguments point.shapeType = 'circle'; point.shapeArgs = { x: point.plotX, y: point.plotY, r: radius }; // Alignment box for the data label point.dlBox = { x: point.plotX - radius, y: point.plotY - radius, width: 2 * radius, height: 2 * radius }; } else { // below zThreshold point.shapeArgs = point.plotY = point.dlBox = undefined; // #1691 } } }, /** * Get the series' symbol in the legend * * @param {Object} legend The legend object * @param {Object} item The series (this) or point */ drawLegendSymbol: function(legend, item) { var renderer = this.chart.renderer, radius = renderer.fontMetrics(legend.itemStyle.fontSize).f / 2; item.legendSymbol = renderer.circle( radius, legend.baseline - radius, radius ).attr({ zIndex: 3 }).add(item.legendGroup); item.legendSymbol.isMarker = true; }, drawPoints: seriesTypes.column.prototype.drawPoints, alignDataLabel: seriesTypes.column.prototype.alignDataLabel, buildKDTree: noop, applyZones: noop // Point class }, { haloPath: function() { return Point.prototype.haloPath.call(this, this.shapeArgs.r + this.series.options.states.hover.halo.size); }, ttBelow: false }); /** * Add logic to pad each axis with the amount of pixels * necessary to avoid the bubbles to overflow. */ Axis.prototype.beforePadding = function() { var axis = this, axisLength = this.len, chart = this.chart, pxMin = 0, pxMax = axisLength, isXAxis = this.isXAxis, dataKey = isXAxis ? 'xData' : 'yData', min = this.min, extremes = {}, smallestSize = Math.min(chart.plotWidth, chart.plotHeight), zMin = Number.MAX_VALUE, zMax = -Number.MAX_VALUE, range = this.max - min, transA = axisLength / range, activeSeries = []; // Handle padding on the second pass, or on redraw each(this.series, function(series) { var seriesOptions = series.options, zData; if (series.bubblePadding && (series.visible || !chart.options.chart.ignoreHiddenSeries)) { // Correction for #1673 axis.allowZoomOutside = true; // Cache it activeSeries.push(series); if (isXAxis) { // because X axis is evaluated first // For each series, translate the size extremes to pixel values each(['minSize', 'maxSize'], function(prop) { var length = seriesOptions[prop], isPercent = /%$/.test(length); length = pInt(length); extremes[prop] = isPercent ? smallestSize * length / 100 : length; }); series.minPxSize = extremes.minSize; series.maxPxSize = extremes.maxSize; // Find the min and max Z zData = series.zData; if (zData.length) { // #1735 zMin = pick(seriesOptions.zMin, Math.min( zMin, Math.max( arrayMin(zData), seriesOptions.displayNegative === false ? seriesOptions.zThreshold : -Number.MAX_VALUE ) )); zMax = pick(seriesOptions.zMax, Math.max(zMax, arrayMax(zData))); } } } }); each(activeSeries, function(series) { var data = series[dataKey], i = data.length, radius; if (isXAxis) { series.getRadii(zMin, zMax, series.minPxSize, series.maxPxSize); } if (range > 0) { while (i--) { if (isNumber(data[i]) && axis.dataMin <= data[i] && data[i] <= axis.dataMax) { radius = series.radii[i]; pxMin = Math.min(((data[i] - min) * transA) - radius, pxMin); pxMax = Math.max(((data[i] - min) * transA) + radius, pxMax); } } } }); if (activeSeries.length && range > 0 && !this.isLog) { pxMax -= axisLength; transA *= (axisLength + pxMin - pxMax) / axisLength; each([ ['min', 'userMin', pxMin], ['max', 'userMax', pxMax] ], function(keys) { if (pick(axis.options[keys[0]], axis[keys[1]]) === undefined) { axis[keys[0]] += keys[2] / transA; } }); } }; /* **************************************************************************** * End Bubble series code * *****************************************************************************/ }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var merge = H.merge, Point = H.Point, seriesType = H.seriesType, seriesTypes = H.seriesTypes; // The mapbubble series type if (seriesTypes.bubble) { seriesType('mapbubble', 'bubble', { animationLimit: 500, tooltip: { pointFormat: '{point.name}: {point.z}' } // Prototype members }, { xyFromShape: true, type: 'mapbubble', pointArrayMap: ['z'], // If one single value is passed, it is interpreted as z /** * Return the map area identified by the dataJoinBy option */ getMapData: seriesTypes.map.prototype.getMapData, getBox: seriesTypes.map.prototype.getBox, setData: seriesTypes.map.prototype.setData // Point class }, { applyOptions: function(options, x) { var point; if (options && options.lat !== undefined && options.lon !== undefined) { point = Point.prototype.applyOptions.call( this, merge(options, this.series.chart.fromLatLonToPoint(options)), x ); } else { point = seriesTypes.map.prototype.pointClass.prototype.applyOptions.call(this, options, x); } return point; }, ttBelow: false }); } }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var Chart = H.Chart, each = H.each, extend = H.extend, error = H.error, format = H.format, merge = H.merge, win = H.win, wrap = H.wrap; /** * Test for point in polygon. Polygon defined as array of [x,y] points. */ function pointInPolygon(point, polygon) { var i, j, rel1, rel2, c = false, x = point.x, y = point.y; for (i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { rel1 = polygon[i][1] > y; rel2 = polygon[j][1] > y; if (rel1 !== rel2 && (x < (polygon[j][0] - polygon[i][0]) * (y - polygon[i][1]) / (polygon[j][1] - polygon[i][1]) + polygon[i][0])) { c = !c; } } return c; } /** * Get point from latLon using specified transform definition */ Chart.prototype.transformFromLatLon = function(latLon, transform) { if (win.proj4 === undefined) { error(21); return { x: 0, y: null }; } var projected = win.proj4(transform.crs, [latLon.lon, latLon.lat]), cosAngle = transform.cosAngle || (transform.rotation && Math.cos(transform.rotation)), sinAngle = transform.sinAngle || (transform.rotation && Math.sin(transform.rotation)), rotated = transform.rotation ? [projected[0] * cosAngle + projected[1] * sinAngle, -projected[0] * sinAngle + projected[1] * cosAngle] : projected; return { x: ((rotated[0] - (transform.xoffset || 0)) * (transform.scale || 1) + (transform.xpan || 0)) * (transform.jsonres || 1) + (transform.jsonmarginX || 0), y: (((transform.yoffset || 0) - rotated[1]) * (transform.scale || 1) + (transform.ypan || 0)) * (transform.jsonres || 1) - (transform.jsonmarginY || 0) }; }; /** * Get latLon from point using specified transform definition */ Chart.prototype.transformToLatLon = function(point, transform) { if (win.proj4 === undefined) { error(21); return; } var normalized = { x: ((point.x - (transform.jsonmarginX || 0)) / (transform.jsonres || 1) - (transform.xpan || 0)) / (transform.scale || 1) + (transform.xoffset || 0), y: ((-point.y - (transform.jsonmarginY || 0)) / (transform.jsonres || 1) + (transform.ypan || 0)) / (transform.scale || 1) + (transform.yoffset || 0) }, cosAngle = transform.cosAngle || (transform.rotation && Math.cos(transform.rotation)), sinAngle = transform.sinAngle || (transform.rotation && Math.sin(transform.rotation)), // Note: Inverted sinAngle to reverse rotation direction projected = win.proj4(transform.crs, 'WGS84', transform.rotation ? { x: normalized.x * cosAngle + normalized.y * -sinAngle, y: normalized.x * sinAngle + normalized.y * cosAngle } : normalized); return { lat: projected.y, lon: projected.x }; }; Chart.prototype.fromPointToLatLon = function(point) { var transforms = this.mapTransforms, transform; if (!transforms) { error(22); return; } for (transform in transforms) { if (transforms.hasOwnProperty(transform) && transforms[transform].hitZone && pointInPolygon({ x: point.x, y: -point.y }, transforms[transform].hitZone.coordinates[0])) { return this.transformToLatLon(point, transforms[transform]); } } return this.transformToLatLon(point, transforms['default']); // eslint-disable-line dot-notation }; Chart.prototype.fromLatLonToPoint = function(latLon) { var transforms = this.mapTransforms, transform, coords; if (!transforms) { error(22); return { x: 0, y: null }; } for (transform in transforms) { if (transforms.hasOwnProperty(transform) && transforms[transform].hitZone) { coords = this.transformFromLatLon(latLon, transforms[transform]); if (pointInPolygon({ x: coords.x, y: -coords.y }, transforms[transform].hitZone.coordinates[0])) { return coords; } } } return this.transformFromLatLon(latLon, transforms['default']); // eslint-disable-line dot-notation }; /** * Convert a geojson object to map data of a given Highcharts type (map, mappoint or mapline). */ H.geojson = function(geojson, hType, series) { var mapData = [], path = [], polygonToPath = function(polygon) { var i, len = polygon.length; path.push('M'); for (i = 0; i < len; i++) { if (i === 1) { path.push('L'); } path.push(polygon[i][0], -polygon[i][1]); } }; hType = hType || 'map'; each(geojson.features, function(feature) { var geometry = feature.geometry, type = geometry.type, coordinates = geometry.coordinates, properties = feature.properties, point; path = []; if (hType === 'map' || hType === 'mapbubble') { if (type === 'Polygon') { each(coordinates, polygonToPath); path.push('Z'); } else if (type === 'MultiPolygon') { each(coordinates, function(items) { each(items, polygonToPath); }); path.push('Z'); } if (path.length) { point = { path: path }; } } else if (hType === 'mapline') { if (type === 'LineString') { polygonToPath(coordinates); } else if (type === 'MultiLineString') { each(coordinates, polygonToPath); } if (path.length) { point = { path: path }; } } else if (hType === 'mappoint') { if (type === 'Point') { point = { x: coordinates[0], y: -coordinates[1] }; } } if (point) { mapData.push(extend(point, { name: properties.name || properties.NAME, properties: properties })); } }); // Create a credits text that includes map source, to be picked up in Chart.addCredits if (series && geojson.copyrightShort) { series.chart.mapCredits = format(series.chart.options.credits.mapText, { geojson: geojson }); series.chart.mapCreditsFull = format(series.chart.options.credits.mapTextFull, { geojson: geojson }); } return mapData; }; /** * Override addCredits to include map source by default */ wrap(Chart.prototype, 'addCredits', function(proceed, credits) { credits = merge(true, this.options.credits, credits); // Disable credits link if map credits enabled. This to allow for in-text anchors. if (this.mapCredits) { credits.href = null; } proceed.call(this, credits); // Add full map credits to hover if (this.credits && this.mapCreditsFull) { this.credits.attr({ title: this.mapCreditsFull }); } }); }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var Chart = H.Chart, defaultOptions = H.defaultOptions, each = H.each, extend = H.extend, merge = H.merge, pick = H.pick, Renderer = H.Renderer, SVGRenderer = H.SVGRenderer, VMLRenderer = H.VMLRenderer; // Add language extend(defaultOptions.lang, { zoomIn: 'Zoom in', zoomOut: 'Zoom out' }); // Set the default map navigation options defaultOptions.mapNavigation = { buttonOptions: { alignTo: 'plotBox', align: 'left', verticalAlign: 'top', x: 0, width: 18, height: 18, padding: 5 }, buttons: { zoomIn: { onclick: function() { this.mapZoom(0.5); }, text: '+', y: 0 }, zoomOut: { onclick: function() { this.mapZoom(2); }, text: '-', y: 28 } }, mouseWheelSensitivity: 1.1 // enabled: false, // enableButtons: null, // inherit from enabled // enableTouchZoom: null, // inherit from enabled // enableDoubleClickZoom: null, // inherit from enabled // enableDoubleClickZoomTo: false // enableMouseWheelZoom: null, // inherit from enabled }; /** * Utility for reading SVG paths directly. */ H.splitPath = function(path) { var i; // Move letters apart path = path.replace(/([A-Za-z])/g, ' $1 '); // Trim path = path.replace(/^\s*/, '').replace(/\s*$/, ''); // Split on spaces and commas path = path.split(/[ ,]+/); // Extra comma to escape gulp.scripts task // Parse numbers for (i = 0; i < path.length; i++) { if (!/[a-zA-Z]/.test(path[i])) { path[i] = parseFloat(path[i]); } } return path; }; // A placeholder for map definitions H.maps = {}; // Create symbols for the zoom buttons function selectiveRoundedRect(x, y, w, h, rTopLeft, rTopRight, rBottomRight, rBottomLeft) { return ['M', x + rTopLeft, y, // top side 'L', x + w - rTopRight, y, // top right corner 'C', x + w - rTopRight / 2, y, x + w, y + rTopRight / 2, x + w, y + rTopRight, // right side 'L', x + w, y + h - rBottomRight, // bottom right corner 'C', x + w, y + h - rBottomRight / 2, x + w - rBottomRight / 2, y + h, x + w - rBottomRight, y + h, // bottom side 'L', x + rBottomLeft, y + h, // bottom left corner 'C', x + rBottomLeft / 2, y + h, x, y + h - rBottomLeft / 2, x, y + h - rBottomLeft, // left side 'L', x, y + rTopLeft, // top left corner 'C', x, y + rTopLeft / 2, x + rTopLeft / 2, y, x + rTopLeft, y, 'Z' ]; } SVGRenderer.prototype.symbols.topbutton = function(x, y, w, h, attr) { return selectiveRoundedRect(x - 1, y - 1, w, h, attr.r, attr.r, 0, 0); }; SVGRenderer.prototype.symbols.bottombutton = function(x, y, w, h, attr) { return selectiveRoundedRect(x - 1, y - 1, w, h, 0, 0, attr.r, attr.r); }; // The symbol callbacks are generated on the SVGRenderer object in all browsers. Even // VML browsers need this in order to generate shapes in export. Now share // them with the VMLRenderer. if (Renderer === VMLRenderer) { each(['topbutton', 'bottombutton'], function(shape) { VMLRenderer.prototype.symbols[shape] = SVGRenderer.prototype.symbols[shape]; }); } /** * A wrapper for Chart with all the default values for a Map */ H.Map = H.mapChart = function(a, b, c) { var hasRenderToArg = typeof a === 'string' || a.nodeName, options = arguments[hasRenderToArg ? 1 : 0], hiddenAxis = { endOnTick: false, visible: false, minPadding: 0, maxPadding: 0, startOnTick: false }, seriesOptions, defaultCreditsOptions = H.getOptions().credits; /* For visual testing hiddenAxis.gridLineWidth = 1; hiddenAxis.gridZIndex = 10; hiddenAxis.tickPositions = undefined; // */ // Don't merge the data seriesOptions = options.series; options.series = null; options = merge({ chart: { panning: 'xy', type: 'map' }, credits: { mapText: pick(defaultCreditsOptions.mapText, ' \u00a9 <a href="{geojson.copyrightUrl}">{geojson.copyrightShort}</a>'), mapTextFull: pick(defaultCreditsOptions.mapTextFull, '{geojson.copyright}') }, xAxis: hiddenAxis, yAxis: merge(hiddenAxis, { reversed: true }) }, options, // user's options { // forced options chart: { inverted: false, alignTicks: false } } ); options.series = seriesOptions; return hasRenderToArg ? new Chart(a, options, c) : new Chart(options, b); }; }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var colorPointMixin = H.colorPointMixin, colorSeriesMixin = H.colorSeriesMixin, each = H.each, LegendSymbolMixin = H.LegendSymbolMixin, merge = H.merge, noop = H.noop, pick = H.pick, Series = H.Series, seriesType = H.seriesType, seriesTypes = H.seriesTypes; // The Heatmap series type seriesType('heatmap', 'scatter', { animation: false, borderWidth: 0, dataLabels: { formatter: function() { // #2945 return this.point.value; }, inside: true, verticalAlign: 'middle', crop: false, overflow: false, padding: 0 // #3837 }, marker: null, pointRange: null, // dynamically set to colsize by default tooltip: { pointFormat: '{point.x}, {point.y}: {point.value}<br/>' }, states: { normal: { animation: true }, hover: { halo: false, // #3406, halo is not required on heatmaps brightness: 0.2 } } }, merge(colorSeriesMixin, { pointArrayMap: ['y', 'value'], hasPointSpecificOptions: true, supportsDrilldown: true, getExtremesFromAll: true, directTouch: true, /** * Override the init method to add point ranges on both axes. */ init: function() { var options; seriesTypes.scatter.prototype.init.apply(this, arguments); options = this.options; options.pointRange = pick(options.pointRange, options.colsize || 1); // #3758, prevent resetting in setData this.yAxis.axisPointRange = options.rowsize || 1; // general point range }, translate: function() { var series = this, options = series.options, xAxis = series.xAxis, yAxis = series.yAxis, between = function(x, a, b) { return Math.min(Math.max(a, x), b); }; series.generatePoints(); each(series.points, function(point) { var xPad = (options.colsize || 1) / 2, yPad = (options.rowsize || 1) / 2, x1 = between(Math.round(xAxis.len - xAxis.translate(point.x - xPad, 0, 1, 0, 1)), -xAxis.len, 2 * xAxis.len), x2 = between(Math.round(xAxis.len - xAxis.translate(point.x + xPad, 0, 1, 0, 1)), -xAxis.len, 2 * xAxis.len), y1 = between(Math.round(yAxis.translate(point.y - yPad, 0, 1, 0, 1)), -yAxis.len, 2 * yAxis.len), y2 = between(Math.round(yAxis.translate(point.y + yPad, 0, 1, 0, 1)), -yAxis.len, 2 * yAxis.len); // Set plotX and plotY for use in K-D-Tree and more point.plotX = point.clientX = (x1 + x2) / 2; point.plotY = (y1 + y2) / 2; point.shapeType = 'rect'; point.shapeArgs = { x: Math.min(x1, x2), y: Math.min(y1, y2), width: Math.abs(x2 - x1), height: Math.abs(y2 - y1) }; }); series.translateColors(); }, drawPoints: function() { seriesTypes.column.prototype.drawPoints.call(this); each(this.points, function(point) { point.graphic.attr(this.colorAttribs(point, point.state)); }, this); }, animate: noop, getBox: noop, drawLegendSymbol: LegendSymbolMixin.drawRectangle, alignDataLabel: seriesTypes.column.prototype.alignDataLabel, getExtremes: function() { // Get the extremes from the value data Series.prototype.getExtremes.call(this, this.valueData); this.valueMin = this.dataMin; this.valueMax = this.dataMax; // Get the extremes from the y data Series.prototype.getExtremes.call(this); } }), colorPointMixin); }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var addEvent = H.addEvent, Chart = H.Chart, createElement = H.createElement, css = H.css, defaultOptions = H.defaultOptions, defaultPlotOptions = H.defaultPlotOptions, each = H.each, extend = H.extend, fireEvent = H.fireEvent, hasTouch = H.hasTouch, inArray = H.inArray, isObject = H.isObject, Legend = H.Legend, merge = H.merge, pick = H.pick, Point = H.Point, Series = H.Series, seriesTypes = H.seriesTypes, svg = H.svg, TrackerMixin; /** * TrackerMixin for points and graphs */ TrackerMixin = H.TrackerMixin = { drawTrackerPoint: function() { var series = this, chart = series.chart, pointer = chart.pointer, onMouseOver = function(e) { var target = e.target, point; while (target && !point) { point = target.point; target = target.parentNode; } if (point !== undefined && point !== chart.hoverPoint) { // undefined on graph in scatterchart point.onMouseOver(e); } }; // Add reference to the point each(series.points, function(point) { if (point.graphic) { point.graphic.element.point = point; } if (point.dataLabel) { point.dataLabel.element.point = point; } }); // Add the event listeners, we need to do this only once if (!series._hasTracking) { each(series.trackerGroups, function(key) { if (series[key]) { // we don't always have dataLabelsGroup series[key] .addClass('highcharts-tracker') .on('mouseover', onMouseOver) .on('mouseout', function(e) { pointer.onTrackerMouseOut(e); }); if (hasTouch) { series[key].on('touchstart', onMouseOver); } } }); series._hasTracking = true; } }, /** * Draw the tracker object that sits above all data labels and markers to * track mouse events on the graph or points. For the line type charts * the tracker uses the same graphPath, but with a greater stroke width * for better control. */ drawTrackerGraph: function() { var series = this, options = series.options, trackByArea = options.trackByArea, trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath), trackerPathLength = trackerPath.length, chart = series.chart, pointer = chart.pointer, renderer = chart.renderer, snap = chart.options.tooltip.snap, tracker = series.tracker, i, onMouseOver = function() { if (chart.hoverSeries !== series) { series.onMouseOver(); } }, /* * Empirical lowest possible opacities for TRACKER_FILL for an element to stay invisible but clickable * IE6: 0.002 * IE7: 0.002 * IE8: 0.002 * IE9: 0.00000000001 (unlimited) * IE10: 0.0001 (exporting only) * FF: 0.00000000001 (unlimited) * Chrome: 0.000001 * Safari: 0.000001 * Opera: 0.00000000001 (unlimited) */ TRACKER_FILL = 'rgba(192,192,192,' + (svg ? 0.0001 : 0.002) + ')'; // Extend end points. A better way would be to use round linecaps, // but those are not clickable in VML. if (trackerPathLength && !trackByArea) { i = trackerPathLength + 1; while (i--) { if (trackerPath[i] === 'M') { // extend left side trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], 'L'); } if ((i && trackerPath[i] === 'M') || i === trackerPathLength) { // extend right side trackerPath.splice(i, 0, 'L', trackerPath[i - 2] + snap, trackerPath[i - 1]); } } } // handle single points /*for (i = 0; i < singlePoints.length; i++) { singlePoint = singlePoints[i]; trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY, L, singlePoint.plotX + snap, singlePoint.plotY); }*/ // draw the tracker if (tracker) { tracker.attr({ d: trackerPath }); } else if (series.graph) { // create series.tracker = renderer.path(trackerPath) .attr({ 'stroke-linejoin': 'round', // #1225 visibility: series.visible ? 'visible' : 'hidden', stroke: TRACKER_FILL, fill: trackByArea ? TRACKER_FILL : 'none', 'stroke-width': series.graph.strokeWidth() + (trackByArea ? 0 : 2 * snap), zIndex: 2 }) .add(series.group); // The tracker is added to the series group, which is clipped, but is covered // by the marker group. So the marker group also needs to capture events. each([series.tracker, series.markerGroup], function(tracker) { tracker.addClass('highcharts-tracker') .on('mouseover', onMouseOver) .on('mouseout', function(e) { pointer.onTrackerMouseOut(e); }); if (hasTouch) { tracker.on('touchstart', onMouseOver); } }); } } }; /* End TrackerMixin */ /** * Add tracking event listener to the series group, so the point graphics * themselves act as trackers */ if (seriesTypes.column) { seriesTypes.column.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.pie) { seriesTypes.pie.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.scatter) { seriesTypes.scatter.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } /* * Extend Legend for item events */ extend(Legend.prototype, { setItemEvents: function(item, legendItem, useHTML) { var legend = this, chart = legend.chart, activeClass = 'highcharts-legend-' + (item.series ? 'point' : 'series') + '-active'; // Set the events on the item group, or in case of useHTML, the item itself (#1249) (useHTML ? legendItem : item.legendGroup).on('mouseover', function() { item.setState('hover'); // A CSS class to dim or hide other than the hovered series chart.seriesGroup.addClass(activeClass); }) .on('mouseout', function() { // A CSS class to dim or hide other than the hovered series chart.seriesGroup.removeClass(activeClass); item.setState(); }) .on('click', function(event) { var strLegendItemClick = 'legendItemClick', fnLegendItemClick = function() { if (item.setVisible) { item.setVisible(); } }; // Pass over the click/touch event. #4. event = { browserEvent: event }; // click the name or symbol if (item.firePointEvent) { // point item.firePointEvent(strLegendItemClick, event, fnLegendItemClick); } else { fireEvent(item, strLegendItemClick, event, fnLegendItemClick); } }); }, createCheckboxForItem: function(item) { var legend = this; item.checkbox = createElement('input', { type: 'checkbox', checked: item.selected, defaultChecked: item.selected // required by IE7 }, legend.options.itemCheckboxStyle, legend.chart.container); addEvent(item.checkbox, 'click', function(event) { var target = event.target; fireEvent( item.series || item, 'checkboxClick', { // #3712 checked: target.checked, item: item }, function() { item.select(); } ); }); } }); /* * Extend the Chart object with interaction */ extend(Chart.prototype, { /** * Display the zoom button */ showResetZoom: function() { var chart = this, lang = defaultOptions.lang, btnOptions = chart.options.chart.resetZoomButton, theme = btnOptions.theme, states = theme.states, alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox'; function zoomOut() { chart.zoomOut(); } this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, zoomOut, theme, states && states.hover) .attr({ align: btnOptions.position.align, title: lang.resetZoomTitle }) .addClass('highcharts-reset-zoom') .add() .align(btnOptions.position, false, alignTo); }, /** * Zoom out to 1:1 */ zoomOut: function() { var chart = this; fireEvent(chart, 'selection', { resetSelection: true }, function() { chart.zoom(); }); }, /** * Zoom into a given portion of the chart given by axis coordinates * @param {Object} event */ zoom: function(event) { var chart = this, hasZoomed, pointer = chart.pointer, displayButton = false, resetZoomButton; // If zoom is called with no arguments, reset the axes if (!event || event.resetSelection) { each(chart.axes, function(axis) { hasZoomed = axis.zoom(); }); } else { // else, zoom in on all axes each(event.xAxis.concat(event.yAxis), function(axisData) { var axis = axisData.axis, isXAxis = axis.isXAxis; // don't zoom more than minRange if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) { hasZoomed = axis.zoom(axisData.min, axisData.max); if (axis.displayBtn) { displayButton = true; } } }); } // Show or hide the Reset zoom button resetZoomButton = chart.resetZoomButton; if (displayButton && !resetZoomButton) { chart.showResetZoom(); } else if (!displayButton && isObject(resetZoomButton)) { chart.resetZoomButton = resetZoomButton.destroy(); } // Redraw if (hasZoomed) { chart.redraw( pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation ); } }, /** * Pan the chart by dragging the mouse across the pane. This function is called * on mouse move, and the distance to pan is computed from chartX compared to * the first chartX position in the dragging operation. */ pan: function(e, panning) { var chart = this, hoverPoints = chart.hoverPoints, doRedraw; // remove active points for shared tooltip if (hoverPoints) { each(hoverPoints, function(point) { point.setState(); }); } each(panning === 'xy' ? [1, 0] : [1], function(isX) { // xy is used in maps var axis = chart[isX ? 'xAxis' : 'yAxis'][0], horiz = axis.horiz, mousePos = e[horiz ? 'chartX' : 'chartY'], mouseDown = horiz ? 'mouseDownX' : 'mouseDownY', startPos = chart[mouseDown], halfPointRange = (axis.pointRange || 0) / 2, extremes = axis.getExtremes(), newMin = axis.toValue(startPos - mousePos, true) + halfPointRange, newMax = axis.toValue(startPos + axis.len - mousePos, true) - halfPointRange, goingLeft = startPos > mousePos; // #3613 if (axis.series.length && (goingLeft || newMin > Math.min(extremes.dataMin, extremes.min)) && (!goingLeft || newMax < Math.max(extremes.dataMax, extremes.max))) { axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' }); doRedraw = true; } chart[mouseDown] = mousePos; // set new reference for next run }); if (doRedraw) { chart.redraw(false); } css(chart.container, { cursor: 'move' }); } }); /* * Extend the Point object with interaction */ extend(Point.prototype, { /** * Toggle the selection status of a point * @param {Boolean} selected Whether to select or unselect the point. * @param {Boolean} accumulate Whether to add to the previous selection. By default, * this happens if the control key (Cmd on Mac) was pressed during clicking. */ select: function(selected, accumulate) { var point = this, series = point.series, chart = series.chart; selected = pick(selected, !point.selected); // fire the event with the default handler point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function() { point.selected = point.options.selected = selected; series.options.data[inArray(point, series.data)] = point.options; point.setState(selected && 'select'); // unselect all other points unless Ctrl or Cmd + click if (!accumulate) { each(chart.getSelectedPoints(), function(loopPoint) { if (loopPoint.selected && loopPoint !== point) { loopPoint.selected = loopPoint.options.selected = false; series.options.data[inArray(loopPoint, series.data)] = loopPoint.options; loopPoint.setState(''); loopPoint.firePointEvent('unselect'); } }); } }); }, /** * Runs on mouse over the point * * @param {Object} e The event arguments * @param {Boolean} byProximity Falsy for kd points that are closest to the mouse, or to * actually hovered points. True for other points in shared tooltip. */ onMouseOver: function(e, byProximity) { var point = this, series = point.series, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; if (point.series) { // It may have been destroyed, #4130 // In shared tooltip, call mouse over when point/series is actually hovered: (#5766) if (!byProximity) { // set normal state to previous series if (hoverPoint && hoverPoint !== point) { hoverPoint.onMouseOut(); } if (chart.hoverSeries !== series) { series.onMouseOver(); } chart.hoverPoint = point; } // update the tooltip if (tooltip && (!tooltip.shared || series.noSharedTooltip)) { // hover point only for non shared points: (#5766) point.setState('hover'); tooltip.refresh(point, e); } else if (!tooltip) { point.setState('hover'); } // trigger the event point.firePointEvent('mouseOver'); } }, /** * Runs on mouse out from the point */ onMouseOut: function() { var chart = this.series.chart, hoverPoints = chart.hoverPoints; this.firePointEvent('mouseOut'); if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887, #2240 this.setState(); chart.hoverPoint = null; } }, /** * Import events from the series' and point's options. Only do it on * demand, to save processing time on hovering. */ importEvents: function() { if (!this.hasImportedEvents) { var point = this, options = merge(point.series.options.point, point.options), events = options.events, eventType; point.events = events; for (eventType in events) { addEvent(point, eventType, events[eventType]); } this.hasImportedEvents = true; } }, /** * Set the point's state * @param {String} state */ setState: function(state, move) { var point = this, plotX = Math.floor(point.plotX), // #4586 plotY = point.plotY, series = point.series, stateOptions = series.options.states[state] || {}, markerOptions = defaultPlotOptions[series.type].marker && series.options.marker, normalDisabled = markerOptions && markerOptions.enabled === false, markerStateOptions = (markerOptions && markerOptions.states && markerOptions.states[state]) || {}, stateDisabled = markerStateOptions.enabled === false, stateMarkerGraphic = series.stateMarkerGraphic, pointMarker = point.marker || {}, chart = series.chart, halo = series.halo, haloOptions, markerAttribs, newSymbol; state = state || ''; // empty string if ( // already has this state (state === point.state && !move) || // selected points don't respond to hover (point.selected && state !== 'select') || // series' state options is disabled (stateOptions.enabled === false) || // general point marker's state options is disabled (state && (stateDisabled || (normalDisabled && markerStateOptions.enabled === false))) || // individual point marker's state options is disabled (state && pointMarker.states && pointMarker.states[state] && pointMarker.states[state].enabled === false) // #1610 ) { return; } if (markerOptions) { markerAttribs = series.markerAttribs(point, state); } // Apply hover styles to the existing point if (point.graphic) { if (point.state) { point.graphic.removeClass('highcharts-point-' + point.state); } if (state) { point.graphic.addClass('highcharts-point-' + state); } /*attribs = radius ? { // new symbol attributes (#507, #612) x: plotX - radius, y: plotY - radius, width: 2 * radius, height: 2 * radius } : {};*/ if (markerAttribs) { point.graphic.animate( markerAttribs, pick( chart.options.chart.animation, // Turn off globally markerStateOptions.animation, markerOptions.animation ) ); } // Zooming in from a range with no markers to a range with markers if (stateMarkerGraphic) { stateMarkerGraphic.hide(); } } else { // if a graphic is not applied to each point in the normal state, create a shared // graphic for the hover state if (state && markerStateOptions) { newSymbol = pointMarker.symbol || series.symbol; // If the point has another symbol than the previous one, throw away the // state marker graphic and force a new one (#1459) if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) { stateMarkerGraphic = stateMarkerGraphic.destroy(); } // Add a new state marker graphic if (!stateMarkerGraphic) { if (newSymbol) { series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol( newSymbol, markerAttribs.x, markerAttribs.y, markerAttribs.width, markerAttribs.height ) .add(series.markerGroup); stateMarkerGraphic.currentSymbol = newSymbol; } // Move the existing graphic } else { stateMarkerGraphic[move ? 'animate' : 'attr']({ // #1054 x: markerAttribs.x, y: markerAttribs.y }); } } if (stateMarkerGraphic) { stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY, chart.inverted) ? 'show' : 'hide'](); // #2450 stateMarkerGraphic.element.point = point; // #4310 } } // Show me your halo haloOptions = stateOptions.halo; if (haloOptions && haloOptions.size) { if (!halo) { series.halo = halo = chart.renderer.path() .add(series.markerGroup || series.group); } H.stop(halo); halo[move ? 'animate' : 'attr']({ d: point.haloPath(haloOptions.size) }); halo.attr({ 'class': 'highcharts-halo highcharts-color-' + pick(point.colorIndex, series.colorIndex) }); } else if (halo) { halo.animate({ d: point.haloPath(0) }); // Hide } point.state = state; }, /** * Get the circular path definition for the halo * @param {Number} size The radius of the circular halo * @returns {Array} The path definition */ haloPath: function(size) { var series = this.series, chart = series.chart, inverted = chart.inverted, plotX = Math.floor(this.plotX); return chart.renderer.symbols.circle( (inverted ? series.yAxis.len - this.plotY : plotX) - size, (inverted ? series.xAxis.len - plotX : this.plotY) - size, size * 2, size * 2 ); } }); /* * Extend the Series object with interaction */ extend(Series.prototype, { /** * Series mouse over handler */ onMouseOver: function() { var series = this, chart = series.chart, hoverSeries = chart.hoverSeries; // set normal state to previous series if (hoverSeries && hoverSeries !== series) { hoverSeries.onMouseOut(); } // trigger the event, but to save processing time, // only if defined if (series.options.events.mouseOver) { fireEvent(series, 'mouseOver'); } // hover this series.setState('hover'); chart.hoverSeries = series; }, /** * Series mouse out handler */ onMouseOut: function() { // trigger the event only if listeners exist var series = this, options = series.options, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; chart.hoverSeries = null; // #182, set to null before the mouseOut event fires // trigger mouse out on the point, which must be in this series if (hoverPoint) { hoverPoint.onMouseOut(); } // fire the mouse out event if (series && options.events.mouseOut) { fireEvent(series, 'mouseOut'); } // hide the tooltip if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) { tooltip.hide(); } // set normal state series.setState(); }, /** * Set the state of the graph */ setState: function(state) { var series = this, options = series.options, graph = series.graph, stateOptions = options.states, lineWidth = options.lineWidth, attribs, i = 0; state = state || ''; if (series.state !== state) { // Toggle class names each([series.group, series.markerGroup], function(group) { if (group) { // Old state if (series.state) { group.removeClass('highcharts-series-' + series.state); } // New state if (state) { group.addClass('highcharts-series-' + state); } } }); series.state = state; } }, /** * Set the visibility of the graph * * @param vis {Boolean} True to show the series, false to hide. If undefined, * the visibility is toggled. */ setVisible: function(vis, redraw) { var series = this, chart = series.chart, legendItem = series.legendItem, showOrHide, ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries, oldVisibility = series.visible; // if called without an argument, toggle visibility series.visible = vis = series.options.visible = series.userOptions.visible = vis === undefined ? !oldVisibility : vis; // #5618 showOrHide = vis ? 'show' : 'hide'; // show or hide elements each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker', 'tt'], function(key) { if (series[key]) { series[key][showOrHide](); } }); // hide tooltip (#1361) if (chart.hoverSeries === series || (chart.hoverPoint && chart.hoverPoint.series) === series) { series.onMouseOut(); } if (legendItem) { chart.legend.colorizeItem(series, vis); } // rescale or adapt to resized chart series.isDirty = true; // in a stack, all other series are affected if (series.options.stacking) { each(chart.series, function(otherSeries) { if (otherSeries.options.stacking && otherSeries.visible) { otherSeries.isDirty = true; } }); } // show or hide linked series each(series.linkedSeries, function(otherSeries) { otherSeries.setVisible(vis, false); }); if (ignoreHiddenSeries) { chart.isDirtyBox = true; } if (redraw !== false) { chart.redraw(); } fireEvent(series, showOrHide); }, /** * Show the graph */ show: function() { this.setVisible(true); }, /** * Hide the graph */ hide: function() { this.setVisible(false); }, /** * Set the selected state of the graph * * @param selected {Boolean} True to select the series, false to unselect. If * undefined, the selection state is toggled. */ select: function(selected) { var series = this; // if called without an argument, toggle series.selected = selected = (selected === undefined) ? !series.selected : selected; if (series.checkbox) { series.checkbox.checked = selected; } fireEvent(series, selected ? 'select' : 'unselect'); }, drawTracker: TrackerMixin.drawTrackerGraph }); }(Highcharts)); (function(H) { /** * (c) 2010-2016 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; var Chart = H.Chart, each = H.each, inArray = H.inArray, isObject = H.isObject, pick = H.pick, splat = H.splat; /** * Update the chart based on the current chart/document size and options for responsiveness */ Chart.prototype.setResponsive = function(redraw) { var options = this.options.responsive; if (options && options.rules) { each(options.rules, function(rule) { this.matchResponsiveRule(rule, redraw); }, this); } }; /** * Handle a single responsiveness rule */ Chart.prototype.matchResponsiveRule = function(rule, redraw) { var respRules = this.respRules, condition = rule.condition, matches, fn = rule.callback || function() { return this.chartWidth <= pick(condition.maxWidth, Number.MAX_VALUE) && this.chartHeight <= pick(condition.maxHeight, Number.MAX_VALUE) && this.chartWidth >= pick(condition.minWidth, 0) && this.chartHeight >= pick(condition.minHeight, 0); }; if (rule._id === undefined) { rule._id = H.idCounter++; } matches = fn.call(this); // Apply a rule if (!respRules[rule._id] && matches) { // Store the current state of the options if (rule.chartOptions) { respRules[rule._id] = this.currentOptions(rule.chartOptions); this.update(rule.chartOptions, redraw); } // Unapply a rule based on the previous options before the rule // was applied } else if (respRules[rule._id] && !matches) { this.update(respRules[rule._id], redraw); delete respRules[rule._id]; } }; /** * Get the current values for a given set of options. Used before we update * the chart with a new responsiveness rule. * TODO: Restore axis options (by id?) */ Chart.prototype.currentOptions = function(options) { var ret = {}; /** * Recurse over a set of options and its current values, * and store the current values in the ret object. */ function getCurrent(options, curr, ret) { var key, i; for (key in options) { if (inArray(key, ['series', 'xAxis', 'yAxis']) > -1) { options[key] = splat(options[key]); ret[key] = []; for (i = 0; i < options[key].length; i++) { ret[key][i] = {}; getCurrent(options[key][i], curr[key][i], ret[key][i]); } } else if (isObject(options[key])) { ret[key] = {}; getCurrent(options[key], curr[key] || {}, ret[key]); } else { ret[key] = curr[key] || null; } } } getCurrent(options, this.options, ret); return ret; }; }(Highcharts)); return Highcharts }));
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ /*jslint evil: true, regexp: true */ /*members $ref, apply, call, decycle, hasOwnProperty, length, prototype, push, retrocycle, stringify, test, toString */ (function (exports) { if (typeof exports.decycle !== 'function') { exports.decycle = function decycle(object) { 'use strict'; var objects = [], paths = []; return (function derez(value, path) { var i, name, nu; switch (typeof value) { case 'object': if (!value) { return null; } for (i = 0; i < objects.length; i += 1) { if (objects[i] === value) { return {$ref: paths[i]}; } } objects.push(value); paths.push(path); if (Object.prototype.toString.apply(value) === '[object Array]') { nu = []; for (i = 0; i < value.length; i += 1) { nu[i] = derez(value[i], path + '[' + i + ']'); } } else { nu = {}; for (name in value) { if (Object.prototype.hasOwnProperty.call(value, name)) { nu[name] = derez(value[name], path + '[' + JSON.stringify(name) + ']'); } } } return nu; case 'number': case 'string': case 'boolean': return value; } }(object, '$')); }; } if (typeof exports.retrocycle !== 'function') { exports.retrocycle = function retrocycle($) { 'use strict'; var px = /^\$(?:\[(?:\d+|\"(?:[^\\\"\u0000-\u001f]|\\([\\\"\/bfnrt]|u[0-9a-zA-Z]{4}))*\")\])*$/; (function rez(value) { var i, item, name, path; if (value && typeof value === 'object') { if (Object.prototype.toString.apply(value) === '[object Array]') { for (i = 0; i < value.length; i += 1) { item = value[i]; if (item && typeof item === 'object') { path = item.$ref; if (typeof path === 'string' && px.test(path)) { value[i] = eval(path); } else { rez(item); } } } } else { for (name in value) { if (typeof value[name] === 'object') { item = value[name]; if (item) { path = item.$ref; if (typeof path === 'string' && px.test(path)) { value[name] = eval(path); } else { rez(item); } } } } } } }($)); return $; }; } }) ( (typeof exports !== 'undefined') ? exports : (window.JSON ? (window.JSON) : (window.JSON = {}) ) ); },{}],2:[function(require,module,exports){ var JSON2 = require('./json2'); var cycle = require('./cycle'); JSON2.decycle = cycle.decycle; JSON2.retrocycle = cycle.retrocycle; module.exports = JSON2; },{"./cycle":1,"./json2":3}],3:[function(require,module,exports){ /* json2.js 2011-10-19 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, regexp: true */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ (function (JSON) { 'use strict'; function f(n) { return n < 10 ? '0' + n : n; } /* DDOPSON-2012-04-16 - mutating global prototypes is NOT allowed for a well-behaved module. * It's also unneeded, since Date already defines toJSON() to the same ISOwhatever format below * Thus, we skip this logic for the CommonJS case where 'exports' is defined */ if (typeof exports === 'undefined') { if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; } if (typeof String.prototype.toJSON !== 'function') { String.prototype.toJSON = function (key) { return this.valueOf(); }; } if (typeof Number.prototype.toJSON !== 'function') { Number.prototype.toJSON = function (key) { return this.valueOf(); }; } if (typeof Boolean.prototype.toJSON !== 'function') { Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { var i, k, v, length, mind = gap, partial, value = holder[key]; if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } if (typeof rep === 'function') { value = rep.call(holder, key, value); } switch (typeof value) { case 'string': return quote(value); case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': return String(value); case 'object': if (!value) { return 'null'; } gap += indent; partial = []; if (Object.prototype.toString.apply(value) === '[object Array]') { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { var i; gap = ''; indent = ''; if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } } else if (typeof space === 'string') { indent = space; } rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } return str('', {'': value}); }; } if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { var j; function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { j = eval('(' + text + ')'); return typeof reviver === 'function' ? walk({'': j}, '') : j; } throw new SyntaxError('JSON.parse'); }; } })( (typeof exports !== 'undefined') ? exports : (window.JSON ? (window.JSON) : (window.JSON = {}) ) ); },{}],4:[function(require,module,exports){ /** * Expose `Emitter`. */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks[event] = this._callbacks[event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ var self = this; this._callbacks = this._callbacks || {}; function on() { self.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; if (0 == arguments.length) { this._callbacks = {}; return this; } var callbacks = this._callbacks[event]; if (!callbacks) return this; if (1 == arguments.length) { delete this._callbacks[event]; return this; } var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks[event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks[event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; },{}],5:[function(require,module,exports){ /*! * domready (c) Dustin Diaz 2012 - License MIT */ !function (name, definition) { if (typeof module != 'undefined') module.exports = definition() else if (typeof define == 'function' && typeof define.amd == 'object') define(definition) else this[name] = definition() }('domready', function (ready) { var fns = [], fn, f = false , doc = document , testEl = doc.documentElement , hack = testEl.doScroll , domContentLoaded = 'DOMContentLoaded' , addEventListener = 'addEventListener' , onreadystatechange = 'onreadystatechange' , readyState = 'readyState' , loadedRgx = hack ? /^loaded|^c/ : /^loaded|c/ , loaded = loadedRgx.test(doc[readyState]) function flush(f) { loaded = 1 while (f = fns.shift()) f() } doc[addEventListener] && doc[addEventListener](domContentLoaded, fn = function () { doc.removeEventListener(domContentLoaded, fn, f) flush() }, f) hack && doc.attachEvent(onreadystatechange, fn = function () { if (/^c/.test(doc[readyState])) { doc.detachEvent(onreadystatechange, fn) flush() } }) return (ready = hack ? function (fn) { self != top ? loaded ? fn() : fns.push(fn) : function () { try { testEl.doScroll('left') } catch (e) { return setTimeout(function() { ready(fn) }, 50) } fn() }() } : function (fn) { loaded ? fn() : fns.push(fn) }) }) },{}],6:[function(require,module,exports){ /** * Module dependencies. */ var Emitter = require('emitter'); var reduce = require('reduce'); /** * Root reference for iframes. */ var root = 'undefined' == typeof window ? this : window; /** * Noop. */ function noop(){}; /** * Check if `obj` is a host object, * we don't want to serialize these :) * * TODO: future proof, move to compoent land * * @param {Object} obj * @return {Boolean} * @api private */ function isHost(obj) { var str = {}.toString.call(obj); switch (str) { case '[object File]': case '[object Blob]': case '[object FormData]': return true; default: return false; } } /** * Determine XHR. */ function getXHR() { if (root.XMLHttpRequest && ('file:' != root.location.protocol || !root.ActiveXObject)) { return new XMLHttpRequest; } else { try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {} try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {} try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {} try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {} } return false; } /** * Removes leading and trailing whitespace, added to support IE. * * @param {String} s * @return {String} * @api private */ var trim = ''.trim ? function(s) { return s.trim(); } : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); }; /** * Check if `obj` is an object. * * @param {Object} obj * @return {Boolean} * @api private */ function isObject(obj) { return obj === Object(obj); } /** * Serialize the given `obj`. * * @param {Object} obj * @return {String} * @api private */ function serialize(obj) { if (!isObject(obj)) return obj; var pairs = []; for (var key in obj) { if (null != obj[key]) { pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key])); } } return pairs.join('&'); } /** * Expose serialization method. */ request.serializeObject = serialize; /** * Parse the given x-www-form-urlencoded `str`. * * @param {String} str * @return {Object} * @api private */ function parseString(str) { var obj = {}; var pairs = str.split('&'); var parts; var pair; for (var i = 0, len = pairs.length; i < len; ++i) { pair = pairs[i]; parts = pair.split('='); obj[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]); } return obj; } /** * Expose parser. */ request.parseString = parseString; /** * Default MIME type map. * * superagent.types.xml = 'application/xml'; * */ request.types = { html: 'text/html', json: 'application/json', xml: 'application/xml', urlencoded: 'application/x-www-form-urlencoded', 'form': 'application/x-www-form-urlencoded', 'form-data': 'application/x-www-form-urlencoded' }; /** * Default serialization map. * * superagent.serialize['application/xml'] = function(obj){ * return 'generated xml here'; * }; * */ request.serialize = { 'application/x-www-form-urlencoded': serialize, 'application/json': JSON.stringify }; /** * Default parsers. * * superagent.parse['application/xml'] = function(str){ * return { object parsed from str }; * }; * */ request.parse = { 'application/x-www-form-urlencoded': parseString, 'application/json': JSON.parse }; /** * Parse the given header `str` into * an object containing the mapped fields. * * @param {String} str * @return {Object} * @api private */ function parseHeader(str) { var lines = str.split(/\r?\n/); var fields = {}; var index; var line; var field; var val; lines.pop(); for (var i = 0, len = lines.length; i < len; ++i) { line = lines[i]; index = line.indexOf(':'); field = line.slice(0, index).toLowerCase(); val = trim(line.slice(index + 1)); fields[field] = val; } return fields; } /** * Return the mime type for the given `str`. * * @param {String} str * @return {String} * @api private */ function type(str){ return str.split(/ *; */).shift(); }; /** * Return header field parameters. * * @param {String} str * @return {Object} * @api private */ function params(str){ return reduce(str.split(/ *; */), function(obj, str){ var parts = str.split(/ *= */) , key = parts.shift() , val = parts.shift(); if (key && val) obj[key] = val; return obj; }, {}); }; /** * Initialize a new `Response` with the given `xhr`. * * - set flags (.ok, .error, etc) * - parse header * * Examples: * * Aliasing `superagent` as `request` is nice: * * request = superagent; * * We can use the promise-like API, or pass callbacks: * * request.get('/').end(function(res){}); * request.get('/', function(res){}); * * Sending data can be chained: * * request * .post('/user') * .send({ name: 'tj' }) * .end(function(res){}); * * Or passed to `.send()`: * * request * .post('/user') * .send({ name: 'tj' }, function(res){}); * * Or passed to `.post()`: * * request * .post('/user', { name: 'tj' }) * .end(function(res){}); * * Or further reduced to a single call for simple cases: * * request * .post('/user', { name: 'tj' }, function(res){}); * * @param {XMLHTTPRequest} xhr * @param {Object} options * @api private */ function Response(req, options) { options = options || {}; this.req = req; this.xhr = this.req.xhr; this.text = this.req.method !='HEAD' ? this.xhr.responseText : null; this.setStatusProperties(this.xhr.status); this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders()); this.header['content-type'] = this.xhr.getResponseHeader('content-type'); this.setHeaderProperties(this.header); this.body = this.req.method != 'HEAD' ? this.parseBody(this.text) : null; } /** * Get case-insensitive `field` value. * * @param {String} field * @return {String} * @api public */ Response.prototype.get = function(field){ return this.header[field.toLowerCase()]; }; /** * Set header related properties: * * - `.type` the content type without params * * A response of "Content-Type: text/plain; charset=utf-8" * will provide you with a `.type` of "text/plain". * * @param {Object} header * @api private */ Response.prototype.setHeaderProperties = function(header){ var ct = this.header['content-type'] || ''; this.type = type(ct); var obj = params(ct); for (var key in obj) this[key] = obj[key]; }; /** * Parse the given body `str`. * * Used for auto-parsing of bodies. Parsers * are defined on the `superagent.parse` object. * * @param {String} str * @return {Mixed} * @api private */ Response.prototype.parseBody = function(str){ var parse = request.parse[this.type]; return parse && str && str.length ? parse(str) : null; }; /** * Set flags such as `.ok` based on `status`. * * For example a 2xx response will give you a `.ok` of __true__ * whereas 5xx will be __false__ and `.error` will be __true__. The * `.clientError` and `.serverError` are also available to be more * specific, and `.statusType` is the class of error ranging from 1..5 * sometimes useful for mapping respond colors etc. * * "sugar" properties are also defined for common cases. Currently providing: * * - .noContent * - .badRequest * - .unauthorized * - .notAcceptable * - .notFound * * @param {Number} status * @api private */ Response.prototype.setStatusProperties = function(status){ var type = status / 100 | 0; this.status = status; this.statusType = type; this.info = 1 == type; this.ok = 2 == type; this.clientError = 4 == type; this.serverError = 5 == type; this.error = (4 == type || 5 == type) ? this.toError() : false; this.accepted = 202 == status; this.noContent = 204 == status || 1223 == status; this.badRequest = 400 == status; this.unauthorized = 401 == status; this.notAcceptable = 406 == status; this.notFound = 404 == status; this.forbidden = 403 == status; }; /** * Return an `Error` representative of this response. * * @return {Error} * @api public */ Response.prototype.toError = function(){ var req = this.req; var method = req.method; var url = req.url; var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')'; var err = new Error(msg); err.status = this.status; err.method = method; err.url = url; return err; }; /** * Expose `Response`. */ request.Response = Response; /** * Initialize a new `Request` with the given `method` and `url`. * * @param {String} method * @param {String} url * @api public */ function Request(method, url) { var self = this; Emitter.call(this); this._query = this._query || []; this.method = method; this.url = url; this.header = {}; this._header = {}; this.on('end', function(){ var err = null; var res = null; try { res = new Response(self); } catch(e) { err = new Error('Parser is unable to parse the response'); err.parse = true; err.original = e; } self.callback(err, res); }); } /** * Mixin `Emitter`. */ Emitter(Request.prototype); /** * Allow for extension */ Request.prototype.use = function(fn) { fn(this); return this; } /** * Set timeout to `ms`. * * @param {Number} ms * @return {Request} for chaining * @api public */ Request.prototype.timeout = function(ms){ this._timeout = ms; return this; }; /** * Clear previous timeout. * * @return {Request} for chaining * @api public */ Request.prototype.clearTimeout = function(){ this._timeout = 0; clearTimeout(this._timer); return this; }; /** * Abort the request, and clear potential timeout. * * @return {Request} * @api public */ Request.prototype.abort = function(){ if (this.aborted) return; this.aborted = true; this.xhr.abort(); this.clearTimeout(); this.emit('abort'); return this; }; /** * Set header `field` to `val`, or multiple fields with one object. * * Examples: * * req.get('/') * .set('Accept', 'application/json') * .set('X-API-Key', 'foobar') * .end(callback); * * req.get('/') * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) * .end(callback); * * @param {String|Object} field * @param {String} val * @return {Request} for chaining * @api public */ Request.prototype.set = function(field, val){ if (isObject(field)) { for (var key in field) { this.set(key, field[key]); } return this; } this._header[field.toLowerCase()] = val; this.header[field] = val; return this; }; /** * Remove header `field`. * * Example: * * req.get('/') * .unset('User-Agent') * .end(callback); * * @param {String} field * @return {Request} for chaining * @api public */ Request.prototype.unset = function(field){ delete this._header[field.toLowerCase()]; delete this.header[field]; return this; }; /** * Get case-insensitive header `field` value. * * @param {String} field * @return {String} * @api private */ Request.prototype.getHeader = function(field){ return this._header[field.toLowerCase()]; }; /** * Set Content-Type to `type`, mapping values from `request.types`. * * Examples: * * superagent.types.xml = 'application/xml'; * * request.post('/') * .type('xml') * .send(xmlstring) * .end(callback); * * request.post('/') * .type('application/xml') * .send(xmlstring) * .end(callback); * * @param {String} type * @return {Request} for chaining * @api public */ Request.prototype.type = function(type){ this.set('Content-Type', request.types[type] || type); return this; }; /** * Set Accept to `type`, mapping values from `request.types`. * * Examples: * * superagent.types.json = 'application/json'; * * request.get('/agent') * .accept('json') * .end(callback); * * request.get('/agent') * .accept('application/json') * .end(callback); * * @param {String} accept * @return {Request} for chaining * @api public */ Request.prototype.accept = function(type){ this.set('Accept', request.types[type] || type); return this; }; /** * Set Authorization field value with `user` and `pass`. * * @param {String} user * @param {String} pass * @return {Request} for chaining * @api public */ Request.prototype.auth = function(user, pass){ var str = btoa(user + ':' + pass); this.set('Authorization', 'Basic ' + str); return this; }; /** * Add query-string `val`. * * Examples: * * request.get('/shoes') * .query('size=10') * .query({ color: 'blue' }) * * @param {Object|String} val * @return {Request} for chaining * @api public */ Request.prototype.query = function(val){ if ('string' != typeof val) val = serialize(val); if (val) this._query.push(val); return this; }; /** * Write the field `name` and `val` for "multipart/form-data" * request bodies. * * ``` js * request.post('/upload') * .field('foo', 'bar') * .end(callback); * ``` * * @param {String} name * @param {String|Blob|File} val * @return {Request} for chaining * @api public */ Request.prototype.field = function(name, val){ if (!this._formData) this._formData = new FormData(); this._formData.append(name, val); return this; }; /** * Queue the given `file` as an attachment to the specified `field`, * with optional `filename`. * * ``` js * request.post('/upload') * .attach(new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"})) * .end(callback); * ``` * * @param {String} field * @param {Blob|File} file * @param {String} filename * @return {Request} for chaining * @api public */ Request.prototype.attach = function(field, file, filename){ if (!this._formData) this._formData = new FormData(); this._formData.append(field, file, filename); return this; }; /** * Send `data`, defaulting the `.type()` to "json" when * an object is given. * * Examples: * * * request.get('/search') * .end(callback) * * * request.get('/search') * .send({ search: 'query' }) * .send({ range: '1..5' }) * .send({ order: 'desc' }) * .end(callback) * * * request.post('/user') * .type('json') * .send('{"name":"tj"}) * .end(callback) * * * request.post('/user') * .send({ name: 'tj' }) * .end(callback) * * * request.post('/user') * .type('form') * .send('name=tj') * .end(callback) * * * request.post('/user') * .type('form') * .send({ name: 'tj' }) * .end(callback) * * * request.post('/user') * .send('name=tobi') * .send('species=ferret') * .end(callback) * * @param {String|Object} data * @return {Request} for chaining * @api public */ Request.prototype.send = function(data){ var obj = isObject(data); var type = this.getHeader('Content-Type'); if (obj && isObject(this._data)) { for (var key in data) { this._data[key] = data[key]; } } else if ('string' == typeof data) { if (!type) this.type('form'); type = this.getHeader('Content-Type'); if ('application/x-www-form-urlencoded' == type) { this._data = this._data ? this._data + '&' + data : data; } else { this._data = (this._data || '') + data; } } else { this._data = data; } if (!obj) return this; if (!type) this.type('json'); return this; }; /** * Invoke the callback with `err` and `res` * and handle arity check. * * @param {Error} err * @param {Response} res * @api private */ Request.prototype.callback = function(err, res){ var fn = this._callback; this.clearTimeout(); if (2 == fn.length) return fn(err, res); if (err) return this.emit('error', err); fn(res); }; /** * Invoke callback with x-domain error. * * @api private */ Request.prototype.crossDomainError = function(){ var err = new Error('Origin is not allowed by Access-Control-Allow-Origin'); err.crossDomain = true; this.callback(err); }; /** * Invoke callback with timeout error. * * @api private */ Request.prototype.timeoutError = function(){ var timeout = this._timeout; var err = new Error('timeout of ' + timeout + 'ms exceeded'); err.timeout = timeout; this.callback(err); }; /** * Enable transmission of cookies with x-domain requests. * * Note that for this to work the origin must not be * using "Access-Control-Allow-Origin" with a wildcard, * and also must set "Access-Control-Allow-Credentials" * to "true". * * @api public */ Request.prototype.withCredentials = function(){ this._withCredentials = true; return this; }; /** * Initiate request, invoking callback `fn(res)` * with an instanceof `Response`. * * @param {Function} fn * @return {Request} for chaining * @api public */ Request.prototype.end = function(fn){ var self = this; var xhr = this.xhr = getXHR(); var query = this._query.join('&'); var timeout = this._timeout; var data = this._formData || this._data; this._callback = fn || noop; xhr.onreadystatechange = function(){ if (4 != xhr.readyState) return; if (0 == xhr.status) { if (self.aborted) return self.timeoutError(); return self.crossDomainError(); } self.emit('end'); }; if (xhr.upload) { xhr.upload.onprogress = function(e){ e.percent = e.loaded / e.total * 100; self.emit('progress', e); }; } if (timeout && !this._timer) { this._timer = setTimeout(function(){ self.abort(); }, timeout); } if (query) { query = request.serializeObject(query); this.url += ~this.url.indexOf('?') ? '&' + query : '?' + query; } xhr.open(this.method, this.url, true); if (this._withCredentials) xhr.withCredentials = true; if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !isHost(data)) { var serialize = request.serialize[this.getHeader('Content-Type')]; if (serialize) data = serialize(data); } for (var field in this.header) { if (null == this.header[field]) continue; xhr.setRequestHeader(field, this.header[field]); } this.emit('request', this); xhr.send(data); return this; }; /** * Expose `Request`. */ request.Request = Request; /** * Issue a request: * * Examples: * * request('GET', '/users').end(callback) * request('/users').end(callback) * request('/users', callback) * * @param {String} method * @param {String|Function} url or callback * @return {Request} * @api public */ function request(method, url) { if ('function' == typeof url) { return new Request('GET', method).end(url); } if (1 == arguments.length) { return new Request('GET', method); } return new Request(method, url); } /** * GET `url` with optional callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} data or fn * @param {Function} fn * @return {Request} * @api public */ request.get = function(url, data, fn){ var req = request('GET', url); if ('function' == typeof data) fn = data, data = null; if (data) req.query(data); if (fn) req.end(fn); return req; }; /** * HEAD `url` with optional callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} data or fn * @param {Function} fn * @return {Request} * @api public */ request.head = function(url, data, fn){ var req = request('HEAD', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * DELETE `url` with optional callback `fn(res)`. * * @param {String} url * @param {Function} fn * @return {Request} * @api public */ request.del = function(url, fn){ var req = request('DELETE', url); if (fn) req.end(fn); return req; }; /** * PATCH `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed} data * @param {Function} fn * @return {Request} * @api public */ request.patch = function(url, data, fn){ var req = request('PATCH', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * POST `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed} data * @param {Function} fn * @return {Request} * @api public */ request.post = function(url, data, fn){ var req = request('POST', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * PUT `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} data or fn * @param {Function} fn * @return {Request} * @api public */ request.put = function(url, data, fn){ var req = request('PUT', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * Expose `request`. */ module.exports = request; },{"emitter":7,"reduce":8}],7:[function(require,module,exports){ arguments[4][4][0].apply(exports,arguments) },{"dup":4}],8:[function(require,module,exports){ /** * Reduce `arr` with `fn`. * * @param {Array} arr * @param {Function} fn * @param {Mixed} initial * * TODO: combatible error handling? */ module.exports = function(arr, fn, initial){ var idx = 0; var len = arr.length; var curr = arguments.length == 3 ? initial : arr[idx++]; while (idx < len) { curr = fn.call(null, curr, arr[idx], ++idx, arr); } return curr; }; },{}],9:[function(require,module,exports){ var Keen = require("./index"), each = require("./utils/each"); module.exports = function(){ var loaded = window['Keen'] || null, cached = window['_' + 'Keen'] || null, clients, ready; if (loaded && cached) { clients = cached['clients'] || {}, ready = cached['ready'] || []; each(clients, function(client, id){ each(Keen.prototype, function(method, key){ loaded.prototype[key] = method; }); each(["Query", "Request", "Dataset", "Dataviz"], function(name){ loaded[name] = (Keen[name]) ? Keen[name] : function(){}; }); if (client._config) { client.configure.call(client, client._config); } if (client._setGlobalProperties) { each(client._setGlobalProperties, function(fn){ client.setGlobalProperties.apply(client, fn); }); } if (client._addEvent) { each(client._addEvent, function(obj){ client.addEvent.apply(client, obj); }); } var callback = client._on || []; if (client._on) { each(client._on, function(obj){ client.on.apply(client, obj); }); client.trigger('ready'); } each(["_config", "_setGlobalProperties", "_addEvent", "_on"], function(name){ if (client[name]) { client[name] = undefined; try{ delete client[name]; } catch(e){} } }); }); each(ready, function(cb, i){ Keen.once("ready", cb); }); } window['_' + 'Keen'] = undefined; try { delete window['_' + 'Keen'] } catch(e) {} }; },{"./index":17,"./utils/each":23}],10:[function(require,module,exports){ var Emitter = require('component-emitter'); Emitter.prototype.trigger = Emitter.prototype.emit; module.exports = Emitter; },{"component-emitter":4}],11:[function(require,module,exports){ module.exports = function(){ return "undefined" == typeof window ? "server" : "browser"; }; },{}],12:[function(require,module,exports){ var each = require('../utils/each'), JSON2 = require('JSON2'); module.exports = function(params){ var query = []; each(params, function(value, key){ if ('string' !== typeof value) { value = JSON2.stringify(value); } query.push(key + '=' + encodeURIComponent(value)); }); return '?' + query.join('&'); }; },{"../utils/each":23,"JSON2":2}],13:[function(require,module,exports){ module.exports = function(){ if ("undefined" !== typeof window) { if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) { return 2000; } } return 16000; }; },{}],14:[function(require,module,exports){ module.exports = function() { var root = "undefined" == typeof window ? this : window; if (root.XMLHttpRequest && ("file:" != root.location.protocol || !root.ActiveXObject)) { return new XMLHttpRequest; } else { try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} } return false; }; },{}],15:[function(require,module,exports){ module.exports = function(err, res, callback) { var cb = callback || function() {}; if (res && !res.ok) { var is_err = res.body && res.body.error_code; err = new Error(is_err ? res.body.message : 'Unknown error occurred'); err.code = is_err ? res.body.error_code : 'UnknownError'; } if (err) { cb(err, null); } else { cb(null, res.body); } return; }; },{}],16:[function(require,module,exports){ var superagent = require('superagent'); var each = require('../utils/each'), getXHR = require('./get-xhr-object'); module.exports = function(type, opts){ return function(request) { var __super__ = request.constructor.prototype.end; if ( 'undefined' === typeof window ) return; request.requestType = request.requestType || {}; request.requestType['type'] = type; request.requestType['options'] = request.requestType['options'] || { async: true, success: { responseText: '{ "created": true }', status: 201 }, error: { responseText: '{ "error_code": "ERROR", "message": "Request failed" }', status: 404 } }; if (opts) { if ( 'boolean' === typeof opts.async ) { request.requestType['options'].async = opts.async; } if ( opts.success ) { extend(request.requestType['options'].success, opts.success); } if ( opts.error ) { extend(request.requestType['options'].error, opts.error); } } request.end = function(fn){ var self = this, reqType = (this.requestType) ? this.requestType['type'] : 'xhr', query, timeout; if ( ('GET' !== self['method'] || 'xhr' === reqType) && self.requestType['options'].async ) { __super__.call(self, fn); return; } query = self._query.join('&'); timeout = self._timeout; self._callback = fn || noop; if (timeout && !self._timer) { self._timer = setTimeout(function(){ abortRequest.call(self); }, timeout); } if (query) { query = superagent.serializeObject(query); self.url += ~self.url.indexOf('?') ? '&' + query : '?' + query; } self.emit('request', self); if ( !self.requestType['options'].async ) { sendXhrSync.call(self); } else if ( 'jsonp' === reqType ) { sendJsonp.call(self); } else if ( 'beacon' === reqType ) { sendBeacon.call(self); } return self; }; return request; }; }; function sendXhrSync(){ var xhr = getXHR(); if (xhr) { xhr.open('GET', this.url, false); xhr.send(null); } return this; } function sendJsonp(){ var self = this, timestamp = new Date().getTime(), script = document.createElement('script'), parent = document.getElementsByTagName('head')[0], callbackName = 'keenJSONPCallback', loaded = false; callbackName += timestamp; while (callbackName in window) { callbackName += 'a'; } window[callbackName] = function(response) { if (loaded === true) return; loaded = true; handleSuccess.call(self, response); cleanup(); }; script.src = self.url + '&jsonp=' + callbackName; parent.appendChild(script); script.onreadystatechange = function() { if (loaded === false && self.readyState === 'loaded') { loaded = true; handleError.call(self); cleanup(); } }; script.onerror = function() { if (loaded === false) { loaded = true; handleError.call(self); cleanup(); } }; function cleanup(){ window[callbackName] = undefined; try { delete window[callbackName]; } catch(e){} parent.removeChild(script); } } function sendBeacon(){ var self = this, img = document.createElement('img'), loaded = false; img.onload = function() { loaded = true; if ('naturalHeight' in this) { if (this.naturalHeight + this.naturalWidth === 0) { this.onerror(); return; } } else if (this.width + this.height === 0) { this.onerror(); return; } handleSuccess.call(self); }; img.onerror = function() { loaded = true; handleError.call(self); }; img.src = self.url + '&c=clv1'; } function handleSuccess(res){ var opts = this.requestType['options']['success'], response = ''; xhrShim.call(this, opts); if (res) { try { response = JSON.stringify(res); } catch(e) {} } else { response = opts['responseText']; } this.xhr.responseText = response; this.xhr.status = opts['status']; this.emit('end'); } function handleError(){ var opts = this.requestType['options']['error']; xhrShim.call(this, opts); this.xhr.responseText = opts['responseText']; this.xhr.status = opts['status']; this.emit('end'); } function abortRequest(){ this.aborted = true; this.clearTimeout(); this.emit('abort'); } function xhrShim(opts){ this.xhr = { getAllResponseHeaders: function(){ return ''; }, getResponseHeader: function(){ return 'application/json'; }, responseText: opts['responseText'], status: opts['status'] }; return this; } },{"../utils/each":23,"./get-xhr-object":14,"superagent":6}],17:[function(require,module,exports){ var root = this; var previous_Keen = root.Keen; var extend = require('./utils/extend'); var Emitter = require('./helpers/emitter-shim'); function Keen(config) { this.configure(config || {}); Keen.trigger('client', this); } Keen.debug = false; Keen.enabled = true; Keen.loaded = true; Keen.version = '3.2.0'; Emitter(Keen); Emitter(Keen.prototype); Keen.prototype.configure = function(cfg){ var config = cfg || {}; if (config['host']) { config['host'].replace(/.*?:\/\//g, ''); } if (config.protocol && config.protocol === 'auto') { config['protocol'] = location.protocol.replace(/:/g, ''); } this.config = { projectId : config.projectId, writeKey : config.writeKey, readKey : config.readKey, masterKey : config.masterKey, requestType : config.requestType || 'jsonp', host : config['host'] || 'api.keen.io/3.0', protocol : config['protocol'] || 'https', globalProperties: null }; if (Keen.debug) { this.on('error', Keen.log); } this.trigger('ready'); }; Keen.prototype.projectId = function(str){ if (!arguments.length) return this.config.projectId; this.config.projectId = (str ? String(str) : null); return this; }; Keen.prototype.masterKey = function(str){ if (!arguments.length) return this.config.masterKey; this.config.masterKey = (str ? String(str) : null); return this; }; Keen.prototype.readKey = function(str){ if (!arguments.length) return this.config.readKey; this.config.readKey = (str ? String(str) : null); return this; }; Keen.prototype.writeKey = function(str){ if (!arguments.length) return this.config.writeKey; this.config.writeKey = (str ? String(str) : null); return this; }; Keen.prototype.url = function(path){ if (!this.projectId()) { this.trigger('error', 'Client is missing projectId property'); return; } return this.config.protocol + '://' + this.config.host + '/projects/' + this.projectId() + path; }; Keen.log = function(message) { if (Keen.debug && typeof console == 'object') { console.log('[Keen IO]', message); } }; Keen.noConflict = function(){ root.Keen = previous_Keen; return Keen; }; Keen.ready = function(fn){ if (Keen.loaded) { fn(); } else { Keen.once('ready', fn); } }; module.exports = Keen; },{"./helpers/emitter-shim":10,"./utils/extend":24}],18:[function(require,module,exports){ var JSON2 = require('JSON2'); var request = require('superagent'); var Keen = require('../index'); var base64 = require('../utils/base64'), each = require('../utils/each'), getContext = require('../helpers/get-context'), getQueryString = require('../helpers/get-query-string'), getUrlMaxLength = require('../helpers/get-url-max-length'), getXHR = require('../helpers/get-xhr-object'), requestTypes = require('../helpers/superagent-request-types'), responseHandler = require('../helpers/superagent-handle-response'); module.exports = function(collection, payload, callback, async) { var self = this, urlBase = this.url('/events/' + collection), reqType = this.config.requestType, data = {}, cb = callback, isAsync, getUrl; isAsync = ('boolean' === typeof async) ? async : true; if (!Keen.enabled) { handleValidationError.call(self, 'Keen.enabled = false'); return; } if (!self.projectId()) { handleValidationError.call(self, 'Missing projectId property'); return; } if (!self.writeKey()) { handleValidationError.call(self, 'Missing writeKey property'); return; } if (!collection || typeof collection !== 'string') { handleValidationError.call(self, 'Collection name must be a string'); return; } if (self.config.globalProperties) { data = self.config.globalProperties(collection); } each(payload, function(value, key){ data[key] = value; }); if ( !getXHR() && 'xhr' === reqType ) { reqType = 'jsonp'; } if ( 'xhr' !== reqType || !isAsync ) { getUrl = prepareGetRequest.call(self, urlBase, data); } if ( getUrl && getContext() === 'browser' ) { request .get(getUrl) .use(function(req){ req.async = isAsync; return req; }) .use(requestTypes(reqType)) .end(handleResponse); } else if ( getXHR() || getContext() === 'server' ) { request .post(urlBase) .set('Content-Type', 'application/json') .set('Authorization', self.writeKey()) .send(data) .end(handleResponse); } else { self.trigger('error', 'Request not sent: URL length exceeds current browser limit, and XHR (POST) is not supported.'); } function handleResponse(err, res){ responseHandler(err, res, cb); cb = callback = null; } function handleValidationError(msg){ var err = 'Event not recorded: ' + msg; self.trigger('error', err); if (cb) { cb.call(self, err, null); cb = callback = null; } } return; }; function prepareGetRequest(url, data){ url += getQueryString({ api_key : this.writeKey(), data : base64.encode( JSON2.stringify(data) ), modified : new Date().getTime() }); return ( url.length < getUrlMaxLength() ) ? url : false; } },{"../helpers/get-context":11,"../helpers/get-query-string":12,"../helpers/get-url-max-length":13,"../helpers/get-xhr-object":14,"../helpers/superagent-handle-response":15,"../helpers/superagent-request-types":16,"../index":17,"../utils/base64":22,"../utils/each":23,"JSON2":2,"superagent":6}],19:[function(require,module,exports){ var Keen = require('../index'); var request = require('superagent'); var each = require('../utils/each'), getContext = require('../helpers/get-context'), getXHR = require('../helpers/get-xhr-object'), requestTypes = require('../helpers/superagent-request-types'), responseHandler = require('../helpers/superagent-handle-response'); module.exports = function(payload, callback) { var self = this, urlBase = this.url('/events'), data = {}, cb = callback; if (!Keen.enabled) { handleValidationError.call(self, 'Keen.enabled = false'); return; } if (!self.projectId()) { handleValidationError.call(self, 'Missing projectId property'); return; } if (!self.writeKey()) { handleValidationError.call(self, 'Missing writeKey property'); return; } if (arguments.length > 2) { handleValidationError.call(self, 'Incorrect arguments provided to #addEvents method'); return; } if (typeof payload !== 'object' || payload instanceof Array) { handleValidationError.call(self, 'Request payload must be an object'); return; } if (self.config.globalProperties) { each(payload, function(events, collection){ each(events, function(body, index){ var base = self.config.globalProperties(collection); each(body, function(value, key){ base[key] = value; }); data[collection].push(base); }); }); } else { data = payload; } if ( getXHR() || getContext() === 'server' ) { request .post(urlBase) .set('Content-Type', 'application/json') .set('Authorization', self.writeKey()) .send(data) .end(function(err, res){ responseHandler(err, res, cb); cb = callback = null; }); } else { self.trigger('error', 'Events not recorded: XHR support is required for batch upload'); } function handleValidationError(msg){ var err = 'Events not recorded: ' + msg; self.trigger('error', err); if (cb) { cb.call(self, err, null); cb = callback = null; } } return; }; },{"../helpers/get-context":11,"../helpers/get-xhr-object":14,"../helpers/superagent-handle-response":15,"../helpers/superagent-request-types":16,"../index":17,"../utils/each":23,"superagent":6}],20:[function(require,module,exports){ module.exports = function(newGlobalProperties) { if (newGlobalProperties && typeof(newGlobalProperties) == "function") { this.config.globalProperties = newGlobalProperties; } else { this.trigger("error", "Invalid value for global properties: " + newGlobalProperties); } }; },{}],21:[function(require,module,exports){ var addEvent = require("./addEvent"); module.exports = function(jsEvent, eventCollection, payload, timeout, timeoutCallback){ var evt = jsEvent, target = (evt.currentTarget) ? evt.currentTarget : (evt.srcElement || evt.target), timer = timeout || 500, triggered = false, targetAttr = "", callback, win; if (target.getAttribute !== void 0) { targetAttr = target.getAttribute("target"); } else if (target.target) { targetAttr = target.target; } if ((targetAttr == "_blank" || targetAttr == "blank") && !evt.metaKey) { win = window.open("about:blank"); win.document.location = target.href; } if (target.nodeName === "A") { callback = function(){ if(!triggered && !evt.metaKey && (targetAttr !== "_blank" && targetAttr !== "blank")){ triggered = true; window.location = target.href; } }; } else if (target.nodeName === "FORM") { callback = function(){ if(!triggered){ triggered = true; target.submit(); } }; } else { this.trigger("error", "#trackExternalLink method not attached to an <a> or <form> DOM element"); } if (timeoutCallback) { callback = function(){ if(!triggered){ triggered = true; timeoutCallback(); } }; } addEvent.call(this, eventCollection, payload, callback); setTimeout(callback, timer); if (!evt.metaKey) { return false; } }; },{"./addEvent":18}],22:[function(require,module,exports){ module.exports = { map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", encode: function (n) { "use strict"; var o = "", i = 0, m = this.map, i1, i2, i3, e1, e2, e3, e4; n = this.utf8.encode(n); while (i < n.length) { i1 = n.charCodeAt(i++); i2 = n.charCodeAt(i++); i3 = n.charCodeAt(i++); e1 = (i1 >> 2); e2 = (((i1 & 3) << 4) | (i2 >> 4)); e3 = (isNaN(i2) ? 64 : ((i2 & 15) << 2) | (i3 >> 6)); e4 = (isNaN(i2) || isNaN(i3)) ? 64 : i3 & 63; o = o + m.charAt(e1) + m.charAt(e2) + m.charAt(e3) + m.charAt(e4); } return o; }, decode: function (n) { "use strict"; var o = "", i = 0, m = this.map, cc = String.fromCharCode, e1, e2, e3, e4, c1, c2, c3; n = n.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < n.length) { e1 = m.indexOf(n.charAt(i++)); e2 = m.indexOf(n.charAt(i++)); e3 = m.indexOf(n.charAt(i++)); e4 = m.indexOf(n.charAt(i++)); c1 = (e1 << 2) | (e2 >> 4); c2 = ((e2 & 15) << 4) | (e3 >> 2); c3 = ((e3 & 3) << 6) | e4; o = o + (cc(c1) + ((e3 != 64) ? cc(c2) : "")) + (((e4 != 64) ? cc(c3) : "")); } return this.utf8.decode(o); }, utf8: { encode: function (n) { "use strict"; var o = "", i = 0, cc = String.fromCharCode, c; while (i < n.length) { c = n.charCodeAt(i++); o = o + ((c < 128) ? cc(c) : ((c > 127) && (c < 2048)) ? (cc((c >> 6) | 192) + cc((c & 63) | 128)) : (cc((c >> 12) | 224) + cc(((c >> 6) & 63) | 128) + cc((c & 63) | 128))); } return o; }, decode: function (n) { "use strict"; var o = "", i = 0, cc = String.fromCharCode, c2, c; while (i < n.length) { c = n.charCodeAt(i); o = o + ((c < 128) ? [cc(c), i++][0] : ((c > 191) && (c < 224)) ? [cc(((c & 31) << 6) | ((c2 = n.charCodeAt(i + 1)) & 63)), (i += 2)][0] : [cc(((c & 15) << 12) | (((c2 = n.charCodeAt(i + 1)) & 63) << 6) | ((c3 = n.charCodeAt(i + 2)) & 63)), (i += 3)][0]); } return o; } } }; },{}],23:[function(require,module,exports){ module.exports = function(o, cb, s){ var n; if (!o){ return 0; } s = !s ? o : s; if (o instanceof Array){ for (n=0; n<o.length; n++) { if (cb.call(s, o[n], n, o) === false){ return 0; } } } else { for (n in o){ if (o.hasOwnProperty(n)) { if (cb.call(s, o[n], n, o) === false){ return 0; } } } } return 1; }; },{}],24:[function(require,module,exports){ module.exports = function(target){ for (var i = 1; i < arguments.length; i++) { for (var prop in arguments[i]){ target[prop] = arguments[i][prop]; } } return target; }; },{}],25:[function(require,module,exports){ function parseParams(str){ var urlParams = {}, match, pl = /\+/g, search = /([^&=]+)=?([^&]*)/g, decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); }, query = str.split("?")[1]; while (!!(match=search.exec(query))) { urlParams[decode(match[1])] = decode(match[2]); } return urlParams; }; module.exports = parseParams; },{}],26:[function(require,module,exports){ (function (global){ ;(function (f) { if (typeof define === "function" && define.amd) { define("keen", [], function(){ return f(); }); } if (typeof exports === "object" && typeof module !== "undefined") { module.exports = f(); } var g = null; if (typeof window !== "undefined") { g = window; } else if (typeof global !== "undefined") { g = global; } else if (typeof self !== "undefined") { g = self; } if (g) { g.Keen = f(); } })(function() { "use strict"; var Keen = require("./core"), extend = require("./core/utils/extend"); extend(Keen.prototype, { "addEvent" : require("./core/lib/addEvent"), "addEvents" : require("./core/lib/addEvents"), "setGlobalProperties" : require("./core/lib/setGlobalProperties"), "trackExternalLink" : require("./core/lib/trackExternalLink") }); Keen.Base64 = require("./core/utils/base64"); Keen.utils = { "domready" : require("domready"), "each" : require("./core/utils/each"), "extend" : extend, "parseParams" : require("./core/utils/parseParams") }; if (Keen.loaded) { setTimeout(function(){ Keen.utils.domready(function(){ Keen.emit("ready"); }); }, 0); } require("./core/async")(); module.exports = Keen; return Keen; }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./core":17,"./core/async":9,"./core/lib/addEvent":18,"./core/lib/addEvents":19,"./core/lib/setGlobalProperties":20,"./core/lib/trackExternalLink":21,"./core/utils/base64":22,"./core/utils/each":23,"./core/utils/extend":24,"./core/utils/parseParams":25,"domready":5}]},{},[26]);
/* * jQuery UI Effects Pulsate 1.7.2 * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Effects/Pulsate * * Depends: * effects.core.js */ (function($) { $.effects.pulsate = function(o) { return this.queue(function() { // Create element var el = $(this); // Set options var mode = $.effects.setMode(el, o.options.mode || 'show'); // Set Mode var times = o.options.times || 5; // Default # of times var duration = o.duration ? o.duration / 2 : $.fx.speeds._default / 2; // Adjust if (mode == 'hide') times--; if (el.is(':hidden')) { // Show fadeIn el.css('opacity', 0); el.show(); // Show el.animate({opacity: 1}, duration, o.options.easing); times = times-2; } // Animate for (var i = 0; i < times; i++) { // Pulsate el.animate({opacity: 0}, duration, o.options.easing).animate({opacity: 1}, duration, o.options.easing); }; if (mode == 'hide') { // Last Pulse el.animate({opacity: 0}, duration, o.options.easing, function(){ el.hide(); // Hide if(o.callback) o.callback.apply(this, arguments); // Callback }); } else { el.animate({opacity: 0}, duration, o.options.easing).animate({opacity: 1}, duration, o.options.easing, function(){ if(o.callback) o.callback.apply(this, arguments); // Callback }); }; el.queue('fx', function() { el.dequeue(); }); el.dequeue(); }); }; })(jQuery);
var config = require('../config'), _ = require('underscore'), path = require('path'), when = require('when'), api = require('../api'), mailer = require('../mail'), errors = require('../errorHandling'), storage = require('../storage'), updateCheck = require('../update-check'), adminNavbar, adminControllers, loginSecurity = []; // TODO: combine path/navClass to single "slug(?)" variable with no prefix adminNavbar = { content: { name: 'Content', navClass: 'content', key: 'admin.navbar.content', path: '/' }, add: { name: 'New Post', navClass: 'editor', key: 'admin.navbar.editor', path: '/editor/' }, settings: { name: 'Settings', navClass: 'settings', key: 'admin.navbar.settings', path: '/settings/' } }; // TODO: make this a util or helper function setSelected(list, name) { _.each(list, function (item, key) { item.selected = key === name; }); return list; } adminControllers = { 'uploader': function (req, res) { var type = req.files.uploadimage.type, ext = path.extname(req.files.uploadimage.name).toLowerCase(), store = storage.get_storage(); if ((type !== 'image/jpeg' && type !== 'image/png' && type !== 'image/gif' && type !== 'image/svg+xml') || (ext !== '.jpg' && ext !== '.jpeg' && ext !== '.png' && ext !== '.gif' && ext !== '.svg' && ext !== '.svgz')) { return res.send(415, 'Unsupported Media Type'); } store .save(req.files.uploadimage) .then(function (url) { return res.send(url); }) .otherwise(function (e) { errors.logError(e); return res.send(500, e.message); }); }, 'login': function (req, res) { /*jslint unparam:true*/ res.render('login', { bodyClass: 'ghost-login', hideNavbar: true, adminNav: setSelected(adminNavbar, 'login') }); }, 'auth': function (req, res) { var currentTime = process.hrtime()[0], remoteAddress = req.connection.remoteAddress, denied = ''; loginSecurity = _.filter(loginSecurity, function (ipTime) { return (ipTime.time + 2 > currentTime); }); denied = _.find(loginSecurity, function (ipTime) { return (ipTime.ip === remoteAddress); }); if (!denied) { loginSecurity.push({ip: remoteAddress, time: currentTime}); api.users.check({email: req.body.email, pw: req.body.password}).then(function (user) { req.session.regenerate(function (err) { if (!err) { req.session.user = user.id; var redirect = config.paths().subdir + '/ghost/'; if (req.body.redirect) { redirect += decodeURIComponent(req.body.redirect); } // If this IP address successfully logins we // can remove it from the array of failed login attempts. loginSecurity = _.reject(loginSecurity, function (ipTime) { return ipTime.ip === remoteAddress; }); res.json(200, {redirect: redirect}); } }); }, function (error) { res.json(401, {error: error.message}); }); } else { res.json(401, {error: 'Slow down, there are way too many login attempts!'}); } }, 'changepw': function (req, res) { return api.users.changePassword({ currentUser: req.session.user, oldpw: req.body.password, newpw: req.body.newpassword, ne2pw: req.body.ne2password }).then(function () { res.json(200, {msg: 'Password changed successfully'}); }, function (error) { res.send(401, {error: error.message}); }); }, 'signup': function (req, res) { /*jslint unparam:true*/ res.render('signup', { bodyClass: 'ghost-signup', hideNavbar: true, adminNav: setSelected(adminNavbar, 'login') }); }, 'doRegister': function (req, res) { var name = req.body.name, email = req.body.email, password = req.body.password; api.users.add({ name: name, email: email, password: password }).then(function (user) { api.settings.edit('email', email).then(function () { var message = { to: email, subject: 'Your New Ghost Blog', html: '<p><strong>Hello!</strong></p>' + '<p>Good news! You\'ve successfully created a brand new Ghost blog over on ' + config().url + '</p>' + '<p>You can log in to your admin account with the following details:</p>' + '<p> Email Address: ' + email + '<br>' + 'Password: The password you chose when you signed up</p>' + '<p>Keep this email somewhere safe for future reference, and have fun!</p>' + '<p>xoxo</p>' + '<p>Team Ghost<br>' + '<a href="https://ghost.org">https://ghost.org</a></p>' }; mailer.send(message).otherwise(function (error) { errors.logError( error.message, "Unable to send welcome email, your blog will continue to function.", "Please see http://docs.ghost.org/mail/ for instructions on configuring email." ); }); req.session.regenerate(function (err) { if (!err) { if (req.session.user === undefined) { req.session.user = user.id; } res.json(200, {redirect: config.paths().subdir + '/ghost/'}); } }); }); }).otherwise(function (error) { res.json(401, {error: error.message}); }); }, 'forgotten': function (req, res) { /*jslint unparam:true*/ res.render('forgotten', { bodyClass: 'ghost-forgotten', hideNavbar: true, adminNav: setSelected(adminNavbar, 'login') }); }, 'generateResetToken': function (req, res) { var email = req.body.email; api.users.generateResetToken(email).then(function (token) { var siteLink = '<a href="' + config().url + '">' + config().url + '</a>', resetUrl = config().url.replace(/\/$/, '') + '/ghost/reset/' + token + '/', resetLink = '<a href="' + resetUrl + '">' + resetUrl + '</a>', message = { to: email, subject: 'Reset Password', html: '<p><strong>Hello!</strong></p>' + '<p>A request has been made to reset the password on the site ' + siteLink + '.</p>' + '<p>Please follow the link below to reset your password:<br><br>' + resetLink + '</p>' + '<p>Ghost</p>' }; return mailer.send(message); }).then(function success() { var notification = { type: 'success', message: 'Check your email for further instructions', status: 'passive', id: 'successresetpw' }; return api.notifications.add(notification).then(function () { res.json(200, {redirect: config.paths().subdir + '/ghost/signin/'}); }); }, function failure(error) { // TODO: This is kind of sketchy, depends on magic string error.message from Bookshelf. // TODO: It's debatable whether we want to just tell the user we sent the email in this case or not, we are giving away sensitive info here. if (error && error.message === 'EmptyResponse') { error.message = "Invalid email address"; } res.json(401, {error: error.message}); }); }, 'reset': function (req, res) { // Validate the request token var token = req.params.token; api.users.validateToken(token).then(function () { // Render the reset form res.render('reset', { bodyClass: 'ghost-reset', hideNavbar: true, adminNav: setSelected(adminNavbar, 'reset') }); }).otherwise(function (err) { // Redirect to forgotten if invalid token var notification = { type: 'error', message: 'Invalid or expired token', status: 'persistent', id: 'errorinvalidtoken' }; errors.logError(err, 'admin.js', "Please check the provided token for validity and expiration."); return api.notifications.add(notification).then(function () { res.redirect(config.paths().subdir + '/ghost/forgotten'); }); }); }, 'resetPassword': function (req, res) { var token = req.params.token, newPassword = req.param('newpassword'), ne2Password = req.param('ne2password'); api.users.resetPassword(token, newPassword, ne2Password).then(function () { var notification = { type: 'success', message: 'Password changed successfully.', status: 'passive', id: 'successresetpw' }; return api.notifications.add(notification).then(function () { res.json(200, {redirect: config.paths().subdir + '/ghost/signin/'}); }); }).otherwise(function (err) { // TODO: Better error message if we can tell whether the passwords didn't match or something res.json(401, {error: err.message}); }); }, 'logout': function (req, res) { req.session.destroy(); var notification = { type: 'success', message: 'You were successfully signed out', status: 'passive', id: 'successlogout' }; return api.notifications.add(notification).then(function () { res.redirect(config.paths().subdir + '/ghost/signin/'); }); }, 'index': function (req, res) { /*jslint unparam:true*/ function renderIndex() { res.render('content', { bodyClass: 'manage', adminNav: setSelected(adminNavbar, 'content') }); } when.join( updateCheck(res), when(renderIndex()) // an error here should just get logged ).otherwise(errors.logError); }, 'editor': function (req, res) { if (req.params.id !== undefined) { res.render('editor', { bodyClass: 'editor', adminNav: setSelected(adminNavbar, 'content') }); } else { res.render('editor', { bodyClass: 'editor', adminNav: setSelected(adminNavbar, 'add') }); } }, 'content': function (req, res) { /*jslint unparam:true*/ res.render('content', { bodyClass: 'manage', adminNav: setSelected(adminNavbar, 'content') }); }, 'settings': function (req, res, next) { // TODO: Centralise list/enumeration of settings panes, so we don't // run into trouble in future. var allowedSections = ['', 'general', 'user'], section = req.url.replace(/(^\/ghost\/settings[\/]*|\/$)/ig, ''); if (allowedSections.indexOf(section) < 0) { return next(); } res.render('settings', { bodyClass: 'settings', adminNav: setSelected(adminNavbar, 'settings') }); }, 'debug': { /* ugly temporary stuff for managing the app before it's properly finished */ index: function (req, res) { /*jslint unparam:true*/ res.render('debug', { bodyClass: 'settings', adminNav: setSelected(adminNavbar, 'settings') }); } } }; module.exports = adminControllers;
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'wsc', 'km', { btnIgnore: 'មិនផ្លាស់ប្តូរ', btnIgnoreAll: 'មិនផ្លាស់ប្តូរ ទាំងអស់', btnReplace: 'ជំនួស', btnReplaceAll: 'ជំនួសទាំងអស់', btnUndo: 'សារឡើងវិញ', changeTo: 'ផ្លាស់ប្តូរទៅ', errorLoading: 'Error loading application service host: %s.', ieSpellDownload: 'ពុំមានកម្មវិធីពិនិត្យអក្ខរាវិរុទ្ធ ។ តើចង់ទាញយកពីណា?', manyChanges: 'ការពិនិត្យអក្ខរាវិរុទ្ធបានចប់: %1 ពាក្យបានផ្លាស់ប្តូរ', noChanges: 'ការពិនិត្យអក្ខរាវិរុទ្ធបានចប់: ពុំមានផ្លាស់ប្តូរ', noMispell: 'ការពិនិត្យអក្ខរាវិរុទ្ធបានចប់: គ្មានកំហុស', noSuggestions: '- គ្មានសំណើរ -', notAvailable: 'Sorry, but service is unavailable now.', notInDic: 'គ្មានក្នុងវចនានុក្រម', oneChange: 'ការពិនិត្យអក្ខរាវិរុទ្ធបានចប់: ពាក្យមួយត្រូចបានផ្លាស់ប្តូរ', progress: 'កំពុងពិនិត្យអក្ខរាវិរុទ្ធ...', title: 'Spell Checker', toolbar: 'ពិនិត្យអក្ខរាវិរុទ្ធ' });
define( "dojo/cldr/nls/hu/hebrew", //begin v1.x content { "months-format-abbr": [ "Tisri", "Hesván", "Kiszlév", "Tévész", "Svát", "Ádár I", "Ádár", "Niszán", "Ijár", "Sziván", "Tamuz", "Áv", "Elul" ], "months-format-abbr-leap": "Ádár II", "months-format-wide": [ "Tisri", "Hesván", "Kiszlév", "Tévész", "Svát", "Ádár risón", "Ádár", "Niszán", "Ijár", "Sziván", "Tamuz", "Áv", "Elul" ], "months-format-wide-leap": "Ádár séni", "months-standAlone-abbr": [ "Tisri", "Hesván", "Kiszlév", "Tévész", "Svát", "Ádár risón", "Ádár", "Niszán", "Ijár", "Sziván", "Tamuz", "Áv", "Elul" ], "months-standAlone-abbr-leap": "Ádár II", "months-standAlone-wide": [ "Tisri", "Hesván", "Kiszlév", "Tévész", "Svát", "Ádár risón", "Ádár", "Niszán", "Ijár", "Sziván", "Tamuz", "Áv", "Elul" ], "months-standAlone-wide-leap": "Ádár II", "eraAbbr": [ "TÉ" ], "eraNames": [ "TÉ" ], "eraNarrow": [ "TÉ" ], "days-format-abbr": [ "V", "H", "K", "Sze", "Cs", "P", "Szo" ], "days-format-narrow": [ "V", "H", "K", "Sz", "Cs", "P", "Sz" ], "days-format-wide": [ "vasárnap", "hétfő", "kedd", "szerda", "csütörtök", "péntek", "szombat" ], "days-standAlone-abbr": [ "V", "H", "K", "Sze", "Cs", "P", "Szo" ], "days-standAlone-narrow": [ "V", "H", "K", "Sz", "Cs", "P", "Sz" ], "days-standAlone-wide": [ "vasárnap", "hétfő", "kedd", "szerda", "csütörtök", "péntek", "szombat" ], "quarters-format-abbr": [ "N1", "N2", "N3", "N4" ], "quarters-format-wide": [ "I. negyedév", "II. negyedév", "III. negyedév", "IV. negyedév" ], "quarters-standAlone-abbr": [ "N1", "N2", "N3", "N4" ], "quarters-standAlone-wide": [ "1. negyedév", "2. negyedév", "3. negyedév", "4. negyedév" ], "dayPeriods-format-narrow-am": "de.", "dayPeriods-format-narrow-pm": "du.", "dayPeriods-format-wide-am": "de.", "dayPeriods-format-wide-pm": "du.", "dateFormat-full": "y. MMMM d., EEEE", "dateFormat-long": "y. MMMM d.", "dateFormat-medium": "yyyy.MM.dd.", "dateFormat-short": "yyyy.MM.dd.", "dateFormatItem-Ed": "d., E", "dateFormatItem-h": "a h", "dateFormatItem-H": "H", "dateFormatItem-hm": "a h:mm", "dateFormatItem-Hm": "H:mm", "dateFormatItem-hms": "a h:mm:ss", "dateFormatItem-Hms": "H:mm:ss", "dateFormatItem-Md": "M. d.", "dateFormatItem-MEd": "M. d., E", "dateFormatItem-MMMd": "MMM d.", "dateFormatItem-MMMEd": "MMM d., E", "dateFormatItem-yM": "y.M.", "dateFormatItem-yMd": "yyyy.MM.dd.", "dateFormatItem-yMEd": "yyyy.MM.dd., E", "dateFormatItem-yMMM": "y. MMM", "dateFormatItem-yMMMd": "y. MMM d.", "dateFormatItem-yMMMEd": "y. MMM d., E", "dateFormatItem-yQQQ": "y. QQQ", "timeFormat-full": "H:mm:ss zzzz", "timeFormat-long": "H:mm:ss z", "timeFormat-medium": "H:mm:ss", "timeFormat-short": "H:mm" } //end v1.x content );
/** * @license AngularJS v1.5.9 * (c) 2010-2016 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular) {'use strict'; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Any commits to this file should be reviewed with security in mind. * * Changes to this file can potentially create security vulnerabilities. * * An approval from 2 Core members with history of modifying * * this file is required. * * * * Does the change somehow allow for arbitrary javascript to be executed? * * Or allows for someone to change the prototype of built-in objects? * * Or gives undesired access to variables likes document or window? * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ var $sanitizeMinErr = angular.$$minErr('$sanitize'); var bind; var extend; var forEach; var isDefined; var lowercase; var noop; var htmlParser; var htmlSanitizeWriter; /** * @ngdoc module * @name ngSanitize * @description * * # ngSanitize * * The `ngSanitize` module provides functionality to sanitize HTML. * * * <div doc-module-components="ngSanitize"></div> * * See {@link ngSanitize.$sanitize `$sanitize`} for usage. */ /** * @ngdoc service * @name $sanitize * @kind function * * @description * Sanitizes an html string by stripping all potentially dangerous tokens. * * The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are * then serialized back to properly escaped html string. This means that no unsafe input can make * it into the returned string. * * The whitelist for URL sanitization of attribute values is configured using the functions * `aHrefSanitizationWhitelist` and `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider * `$compileProvider`}. * * The input may also contain SVG markup if this is enabled via {@link $sanitizeProvider}. * * @param {string} html HTML input. * @returns {string} Sanitized HTML. * * @example <example module="sanitizeExample" deps="angular-sanitize.js" name="sanitize-service"> <file name="index.html"> <script> angular.module('sanitizeExample', ['ngSanitize']) .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) { $scope.snippet = '<p style="color:blue">an html\n' + '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' + 'snippet</p>'; $scope.deliberatelyTrustDangerousSnippet = function() { return $sce.trustAsHtml($scope.snippet); }; }]); </script> <div ng-controller="ExampleController"> Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea> <table> <tr> <td>Directive</td> <td>How</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="bind-html-with-sanitize"> <td>ng-bind-html</td> <td>Automatically uses $sanitize</td> <td><pre>&lt;div ng-bind-html="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng-bind-html="snippet"></div></td> </tr> <tr id="bind-html-with-trust"> <td>ng-bind-html</td> <td>Bypass $sanitize by explicitly trusting the dangerous value</td> <td> <pre>&lt;div ng-bind-html="deliberatelyTrustDangerousSnippet()"&gt; &lt;/div&gt;</pre> </td> <td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td> </tr> <tr id="bind-default"> <td>ng-bind</td> <td>Automatically escapes</td> <td><pre>&lt;div ng-bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng-bind="snippet"></div></td> </tr> </table> </div> </file> <file name="protractor.js" type="protractor"> it('should sanitize the html snippet by default', function() { expect(element(by.css('#bind-html-with-sanitize div')).getAttribute('innerHTML')). toBe('<p>an html\n<em>click here</em>\nsnippet</p>'); }); it('should inline raw snippet if bound to a trusted value', function() { expect(element(by.css('#bind-html-with-trust div')).getAttribute('innerHTML')). toBe("<p style=\"color:blue\">an html\n" + "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + "snippet</p>"); }); it('should escape snippet without any filter', function() { expect(element(by.css('#bind-default div')).getAttribute('innerHTML')). toBe("&lt;p style=\"color:blue\"&gt;an html\n" + "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" + "snippet&lt;/p&gt;"); }); it('should update', function() { element(by.model('snippet')).clear(); element(by.model('snippet')).sendKeys('new <b onclick="alert(1)">text</b>'); expect(element(by.css('#bind-html-with-sanitize div')).getAttribute('innerHTML')). toBe('new <b>text</b>'); expect(element(by.css('#bind-html-with-trust div')).getAttribute('innerHTML')).toBe( 'new <b onclick="alert(1)">text</b>'); expect(element(by.css('#bind-default div')).getAttribute('innerHTML')).toBe( "new &lt;b onclick=\"alert(1)\"&gt;text&lt;/b&gt;"); }); </file> </example> */ /** * @ngdoc provider * @name $sanitizeProvider * @this * * @description * Creates and configures {@link $sanitize} instance. */ function $SanitizeProvider() { var svgEnabled = false; this.$get = ['$$sanitizeUri', function($$sanitizeUri) { if (svgEnabled) { extend(validElements, svgElements); } return function(html) { var buf = []; htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) { return !/^unsafe:/.test($$sanitizeUri(uri, isImage)); })); return buf.join(''); }; }]; /** * @ngdoc method * @name $sanitizeProvider#enableSvg * @kind function * * @description * Enables a subset of svg to be supported by the sanitizer. * * <div class="alert alert-warning"> * <p>By enabling this setting without taking other precautions, you might expose your * application to click-hijacking attacks. In these attacks, sanitized svg elements could be positioned * outside of the containing element and be rendered over other elements on the page (e.g. a login * link). Such behavior can then result in phishing incidents.</p> * * <p>To protect against these, explicitly setup `overflow: hidden` css rule for all potential svg * tags within the sanitized content:</p> * * <br> * * <pre><code> * .rootOfTheIncludedContent svg { * overflow: hidden !important; * } * </code></pre> * </div> * * @param {boolean=} flag Enable or disable SVG support in the sanitizer. * @returns {boolean|ng.$sanitizeProvider} Returns the currently configured value if called * without an argument or self for chaining otherwise. */ this.enableSvg = function(enableSvg) { if (isDefined(enableSvg)) { svgEnabled = enableSvg; return this; } else { return svgEnabled; } }; ////////////////////////////////////////////////////////////////////////////////////////////////// // Private stuff ////////////////////////////////////////////////////////////////////////////////////////////////// bind = angular.bind; extend = angular.extend; forEach = angular.forEach; isDefined = angular.isDefined; lowercase = angular.lowercase; noop = angular.noop; htmlParser = htmlParserImpl; htmlSanitizeWriter = htmlSanitizeWriterImpl; // Regular Expressions for parsing tags and attributes var SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g, // Match everything outside of normal chars and " (quote character) NON_ALPHANUMERIC_REGEXP = /([^#-~ |!])/g; // Good source of info about elements and attributes // http://dev.w3.org/html5/spec/Overview.html#semantics // http://simon.html5.org/html-elements // Safe Void Elements - HTML5 // http://dev.w3.org/html5/spec/Overview.html#void-elements var voidElements = toMap('area,br,col,hr,img,wbr'); // Elements that you can, intentionally, leave open (and which close themselves) // http://dev.w3.org/html5/spec/Overview.html#optional-tags var optionalEndTagBlockElements = toMap('colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr'), optionalEndTagInlineElements = toMap('rp,rt'), optionalEndTagElements = extend({}, optionalEndTagInlineElements, optionalEndTagBlockElements); // Safe Block Elements - HTML5 var blockElements = extend({}, optionalEndTagBlockElements, toMap('address,article,' + 'aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,' + 'h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,section,table,ul')); // Inline Elements - HTML5 var inlineElements = extend({}, optionalEndTagInlineElements, toMap('a,abbr,acronym,b,' + 'bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,' + 'samp,small,span,strike,strong,sub,sup,time,tt,u,var')); // SVG Elements // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements // Note: the elements animate,animateColor,animateMotion,animateTransform,set are intentionally omitted. // They can potentially allow for arbitrary javascript to be executed. See #11290 var svgElements = toMap('circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,' + 'hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,' + 'radialGradient,rect,stop,svg,switch,text,title,tspan'); // Blocked Elements (will be stripped) var blockedElements = toMap('script,style'); var validElements = extend({}, voidElements, blockElements, inlineElements, optionalEndTagElements); //Attributes that have href and hence need to be sanitized var uriAttrs = toMap('background,cite,href,longdesc,src,xlink:href'); var htmlAttrs = toMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' + 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' + 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' + 'scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,' + 'valign,value,vspace,width'); // SVG attributes (without "id" and "name" attributes) // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes var svgAttrs = toMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' + 'baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,' + 'cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,' + 'font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,' + 'height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,' + 'marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,' + 'max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,' + 'path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,' + 'requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,' + 'stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,' + 'stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,' + 'stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,' + 'underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,' + 'width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,' + 'xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan', true); var validAttrs = extend({}, uriAttrs, svgAttrs, htmlAttrs); function toMap(str, lowercaseKeys) { var obj = {}, items = str.split(','), i; for (i = 0; i < items.length; i++) { obj[lowercaseKeys ? lowercase(items[i]) : items[i]] = true; } return obj; } var inertBodyElement; (function(window) { var doc; if (window.document && window.document.implementation) { doc = window.document.implementation.createHTMLDocument('inert'); } else { throw $sanitizeMinErr('noinert', 'Can\'t create an inert html document'); } var docElement = doc.documentElement || doc.getDocumentElement(); var bodyElements = docElement.getElementsByTagName('body'); // usually there should be only one body element in the document, but IE doesn't have any, so we need to create one if (bodyElements.length === 1) { inertBodyElement = bodyElements[0]; } else { var html = doc.createElement('html'); inertBodyElement = doc.createElement('body'); html.appendChild(inertBodyElement); doc.appendChild(html); } })(window); /** * @example * htmlParser(htmlString, { * start: function(tag, attrs) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * * @param {string} html string * @param {object} handler */ function htmlParserImpl(html, handler) { if (html === null || html === undefined) { html = ''; } else if (typeof html !== 'string') { html = '' + html; } inertBodyElement.innerHTML = html; //mXSS protection var mXSSAttempts = 5; do { if (mXSSAttempts === 0) { throw $sanitizeMinErr('uinput', 'Failed to sanitize html because the input is unstable'); } mXSSAttempts--; // strip custom-namespaced attributes on IE<=11 if (window.document.documentMode) { stripCustomNsAttrs(inertBodyElement); } html = inertBodyElement.innerHTML; //trigger mXSS inertBodyElement.innerHTML = html; } while (html !== inertBodyElement.innerHTML); var node = inertBodyElement.firstChild; while (node) { switch (node.nodeType) { case 1: // ELEMENT_NODE handler.start(node.nodeName.toLowerCase(), attrToMap(node.attributes)); break; case 3: // TEXT NODE handler.chars(node.textContent); break; } var nextNode; if (!(nextNode = node.firstChild)) { if (node.nodeType === 1) { handler.end(node.nodeName.toLowerCase()); } nextNode = node.nextSibling; if (!nextNode) { while (nextNode == null) { node = node.parentNode; if (node === inertBodyElement) break; nextNode = node.nextSibling; if (node.nodeType === 1) { handler.end(node.nodeName.toLowerCase()); } } } } node = nextNode; } while ((node = inertBodyElement.firstChild)) { inertBodyElement.removeChild(node); } } function attrToMap(attrs) { var map = {}; for (var i = 0, ii = attrs.length; i < ii; i++) { var attr = attrs[i]; map[attr.name] = attr.value; } return map; } /** * Escapes all potentially dangerous characters, so that the * resulting string can be safely inserted into attribute or * element text. * @param value * @returns {string} escaped text */ function encodeEntities(value) { return value. replace(/&/g, '&amp;'). replace(SURROGATE_PAIR_REGEXP, function(value) { var hi = value.charCodeAt(0); var low = value.charCodeAt(1); return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';'; }). replace(NON_ALPHANUMERIC_REGEXP, function(value) { return '&#' + value.charCodeAt(0) + ';'; }). replace(/</g, '&lt;'). replace(/>/g, '&gt;'); } /** * create an HTML/XML writer which writes to buffer * @param {Array} buf use buf.join('') to get out sanitized html string * @returns {object} in the form of { * start: function(tag, attrs) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * } */ function htmlSanitizeWriterImpl(buf, uriValidator) { var ignoreCurrentElement = false; var out = bind(buf, buf.push); return { start: function(tag, attrs) { tag = lowercase(tag); if (!ignoreCurrentElement && blockedElements[tag]) { ignoreCurrentElement = tag; } if (!ignoreCurrentElement && validElements[tag] === true) { out('<'); out(tag); forEach(attrs, function(value, key) { var lkey = lowercase(key); var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background'); if (validAttrs[lkey] === true && (uriAttrs[lkey] !== true || uriValidator(value, isImage))) { out(' '); out(key); out('="'); out(encodeEntities(value)); out('"'); } }); out('>'); } }, end: function(tag) { tag = lowercase(tag); if (!ignoreCurrentElement && validElements[tag] === true && voidElements[tag] !== true) { out('</'); out(tag); out('>'); } // eslint-disable-next-line eqeqeq if (tag == ignoreCurrentElement) { ignoreCurrentElement = false; } }, chars: function(chars) { if (!ignoreCurrentElement) { out(encodeEntities(chars)); } } }; } /** * When IE9-11 comes across an unknown namespaced attribute e.g. 'xlink:foo' it adds 'xmlns:ns1' attribute to declare * ns1 namespace and prefixes the attribute with 'ns1' (e.g. 'ns1:xlink:foo'). This is undesirable since we don't want * to allow any of these custom attributes. This method strips them all. * * @param node Root element to process */ function stripCustomNsAttrs(node) { if (node.nodeType === window.Node.ELEMENT_NODE) { var attrs = node.attributes; for (var i = 0, l = attrs.length; i < l; i++) { var attrNode = attrs[i]; var attrName = attrNode.name.toLowerCase(); if (attrName === 'xmlns:ns1' || attrName.lastIndexOf('ns1:', 0) === 0) { node.removeAttributeNode(attrNode); i--; l--; } } } var nextNode = node.firstChild; if (nextNode) { stripCustomNsAttrs(nextNode); } nextNode = node.nextSibling; if (nextNode) { stripCustomNsAttrs(nextNode); } } } function sanitizeText(chars) { var buf = []; var writer = htmlSanitizeWriter(buf, noop); writer.chars(chars); return buf.join(''); } // define ngSanitize module and register $sanitize service angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider); /** * @ngdoc filter * @name linky * @kind function * * @description * Finds links in text input and turns them into html links. Supports `http/https/ftp/mailto` and * plain email address links. * * Requires the {@link ngSanitize `ngSanitize`} module to be installed. * * @param {string} text Input text. * @param {string} target Window (`_blank|_self|_parent|_top`) or named frame to open links in. * @param {object|function(url)} [attributes] Add custom attributes to the link element. * * Can be one of: * * - `object`: A map of attributes * - `function`: Takes the url as a parameter and returns a map of attributes * * If the map of attributes contains a value for `target`, it overrides the value of * the target parameter. * * * @returns {string} Html-linkified and {@link $sanitize sanitized} text. * * @usage <span ng-bind-html="linky_expression | linky"></span> * * @example <example module="linkyExample" deps="angular-sanitize.js" name="linky-filter"> <file name="index.html"> <div ng-controller="ExampleController"> Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea> <table> <tr> <th>Filter</th> <th>Source</th> <th>Rendered</th> </tr> <tr id="linky-filter"> <td>linky filter</td> <td> <pre>&lt;div ng-bind-html="snippet | linky"&gt;<br>&lt;/div&gt;</pre> </td> <td> <div ng-bind-html="snippet | linky"></div> </td> </tr> <tr id="linky-target"> <td>linky target</td> <td> <pre>&lt;div ng-bind-html="snippetWithSingleURL | linky:'_blank'"&gt;<br>&lt;/div&gt;</pre> </td> <td> <div ng-bind-html="snippetWithSingleURL | linky:'_blank'"></div> </td> </tr> <tr id="linky-custom-attributes"> <td>linky custom attributes</td> <td> <pre>&lt;div ng-bind-html="snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}"&gt;<br>&lt;/div&gt;</pre> </td> <td> <div ng-bind-html="snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}"></div> </td> </tr> <tr id="escaped-html"> <td>no filter</td> <td><pre>&lt;div ng-bind="snippet"&gt;<br>&lt;/div&gt;</pre></td> <td><div ng-bind="snippet"></div></td> </tr> </table> </file> <file name="script.js"> angular.module('linkyExample', ['ngSanitize']) .controller('ExampleController', ['$scope', function($scope) { $scope.snippet = 'Pretty text with some links:\n' + 'http://angularjs.org/,\n' + 'mailto:[email protected],\n' + '[email protected],\n' + 'and one more: ftp://127.0.0.1/.'; $scope.snippetWithSingleURL = 'http://angularjs.org/'; }]); </file> <file name="protractor.js" type="protractor"> it('should linkify the snippet with urls', function() { expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()). toBe('Pretty text with some links: http://angularjs.org/, [email protected], ' + '[email protected], and one more: ftp://127.0.0.1/.'); expect(element.all(by.css('#linky-filter a')).count()).toEqual(4); }); it('should not linkify snippet without the linky filter', function() { expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()). toBe('Pretty text with some links: http://angularjs.org/, mailto:[email protected], ' + '[email protected], and one more: ftp://127.0.0.1/.'); expect(element.all(by.css('#escaped-html a')).count()).toEqual(0); }); it('should update', function() { element(by.model('snippet')).clear(); element(by.model('snippet')).sendKeys('new http://link.'); expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()). toBe('new http://link.'); expect(element.all(by.css('#linky-filter a')).count()).toEqual(1); expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()) .toBe('new http://link.'); }); it('should work with the target property', function() { expect(element(by.id('linky-target')). element(by.binding("snippetWithSingleURL | linky:'_blank'")).getText()). toBe('http://angularjs.org/'); expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank'); }); it('should optionally add custom attributes', function() { expect(element(by.id('linky-custom-attributes')). element(by.binding("snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}")).getText()). toBe('http://angularjs.org/'); expect(element(by.css('#linky-custom-attributes a')).getAttribute('rel')).toEqual('nofollow'); }); </file> </example> */ angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) { var LINKY_URL_REGEXP = /((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i, MAILTO_REGEXP = /^mailto:/i; var linkyMinErr = angular.$$minErr('linky'); var isDefined = angular.isDefined; var isFunction = angular.isFunction; var isObject = angular.isObject; var isString = angular.isString; return function(text, target, attributes) { if (text == null || text === '') return text; if (!isString(text)) throw linkyMinErr('notstring', 'Expected string but received: {0}', text); var attributesFn = isFunction(attributes) ? attributes : isObject(attributes) ? function getAttributesObject() {return attributes;} : function getEmptyAttributesObject() {return {};}; var match; var raw = text; var html = []; var url; var i; while ((match = raw.match(LINKY_URL_REGEXP))) { // We can not end in these as they are sometimes found at the end of the sentence url = match[0]; // if we did not match ftp/http/www/mailto then assume mailto if (!match[2] && !match[4]) { url = (match[3] ? 'http://' : 'mailto:') + url; } i = match.index; addText(raw.substr(0, i)); addLink(url, match[0].replace(MAILTO_REGEXP, '')); raw = raw.substring(i + match[0].length); } addText(raw); return $sanitize(html.join('')); function addText(text) { if (!text) { return; } html.push(sanitizeText(text)); } function addLink(url, text) { var key, linkAttributes = attributesFn(url); html.push('<a '); for (key in linkAttributes) { html.push(key + '="' + linkAttributes[key] + '" '); } if (isDefined(target) && !('target' in linkAttributes)) { html.push('target="', target, '" '); } html.push('href="', url.replace(/"/g, '&quot;'), '">'); addText(text); html.push('</a>'); } }; }]); })(window, window.angular);
/** * jqPlot * Pure JavaScript plotting plugin using jQuery * * Version: 1.0.4 * Revision: 1120 * * Copyright (c) 2009-2012 Chris Leonello * jqPlot is currently available for use in all personal or commercial projects * under both the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL * version 2.0 (http://www.gnu.org/licenses/gpl-2.0.html) licenses. This means that you can * choose the license that best suits your project and use it accordingly. * * Although not required, the author would appreciate an email letting him * know of any substantial use of jqPlot. You can reach the author at: * chris at jqplot dot com or see http://www.jqplot.com/info.php . * * If you are feeling kind and generous, consider supporting the project by * making a donation at: http://www.jqplot.com/donate.php . * * sprintf functions contained in jqplot.sprintf.js by Ash Searle: * * version 2007.04.27 * author Ash Searle * http://hexmen.com/blog/2007/03/printf-sprintf/ * http://hexmen.com/js/sprintf.js * The author (Ash Searle) has placed this code in the public domain: * "This code is unrestricted: you are free to use it however you like." * */ (function($) { /** * Class: $.jqplot.Cursor * Plugin class representing the cursor as displayed on the plot. */ $.jqplot.Cursor = function(options) { // Group: Properties // // prop: style // CSS spec for cursor style this.style = 'crosshair'; this.previousCursor = 'auto'; // prop: show // wether to show the cursor or not. this.show = $.jqplot.config.enablePlugins; // prop: showTooltip // show a cursor position tooltip. Location of the tooltip // will be controlled by followMouse and tooltipLocation. this.showTooltip = true; // prop: followMouse // Tooltip follows the mouse, it is not at a fixed location. // Tooltip will show on the grid at the location given by // tooltipLocation, offset from the grid edge by tooltipOffset. this.followMouse = false; // prop: tooltipLocation // Where to position tooltip. If followMouse is true, this is // relative to the cursor, otherwise, it is relative to the grid. // One of 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw' this.tooltipLocation = 'se'; // prop: tooltipOffset // Pixel offset of tooltip from the grid boudaries or cursor center. this.tooltipOffset = 6; // prop: showTooltipGridPosition // show the grid pixel coordinates of the mouse. this.showTooltipGridPosition = false; // prop: showTooltipUnitPosition // show the unit (data) coordinates of the mouse. this.showTooltipUnitPosition = true; // prop: showTooltipDataPosition // Used with showVerticalLine to show intersecting data points in the tooltip. this.showTooltipDataPosition = false; // prop: tooltipFormatString // sprintf format string for the tooltip. // Uses Ash Searle's javascript sprintf implementation // found here: http://hexmen.com/blog/2007/03/printf-sprintf/ // See http://perldoc.perl.org/functions/sprintf.html for reference // Note, if showTooltipDataPosition is true, the default tooltipFormatString // will be set to the cursorLegendFormatString, not the default given here. this.tooltipFormatString = '%.4P, %.4P'; // prop: useAxesFormatters // Use the x and y axes formatters to format the text in the tooltip. this.useAxesFormatters = true; // prop: tooltipAxisGroups // Show position for the specified axes. // This is an array like [['xaxis', 'yaxis'], ['xaxis', 'y2axis']] // Default is to compute automatically for all visible axes. this.tooltipAxisGroups = []; // prop: zoom // Enable plot zooming. this.zoom = false; // zoomProxy and zoomTarget properties are not directly set by user. // They Will be set through call to zoomProxy method. this.zoomProxy = false; this.zoomTarget = false; // prop: looseZoom // Will expand zoom range to provide more rounded tick values. // Works only with linear, log and date axes. this.looseZoom = true; // prop: clickReset // Will reset plot zoom if single click on plot without drag. this.clickReset = false; // prop: dblClickReset // Will reset plot zoom if double click on plot without drag. this.dblClickReset = true; // prop: showVerticalLine // draw a vertical line across the plot which follows the cursor. // When the line is near a data point, a special legend and/or tooltip can // be updated with the data values. this.showVerticalLine = false; // prop: showHorizontalLine // draw a horizontal line across the plot which follows the cursor. this.showHorizontalLine = false; // prop: constrainZoomTo // 'none', 'x' or 'y' this.constrainZoomTo = 'none'; // // prop: autoscaleConstraint // // when a constrained axis is specified, true will // // auatoscale the adjacent axis. // this.autoscaleConstraint = true; this.shapeRenderer = new $.jqplot.ShapeRenderer(); this._zoom = {start:[], end:[], started: false, zooming:false, isZoomed:false, axes:{start:{}, end:{}}, gridpos:{}, datapos:{}}; this._tooltipElem; this.zoomCanvas; this.cursorCanvas; // prop: intersectionThreshold // pixel distance from data point or marker to consider cursor lines intersecting with point. // If data point markers are not shown, this should be >= 1 or will often miss point intersections. this.intersectionThreshold = 2; // prop: showCursorLegend // Replace the plot legend with an enhanced legend displaying intersection information. this.showCursorLegend = false; // prop: cursorLegendFormatString // Format string used in the cursor legend. If showTooltipDataPosition is true, // this will also be the default format string used by tooltipFormatString. this.cursorLegendFormatString = $.jqplot.Cursor.cursorLegendFormatString; // whether the cursor is over the grid or not. this._oldHandlers = {onselectstart: null, ondrag: null, onmousedown: null}; // prop: constrainOutsideZoom // True to limit actual zoom area to edges of grid, even when zooming // outside of plot area. That is, can't zoom out by mousing outside plot. this.constrainOutsideZoom = true; // prop: showTooltipOutsideZoom // True will keep updating the tooltip when zooming of the grid. this.showTooltipOutsideZoom = false; // true if mouse is over grid, false if not. this.onGrid = false; $.extend(true, this, options); }; $.jqplot.Cursor.cursorLegendFormatString = '%s x:%s, y:%s'; // called with scope of plot $.jqplot.Cursor.init = function (target, data, opts){ // add a cursor attribute to the plot var options = opts || {}; this.plugins.cursor = new $.jqplot.Cursor(options.cursor); var c = this.plugins.cursor; if (c.show) { $.jqplot.eventListenerHooks.push(['jqplotMouseEnter', handleMouseEnter]); $.jqplot.eventListenerHooks.push(['jqplotMouseLeave', handleMouseLeave]); $.jqplot.eventListenerHooks.push(['jqplotMouseMove', handleMouseMove]); if (c.showCursorLegend) { opts.legend = opts.legend || {}; opts.legend.renderer = $.jqplot.CursorLegendRenderer; opts.legend.formatString = this.plugins.cursor.cursorLegendFormatString; opts.legend.show = true; } if (c.zoom) { $.jqplot.eventListenerHooks.push(['jqplotMouseDown', handleMouseDown]); if (c.clickReset) { $.jqplot.eventListenerHooks.push(['jqplotClick', handleClick]); } if (c.dblClickReset) { $.jqplot.eventListenerHooks.push(['jqplotDblClick', handleDblClick]); } } this.resetZoom = function() { var axes = this.axes; if (!c.zoomProxy) { for (var ax in axes) { axes[ax].reset(); axes[ax]._ticks = []; // fake out tick creation algorithm to make sure original auto // computed format string is used if _overrideFormatString is true if (c._zoom.axes[ax] !== undefined) { axes[ax]._autoFormatString = c._zoom.axes[ax].tickFormatString; } } this.redraw(); } else { var ctx = this.plugins.cursor.zoomCanvas._ctx; ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height); ctx = null; } this.plugins.cursor._zoom.isZoomed = false; this.target.trigger('jqplotResetZoom', [this, this.plugins.cursor]); }; if (c.showTooltipDataPosition) { c.showTooltipUnitPosition = false; c.showTooltipGridPosition = false; if (options.cursor.tooltipFormatString == undefined) { c.tooltipFormatString = $.jqplot.Cursor.cursorLegendFormatString; } } } }; // called with context of plot $.jqplot.Cursor.postDraw = function() { var c = this.plugins.cursor; // Memory Leaks patch if (c.zoomCanvas) { c.zoomCanvas.resetCanvas(); c.zoomCanvas = null; } if (c.cursorCanvas) { c.cursorCanvas.resetCanvas(); c.cursorCanvas = null; } if (c._tooltipElem) { c._tooltipElem.emptyForce(); c._tooltipElem = null; } if (c.zoom) { c.zoomCanvas = new $.jqplot.GenericCanvas(); this.eventCanvas._elem.before(c.zoomCanvas.createElement(this._gridPadding, 'jqplot-zoom-canvas', this._plotDimensions, this)); c.zoomCanvas.setContext(); } var elem = document.createElement('div'); c._tooltipElem = $(elem); elem = null; c._tooltipElem.addClass('jqplot-cursor-tooltip'); c._tooltipElem.css({position:'absolute', display:'none'}); if (c.zoomCanvas) { c.zoomCanvas._elem.before(c._tooltipElem); } else { this.eventCanvas._elem.before(c._tooltipElem); } if (c.showVerticalLine || c.showHorizontalLine) { c.cursorCanvas = new $.jqplot.GenericCanvas(); this.eventCanvas._elem.before(c.cursorCanvas.createElement(this._gridPadding, 'jqplot-cursor-canvas', this._plotDimensions, this)); c.cursorCanvas.setContext(); } // if we are showing the positions in unit coordinates, and no axes groups // were specified, create a default set. if (c.showTooltipUnitPosition){ if (c.tooltipAxisGroups.length === 0) { var series = this.series; var s; var temp = []; for (var i=0; i<series.length; i++) { s = series[i]; var ax = s.xaxis+','+s.yaxis; if ($.inArray(ax, temp) == -1) { temp.push(ax); } } for (var i=0; i<temp.length; i++) { c.tooltipAxisGroups.push(temp[i].split(',')); } } } }; // Group: methods // // method: $.jqplot.Cursor.zoomProxy // links targetPlot to controllerPlot so that plot zooming of // targetPlot will be controlled by zooming on the controllerPlot. // controllerPlot will not actually zoom, but acts as an // overview plot. Note, the zoom options must be set to true for // zoomProxy to work. $.jqplot.Cursor.zoomProxy = function(targetPlot, controllerPlot) { var tc = targetPlot.plugins.cursor; var cc = controllerPlot.plugins.cursor; tc.zoomTarget = true; tc.zoom = true; tc.style = 'auto'; tc.dblClickReset = false; cc.zoom = true; cc.zoomProxy = true; controllerPlot.target.bind('jqplotZoom', plotZoom); controllerPlot.target.bind('jqplotResetZoom', plotReset); function plotZoom(ev, gridpos, datapos, plot, cursor) { tc.doZoom(gridpos, datapos, targetPlot, cursor); } function plotReset(ev, plot, cursor) { targetPlot.resetZoom(); } }; $.jqplot.Cursor.prototype.resetZoom = function(plot, cursor) { var axes = plot.axes; var cax = cursor._zoom.axes; if (!plot.plugins.cursor.zoomProxy && cursor._zoom.isZoomed) { for (var ax in axes) { // axes[ax]._ticks = []; // axes[ax].min = cax[ax].min; // axes[ax].max = cax[ax].max; // axes[ax].numberTicks = cax[ax].numberTicks; // axes[ax].tickInterval = cax[ax].tickInterval; // // for date axes // axes[ax].daTickInterval = cax[ax].daTickInterval; axes[ax].reset(); axes[ax]._ticks = []; // fake out tick creation algorithm to make sure original auto // computed format string is used if _overrideFormatString is true axes[ax]._autoFormatString = cax[ax].tickFormatString; } plot.redraw(); cursor._zoom.isZoomed = false; } else { var ctx = cursor.zoomCanvas._ctx; ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height); ctx = null; } plot.target.trigger('jqplotResetZoom', [plot, cursor]); }; $.jqplot.Cursor.resetZoom = function(plot) { plot.resetZoom(); }; $.jqplot.Cursor.prototype.doZoom = function (gridpos, datapos, plot, cursor) { var c = cursor; var axes = plot.axes; var zaxes = c._zoom.axes; var start = zaxes.start; var end = zaxes.end; var min, max, dp, span, newmin, newmax, curax, _numberTicks, ret; var ctx = plot.plugins.cursor.zoomCanvas._ctx; // don't zoom if zoom area is too small (in pixels) if ((c.constrainZoomTo == 'none' && Math.abs(gridpos.x - c._zoom.start[0]) > 6 && Math.abs(gridpos.y - c._zoom.start[1]) > 6) || (c.constrainZoomTo == 'x' && Math.abs(gridpos.x - c._zoom.start[0]) > 6) || (c.constrainZoomTo == 'y' && Math.abs(gridpos.y - c._zoom.start[1]) > 6)) { if (!plot.plugins.cursor.zoomProxy) { for (var ax in datapos) { // make a copy of the original axes to revert back. if (c._zoom.axes[ax] == undefined) { c._zoom.axes[ax] = {}; c._zoom.axes[ax].numberTicks = axes[ax].numberTicks; c._zoom.axes[ax].tickInterval = axes[ax].tickInterval; // for date axes... c._zoom.axes[ax].daTickInterval = axes[ax].daTickInterval; c._zoom.axes[ax].min = axes[ax].min; c._zoom.axes[ax].max = axes[ax].max; c._zoom.axes[ax].tickFormatString = (axes[ax].tickOptions != null) ? axes[ax].tickOptions.formatString : ''; } if ((c.constrainZoomTo == 'none') || (c.constrainZoomTo == 'x' && ax.charAt(0) == 'x') || (c.constrainZoomTo == 'y' && ax.charAt(0) == 'y')) { dp = datapos[ax]; if (dp != null) { if (dp > start[ax]) { newmin = start[ax]; newmax = dp; } else { span = start[ax] - dp; newmin = dp; newmax = start[ax]; } curax = axes[ax]; _numberTicks = null; // if aligning this axis, use number of ticks from previous axis. // Do I need to reset somehow if alignTicks is changed and then graph is replotted?? if (curax.alignTicks) { if (curax.name === 'x2axis' && plot.axes.xaxis.show) { _numberTicks = plot.axes.xaxis.numberTicks; } else if (curax.name.charAt(0) === 'y' && curax.name !== 'yaxis' && curax.name !== 'yMidAxis' && plot.axes.yaxis.show) { _numberTicks = plot.axes.yaxis.numberTicks; } } if (this.looseZoom && (axes[ax].renderer.constructor === $.jqplot.LinearAxisRenderer || axes[ax].renderer.constructor === $.jqplot.LogAxisRenderer )) { //} || axes[ax].renderer.constructor === $.jqplot.DateAxisRenderer)) { ret = $.jqplot.LinearTickGenerator(newmin, newmax, curax._scalefact, _numberTicks); // if new minimum is less than "true" minimum of axis display, adjust it if (axes[ax].tickInset && ret[0] < axes[ax].min + axes[ax].tickInset * axes[ax].tickInterval) { ret[0] += ret[4]; ret[2] -= 1; } // if new maximum is greater than "true" max of axis display, adjust it if (axes[ax].tickInset && ret[1] > axes[ax].max - axes[ax].tickInset * axes[ax].tickInterval) { ret[1] -= ret[4]; ret[2] -= 1; } // for log axes, don't fall below current minimum, this will look bad and can't have 0 in range anyway. if (axes[ax].renderer.constructor === $.jqplot.LogAxisRenderer && ret[0] < axes[ax].min) { // remove a tick and shift min up ret[0] += ret[4]; ret[2] -= 1; } axes[ax].min = ret[0]; axes[ax].max = ret[1]; axes[ax]._autoFormatString = ret[3]; axes[ax].numberTicks = ret[2]; axes[ax].tickInterval = ret[4]; // for date axes... axes[ax].daTickInterval = [ret[4]/1000, 'seconds']; } else { axes[ax].min = newmin; axes[ax].max = newmax; axes[ax].tickInterval = null; axes[ax].numberTicks = null; // for date axes... axes[ax].daTickInterval = null; } axes[ax]._ticks = []; } } // if ((c.constrainZoomTo == 'x' && ax.charAt(0) == 'y' && c.autoscaleConstraint) || (c.constrainZoomTo == 'y' && ax.charAt(0) == 'x' && c.autoscaleConstraint)) { // dp = datapos[ax]; // if (dp != null) { // axes[ax].max == null; // axes[ax].min = null; // } // } } ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height); plot.redraw(); c._zoom.isZoomed = true; ctx = null; } plot.target.trigger('jqplotZoom', [gridpos, datapos, plot, cursor]); } }; $.jqplot.preInitHooks.push($.jqplot.Cursor.init); $.jqplot.postDrawHooks.push($.jqplot.Cursor.postDraw); function updateTooltip(gridpos, datapos, plot) { var c = plot.plugins.cursor; var s = ''; var addbr = false; if (c.showTooltipGridPosition) { s = gridpos.x+', '+gridpos.y; addbr = true; } if (c.showTooltipUnitPosition) { var g; for (var i=0; i<c.tooltipAxisGroups.length; i++) { g = c.tooltipAxisGroups[i]; if (addbr) { s += '<br />'; } if (c.useAxesFormatters) { for (var j=0; j<g.length; j++) { if (j) { s += ', '; } var af = plot.axes[g[j]]._ticks[0].formatter; var afstr = plot.axes[g[j]]._ticks[0].formatString; s += af(afstr, datapos[g[j]]); } } else { s += $.jqplot.sprintf(c.tooltipFormatString, datapos[g[0]], datapos[g[1]]); } addbr = true; } } if (c.showTooltipDataPosition) { var series = plot.series; var ret = getIntersectingPoints(plot, gridpos.x, gridpos.y); var addbr = false; for (var i = 0; i< series.length; i++) { if (series[i].show) { var idx = series[i].index; var label = series[i].label.toString(); var cellid = $.inArray(idx, ret.indices); var sx = undefined; var sy = undefined; if (cellid != -1) { var data = ret.data[cellid].data; if (c.useAxesFormatters) { var xf = series[i]._xaxis._ticks[0].formatter; var yf = series[i]._yaxis._ticks[0].formatter; var xfstr = series[i]._xaxis._ticks[0].formatString; var yfstr = series[i]._yaxis._ticks[0].formatString; sx = xf(xfstr, data[0]); sy = yf(yfstr, data[1]); } else { sx = data[0]; sy = data[1]; } if (addbr) { s += '<br />'; } s += $.jqplot.sprintf(c.tooltipFormatString, label, sx, sy); addbr = true; } } } } c._tooltipElem.html(s); } function moveLine(gridpos, plot) { var c = plot.plugins.cursor; var ctx = c.cursorCanvas._ctx; ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height); if (c.showVerticalLine) { c.shapeRenderer.draw(ctx, [[gridpos.x, 0], [gridpos.x, ctx.canvas.height]]); } if (c.showHorizontalLine) { c.shapeRenderer.draw(ctx, [[0, gridpos.y], [ctx.canvas.width, gridpos.y]]); } var ret = getIntersectingPoints(plot, gridpos.x, gridpos.y); if (c.showCursorLegend) { var cells = $(plot.targetId + ' td.jqplot-cursor-legend-label'); for (var i=0; i<cells.length; i++) { var idx = $(cells[i]).data('seriesIndex'); var series = plot.series[idx]; var label = series.label.toString(); var cellid = $.inArray(idx, ret.indices); var sx = undefined; var sy = undefined; if (cellid != -1) { var data = ret.data[cellid].data; if (c.useAxesFormatters) { var xf = series._xaxis._ticks[0].formatter; var yf = series._yaxis._ticks[0].formatter; var xfstr = series._xaxis._ticks[0].formatString; var yfstr = series._yaxis._ticks[0].formatString; sx = xf(xfstr, data[0]); sy = yf(yfstr, data[1]); } else { sx = data[0]; sy = data[1]; } } if (plot.legend.escapeHtml) { $(cells[i]).text($.jqplot.sprintf(c.cursorLegendFormatString, label, sx, sy)); } else { $(cells[i]).html($.jqplot.sprintf(c.cursorLegendFormatString, label, sx, sy)); } } } ctx = null; } function getIntersectingPoints(plot, x, y) { var ret = {indices:[], data:[]}; var s, i, d0, d, j, r, p; var threshold; var c = plot.plugins.cursor; for (var i=0; i<plot.series.length; i++) { s = plot.series[i]; r = s.renderer; if (s.show) { threshold = c.intersectionThreshold; if (s.showMarker) { threshold += s.markerRenderer.size/2; } for (var j=0; j<s.gridData.length; j++) { p = s.gridData[j]; // check vertical line if (c.showVerticalLine) { if (Math.abs(x-p[0]) <= threshold) { ret.indices.push(i); ret.data.push({seriesIndex: i, pointIndex:j, gridData:p, data:s.data[j]}); } } } } } return ret; } function moveTooltip(gridpos, plot) { var c = plot.plugins.cursor; var elem = c._tooltipElem; switch (c.tooltipLocation) { case 'nw': var x = gridpos.x + plot._gridPadding.left - elem.outerWidth(true) - c.tooltipOffset; var y = gridpos.y + plot._gridPadding.top - c.tooltipOffset - elem.outerHeight(true); break; case 'n': var x = gridpos.x + plot._gridPadding.left - elem.outerWidth(true)/2; var y = gridpos.y + plot._gridPadding.top - c.tooltipOffset - elem.outerHeight(true); break; case 'ne': var x = gridpos.x + plot._gridPadding.left + c.tooltipOffset; var y = gridpos.y + plot._gridPadding.top - c.tooltipOffset - elem.outerHeight(true); break; case 'e': var x = gridpos.x + plot._gridPadding.left + c.tooltipOffset; var y = gridpos.y + plot._gridPadding.top - elem.outerHeight(true)/2; break; case 'se': var x = gridpos.x + plot._gridPadding.left + c.tooltipOffset; var y = gridpos.y + plot._gridPadding.top + c.tooltipOffset; break; case 's': var x = gridpos.x + plot._gridPadding.left - elem.outerWidth(true)/2; var y = gridpos.y + plot._gridPadding.top + c.tooltipOffset; break; case 'sw': var x = gridpos.x + plot._gridPadding.left - elem.outerWidth(true) - c.tooltipOffset; var y = gridpos.y + plot._gridPadding.top + c.tooltipOffset; break; case 'w': var x = gridpos.x + plot._gridPadding.left - elem.outerWidth(true) - c.tooltipOffset; var y = gridpos.y + plot._gridPadding.top - elem.outerHeight(true)/2; break; default: var x = gridpos.x + plot._gridPadding.left + c.tooltipOffset; var y = gridpos.y + plot._gridPadding.top + c.tooltipOffset; break; } elem.css('left', x); elem.css('top', y); elem = null; } function positionTooltip(plot) { // fake a grid for positioning var grid = plot._gridPadding; var c = plot.plugins.cursor; var elem = c._tooltipElem; switch (c.tooltipLocation) { case 'nw': var a = grid.left + c.tooltipOffset; var b = grid.top + c.tooltipOffset; elem.css('left', a); elem.css('top', b); break; case 'n': var a = (grid.left + (plot._plotDimensions.width - grid.right))/2 - elem.outerWidth(true)/2; var b = grid.top + c.tooltipOffset; elem.css('left', a); elem.css('top', b); break; case 'ne': var a = grid.right + c.tooltipOffset; var b = grid.top + c.tooltipOffset; elem.css({right:a, top:b}); break; case 'e': var a = grid.right + c.tooltipOffset; var b = (grid.top + (plot._plotDimensions.height - grid.bottom))/2 - elem.outerHeight(true)/2; elem.css({right:a, top:b}); break; case 'se': var a = grid.right + c.tooltipOffset; var b = grid.bottom + c.tooltipOffset; elem.css({right:a, bottom:b}); break; case 's': var a = (grid.left + (plot._plotDimensions.width - grid.right))/2 - elem.outerWidth(true)/2; var b = grid.bottom + c.tooltipOffset; elem.css({left:a, bottom:b}); break; case 'sw': var a = grid.left + c.tooltipOffset; var b = grid.bottom + c.tooltipOffset; elem.css({left:a, bottom:b}); break; case 'w': var a = grid.left + c.tooltipOffset; var b = (grid.top + (plot._plotDimensions.height - grid.bottom))/2 - elem.outerHeight(true)/2; elem.css({left:a, top:b}); break; default: // same as 'se' var a = grid.right - c.tooltipOffset; var b = grid.bottom + c.tooltipOffset; elem.css({right:a, bottom:b}); break; } elem = null; } function handleClick (ev, gridpos, datapos, neighbor, plot) { ev.preventDefault(); ev.stopImmediatePropagation(); var c = plot.plugins.cursor; if (c.clickReset) { c.resetZoom(plot, c); } var sel = window.getSelection; if (document.selection && document.selection.empty) { document.selection.empty(); } else if (sel && !sel().isCollapsed) { sel().collapse(); } return false; } function handleDblClick (ev, gridpos, datapos, neighbor, plot) { ev.preventDefault(); ev.stopImmediatePropagation(); var c = plot.plugins.cursor; if (c.dblClickReset) { c.resetZoom(plot, c); } var sel = window.getSelection; if (document.selection && document.selection.empty) { document.selection.empty(); } else if (sel && !sel().isCollapsed) { sel().collapse(); } return false; } function handleMouseLeave(ev, gridpos, datapos, neighbor, plot) { var c = plot.plugins.cursor; c.onGrid = false; if (c.show) { $(ev.target).css('cursor', c.previousCursor); if (c.showTooltip && !(c._zoom.zooming && c.showTooltipOutsideZoom && !c.constrainOutsideZoom)) { c._tooltipElem.empty(); c._tooltipElem.hide(); } if (c.zoom) { c._zoom.gridpos = gridpos; c._zoom.datapos = datapos; } if (c.showVerticalLine || c.showHorizontalLine) { var ctx = c.cursorCanvas._ctx; ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height); ctx = null; } if (c.showCursorLegend) { var cells = $(plot.targetId + ' td.jqplot-cursor-legend-label'); for (var i=0; i<cells.length; i++) { var idx = $(cells[i]).data('seriesIndex'); var series = plot.series[idx]; var label = series.label.toString(); if (plot.legend.escapeHtml) { $(cells[i]).text($.jqplot.sprintf(c.cursorLegendFormatString, label, undefined, undefined)); } else { $(cells[i]).html($.jqplot.sprintf(c.cursorLegendFormatString, label, undefined, undefined)); } } } } } function handleMouseEnter(ev, gridpos, datapos, neighbor, plot) { var c = plot.plugins.cursor; c.onGrid = true; if (c.show) { c.previousCursor = ev.target.style.cursor; ev.target.style.cursor = c.style; if (c.showTooltip) { updateTooltip(gridpos, datapos, plot); if (c.followMouse) { moveTooltip(gridpos, plot); } else { positionTooltip(plot); } c._tooltipElem.show(); } if (c.showVerticalLine || c.showHorizontalLine) { moveLine(gridpos, plot); } } } function handleMouseMove(ev, gridpos, datapos, neighbor, plot) { var c = plot.plugins.cursor; if (c.show) { if (c.showTooltip) { updateTooltip(gridpos, datapos, plot); if (c.followMouse) { moveTooltip(gridpos, plot); } } if (c.showVerticalLine || c.showHorizontalLine) { moveLine(gridpos, plot); } } } function getEventPosition(ev) { var plot = ev.data.plot; var go = plot.eventCanvas._elem.offset(); var gridPos = {x:ev.pageX - go.left, y:ev.pageY - go.top}; ////// // TO DO: handle yMidAxis ////// var dataPos = {xaxis:null, yaxis:null, x2axis:null, y2axis:null, y3axis:null, y4axis:null, y5axis:null, y6axis:null, y7axis:null, y8axis:null, y9axis:null, yMidAxis:null}; var an = ['xaxis', 'yaxis', 'x2axis', 'y2axis', 'y3axis', 'y4axis', 'y5axis', 'y6axis', 'y7axis', 'y8axis', 'y9axis', 'yMidAxis']; var ax = plot.axes; var n, axis; for (n=11; n>0; n--) { axis = an[n-1]; if (ax[axis].show) { dataPos[axis] = ax[axis].series_p2u(gridPos[axis.charAt(0)]); } } return {offsets:go, gridPos:gridPos, dataPos:dataPos}; } function handleZoomMove(ev) { var plot = ev.data.plot; var c = plot.plugins.cursor; // don't do anything if not on grid. if (c.show && c.zoom && c._zoom.started && !c.zoomTarget) { ev.preventDefault(); var ctx = c.zoomCanvas._ctx; var positions = getEventPosition(ev); var gridpos = positions.gridPos; var datapos = positions.dataPos; c._zoom.gridpos = gridpos; c._zoom.datapos = datapos; c._zoom.zooming = true; var xpos = gridpos.x; var ypos = gridpos.y; var height = ctx.canvas.height; var width = ctx.canvas.width; if (c.showTooltip && !c.onGrid && c.showTooltipOutsideZoom) { updateTooltip(gridpos, datapos, plot); if (c.followMouse) { moveTooltip(gridpos, plot); } } if (c.constrainZoomTo == 'x') { c._zoom.end = [xpos, height]; } else if (c.constrainZoomTo == 'y') { c._zoom.end = [width, ypos]; } else { c._zoom.end = [xpos, ypos]; } var sel = window.getSelection; if (document.selection && document.selection.empty) { document.selection.empty(); } else if (sel && !sel().isCollapsed) { sel().collapse(); } drawZoomBox.call(c); ctx = null; } } function handleMouseDown(ev, gridpos, datapos, neighbor, plot) { var c = plot.plugins.cursor; if(plot.plugins.mobile){ $(document).one('vmouseup.jqplot_cursor', {plot:plot}, handleMouseUp); } else { $(document).one('mouseup.jqplot_cursor', {plot:plot}, handleMouseUp); } var axes = plot.axes; if (document.onselectstart != undefined) { c._oldHandlers.onselectstart = document.onselectstart; document.onselectstart = function () { return false; }; } if (document.ondrag != undefined) { c._oldHandlers.ondrag = document.ondrag; document.ondrag = function () { return false; }; } if (document.onmousedown != undefined) { c._oldHandlers.onmousedown = document.onmousedown; document.onmousedown = function () { return false; }; } if (c.zoom) { if (!c.zoomProxy) { var ctx = c.zoomCanvas._ctx; ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height); ctx = null; } if (c.constrainZoomTo == 'x') { c._zoom.start = [gridpos.x, 0]; } else if (c.constrainZoomTo == 'y') { c._zoom.start = [0, gridpos.y]; } else { c._zoom.start = [gridpos.x, gridpos.y]; } c._zoom.started = true; for (var ax in datapos) { // get zoom starting position. c._zoom.axes.start[ax] = datapos[ax]; } if(plot.plugins.mobile){ $(document).bind('vmousemove.jqplotCursor', {plot:plot}, handleZoomMove); } else { $(document).bind('mousemove.jqplotCursor', {plot:plot}, handleZoomMove); } } } function handleMouseUp(ev) { var plot = ev.data.plot; var c = plot.plugins.cursor; if (c.zoom && c._zoom.zooming && !c.zoomTarget) { var xpos = c._zoom.gridpos.x; var ypos = c._zoom.gridpos.y; var datapos = c._zoom.datapos; var height = c.zoomCanvas._ctx.canvas.height; var width = c.zoomCanvas._ctx.canvas.width; var axes = plot.axes; if (c.constrainOutsideZoom && !c.onGrid) { if (xpos < 0) { xpos = 0; } else if (xpos > width) { xpos = width; } if (ypos < 0) { ypos = 0; } else if (ypos > height) { ypos = height; } for (var axis in datapos) { if (datapos[axis]) { if (axis.charAt(0) == 'x') { datapos[axis] = axes[axis].series_p2u(xpos); } else { datapos[axis] = axes[axis].series_p2u(ypos); } } } } if (c.constrainZoomTo == 'x') { ypos = height; } else if (c.constrainZoomTo == 'y') { xpos = width; } c._zoom.end = [xpos, ypos]; c._zoom.gridpos = {x:xpos, y:ypos}; c.doZoom(c._zoom.gridpos, datapos, plot, c); } c._zoom.started = false; c._zoom.zooming = false; $(document).unbind('mousemove.jqplotCursor', handleZoomMove); if (document.onselectstart != undefined && c._oldHandlers.onselectstart != null){ document.onselectstart = c._oldHandlers.onselectstart; c._oldHandlers.onselectstart = null; } if (document.ondrag != undefined && c._oldHandlers.ondrag != null){ document.ondrag = c._oldHandlers.ondrag; c._oldHandlers.ondrag = null; } if (document.onmousedown != undefined && c._oldHandlers.onmousedown != null){ document.onmousedown = c._oldHandlers.onmousedown; c._oldHandlers.onmousedown = null; } } function drawZoomBox() { var start = this._zoom.start; var end = this._zoom.end; var ctx = this.zoomCanvas._ctx; var l, t, h, w; if (end[0] > start[0]) { l = start[0]; w = end[0] - start[0]; } else { l = end[0]; w = start[0] - end[0]; } if (end[1] > start[1]) { t = start[1]; h = end[1] - start[1]; } else { t = end[1]; h = start[1] - end[1]; } ctx.fillStyle = 'rgba(0,0,0,0.2)'; ctx.strokeStyle = '#999999'; ctx.lineWidth = 1.0; ctx.clearRect(0,0,ctx.canvas.width, ctx.canvas.height); ctx.fillRect(0,0,ctx.canvas.width, ctx.canvas.height); ctx.clearRect(l, t, w, h); // IE won't show transparent fill rect, so stroke a rect also. ctx.strokeRect(l,t,w,h); ctx = null; } $.jqplot.CursorLegendRenderer = function(options) { $.jqplot.TableLegendRenderer.call(this, options); this.formatString = '%s'; }; $.jqplot.CursorLegendRenderer.prototype = new $.jqplot.TableLegendRenderer(); $.jqplot.CursorLegendRenderer.prototype.constructor = $.jqplot.CursorLegendRenderer; // called in context of a Legend $.jqplot.CursorLegendRenderer.prototype.draw = function() { if (this._elem) { this._elem.emptyForce(); this._elem = null; } if (this.show) { var series = this._series, s; // make a table. one line label per row. var elem = document.createElement('div'); this._elem = $(elem); elem = null; this._elem.addClass('jqplot-legend jqplot-cursor-legend'); this._elem.css('position', 'absolute'); var pad = false; for (var i = 0; i< series.length; i++) { s = series[i]; if (s.show && s.showLabel) { var lt = $.jqplot.sprintf(this.formatString, s.label.toString()); if (lt) { var color = s.color; if (s._stack && !s.fill) { color = ''; } addrow.call(this, lt, color, pad, i); pad = true; } // let plugins add more rows to legend. Used by trend line plugin. for (var j=0; j<$.jqplot.addLegendRowHooks.length; j++) { var item = $.jqplot.addLegendRowHooks[j].call(this, s); if (item) { addrow.call(this, item.label, item.color, pad); pad = true; } } } } series = s = null; delete series; delete s; } function addrow(label, color, pad, idx) { var rs = (pad) ? this.rowSpacing : '0'; var tr = $('<tr class="jqplot-legend jqplot-cursor-legend"></tr>').appendTo(this._elem); tr.data('seriesIndex', idx); $('<td class="jqplot-legend jqplot-cursor-legend-swatch" style="padding-top:'+rs+';">'+ '<div style="border:1px solid #cccccc;padding:0.2em;">'+ '<div class="jqplot-cursor-legend-swatch" style="background-color:'+color+';"></div>'+ '</div></td>').appendTo(tr); var td = $('<td class="jqplot-legend jqplot-cursor-legend-label" style="vertical-align:middle;padding-top:'+rs+';"></td>'); td.appendTo(tr); td.data('seriesIndex', idx); if (this.escapeHtml) { td.text(label); } else { td.html(label); } tr = null; td = null; } return this._elem; }; })(jQuery);
// SpryDOMUtils.js - version 0.13 - Spry Pre-Release 1.7 // // Copyright (c) 2007. Adobe Systems Incorporated. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Adobe Systems Incorporated nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. (function() { // BeginSpryComponent if (typeof Spry == "undefined") window.Spry = {}; if (!Spry.Utils) Spry.Utils = {}; ////////////////////////////////////////////////////////////////////// // // Define Prototype's $() convenience function, but make sure it is // namespaced under Spry so that we avoid collisions with other // toolkits. // ////////////////////////////////////////////////////////////////////// Spry.$ = function(element) { if (arguments.length > 1) { for (var i = 0, elements = [], length = arguments.length; i < length; i++) elements.push(Spry.$(arguments[i])); return elements; } if (typeof element == 'string') element = document.getElementById(element); return element; }; ////////////////////////////////////////////////////////////////////// // // DOM Utils // ////////////////////////////////////////////////////////////////////// Spry.Utils.getAttribute = function(ele, name) { ele = Spry.$(ele); if (!ele || !name) return null; // We need to wrap getAttribute with a try/catch because IE will throw // an exception if you call it with a namespace prefixed attribute name // that doesn't exist. try { var value = ele.getAttribute(name); } catch (e) { value == undefined; } // XXX: Workaround for Safari 2.x and earlier: // // If value is undefined, the attribute didn't exist. Check to see if this is // a namespace prefixed attribute name. If it is, remove the ':' from the name // and try again. This allows us to support spry attributes of the form // "spry:region" and "spryregion". if (value == undefined && name.search(/:/) != -1) { try { var value = ele.getAttribute(name.replace(/:/, "")); } catch (e) { value == undefined; } } return value; }; Spry.Utils.setAttribute = function(ele, name, value) { ele = Spry.$(ele); if (!ele || !name) return; // IE doesn't allow you to set the "class" attribute. You // have to set the className property instead. if (name == "class") ele.className = value; else { // I'm probably being a bit paranoid, but given the fact that // getAttribute() throws exceptions when dealing with namespace // prefixed attributes, I'm going to wrap this setAttribute() // call with try/catch just in case ... try { ele.setAttribute(name, value); } catch(e) {} // XXX: Workaround for Safari 2.x and earlier: // // If this is a namespace prefixed attribute, check to make // sure an attribute was created. This is necessary because some // older versions of Safari (2.x and earlier) drop the namespace // prefixes. If the attribute was munged, try removing the ':' // character from the attribute name and setting the attribute // using the resulting name. The idea here is that even if we // remove the ':' character, Spry.Utils.getAttribute() will still // find the attribute. if (name.search(/:/) != -1 && ele.getAttribute(name) == undefined) ele.setAttribute(name.replace(/:/, ""), value); } }; Spry.Utils.removeAttribute = function(ele, name) { ele = Spry.$(ele); if (!ele || !name) return; try { ele.removeAttribute(name); } catch(e) {} // XXX: Workaround for Safari 2.x and earlier: // // If this is a namespace prefixed attribute, make sure we // also remove any attributes with the same name, but without // the ':' character. if (name.search(/:/) != -1) ele.removeAttribute(name.replace(/:/, "")); // XXX: Workaround for IE // // IE doesn't allow you to remove the "class" attribute. // It requires you to remove "className" instead, so go // ahead and try to remove that too. if (name == "class") ele.removeAttribute("className"); }; Spry.Utils.addClassName = function(ele, className) { ele = Spry.$(ele); if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) != -1)) return; ele.className += (ele.className ? " " : "") + className; }; Spry.Utils.removeClassName = function(ele, className) { ele = Spry.$(ele); if (Spry.Utils.hasClassName(ele, className)) ele.className = ele.className.replace(new RegExp("\\s*\\b" + className + "\\b", "g"), ""); }; Spry.Utils.toggleClassName = function(ele, className) { if (Spry.Utils.hasClassName(ele, className)) Spry.Utils.removeClassName(ele, className); else Spry.Utils.addClassName(ele, className); }; Spry.Utils.hasClassName = function(ele, className) { ele = Spry.$(ele); if (!ele || !className || !ele.className || ele.className.search(new RegExp("\\b" + className + "\\b")) == -1) return false; return true; }; Spry.Utils.camelizeString = function(str) { var cStr = ""; var a = str.split("-"); for (var i = 0; i < a.length; i++) { var s = a[i]; if (s) cStr = cStr ? (cStr + s.charAt(0).toUpperCase() + s.substring(1)) : s; } return cStr; }; Spry.Utils.styleStringToObject = function(styleStr) { var o = {}; if (styleStr) { var pvA = styleStr.split(";"); for (var i = 0; i < pvA.length; i++) { var pv = pvA[i]; if (pv && pv.indexOf(":") != -1) { var nvA = pv.split(":"); var n = nvA[0].replace(/^\s*|\s*$/g, ""); var v = nvA[1].replace(/^\s*|\s*$/g, ""); if (n && v) o[Spry.Utils.camelizeString(n)] = v; } } } return o; }; Spry.Utils.addEventListener = function(element, eventType, handler, capture) { try { if (!Spry.Utils.eventListenerIsBoundToElement(element, eventType, handler, capture)) { element = Spry.$(element); handler = Spry.Utils.bindEventListenerToElement(element, eventType, handler, capture); if (element.addEventListener) element.addEventListener(eventType, handler, capture); else if (element.attachEvent) element.attachEvent("on" + eventType, handler); } } catch (e) {} }; Spry.Utils.removeEventListener = function(element, eventType, handler, capture) { try { element = Spry.$(element); handler = Spry.Utils.unbindEventListenerFromElement(element, eventType, handler, capture); if (element.removeEventListener) element.removeEventListener(eventType, handler, capture); else if (element.detachEvent) element.detachEvent("on" + eventType, handler); } catch (e) {} }; Spry.Utils.eventListenerHash = {}; Spry.Utils.nextEventListenerID = 1; Spry.Utils.getHashForElementAndHandler = function(element, eventType, handler, capture) { var hash = null; element = Spry.$(element); if (element) { if (typeof element.spryEventListenerID == "undefined") element.spryEventListenerID = "e" + (Spry.Utils.nextEventListenerID++); if (typeof handler.spryEventHandlerID == "undefined") handler.spryEventHandlerID = "h" + (Spry.Utils.nextEventListenerID++); hash = element.spryEventListenerID + "-" + handler.spryEventHandlerID + "-" + eventType + (capture?"-capture":""); } return hash; }; Spry.Utils.eventListenerIsBoundToElement = function(element, eventType, handler, capture) { element = Spry.$(element); var hash = Spry.Utils.getHashForElementAndHandler(element, eventType, handler, capture); return Spry.Utils.eventListenerHash[hash] != undefined; }; Spry.Utils.bindEventListenerToElement = function(element, eventType, handler, capture) { element = Spry.$(element); var hash = Spry.Utils.getHashForElementAndHandler(element, eventType, handler, capture); if (Spry.Utils.eventListenerHash[hash]) return Spry.Utils.eventListenerHash[hash]; return Spry.Utils.eventListenerHash[hash] = function(e) { e = e || window.event; if (!e.preventDefault) e.preventDefault = function() { this.returnValue = false; }; if (!e.stopPropagation) e.stopPropagation = function() { this.cancelBubble = true; }; var result = handler.call(element, e); if (result == false) { e.preventDefault(); e.stopPropagation(); } return result; }; }; Spry.Utils.unbindEventListenerFromElement = function(element, eventType, handler, capture) { element = Spry.$(element); var hash = Spry.Utils.getHashForElementAndHandler(element, eventType, handler, capture); if (Spry.Utils.eventListenerHash[hash]) { handler = Spry.Utils.eventListenerHash[hash]; Spry.Utils.eventListenerHash[hash] = undefined; } return handler; }; Spry.Utils.cancelEvent = function(e) { if (e.preventDefault) e.preventDefault(); else e.returnValue = false; if (e.stopPropagation) e.stopPropagation(); else e.cancelBubble = true; return false; }; Spry.Utils.addLoadListener = function(handler) { if (typeof window.addEventListener != 'undefined') window.addEventListener('load', handler, false); else if (typeof document.addEventListener != 'undefined') document.addEventListener('load', handler, false); else if (typeof window.attachEvent != 'undefined') window.attachEvent('onload', handler); }; Spry.Utils.isDescendant = function(parent, child) { if (parent && child) { child = child.parentNode; while (child) { if (parent == child) return true; child = child.parentNode; } } return false; }; Spry.Utils.getAncestor = function(ele, selector) { ele = Spry.$(ele); if (ele) { var s = Spry.$$.tokenizeSequence(selector ? selector : "*")[0]; var t = s ? s[0] : null; if (t) { var p = ele.parentNode; while (p) { if (t.match(p)) return p; p = p.parentNode; } } } return null; }; ////////////////////////////////////////////////////////////////////// // // CSS Selector Matching // ////////////////////////////////////////////////////////////////////// Spry.$$ = function(selectorSequence, rootNode) { var matches = []; Spry.$$.addExtensions(matches); // If the first argument to $$() is an object, it // is assumed that all args are either a DOM element // or an array of DOM elements, in which case we // simply append all DOM elements to our special // matches array and return immediately. if (typeof arguments[0] == "object") { for (var i = 0; i < arguments.length; i++) { if (arguments[i].constructor == Array) matches.push.apply(matches, arguments[i]); else matches.push(arguments[i]); } return matches; } if (!rootNode) rootNode = document; else rootNode = Spry.$(rootNode); var sequences = Spry.$$.tokenizeSequence(selectorSequence); ++Spry.$$.queryID; var nid = 0; var ns = sequences.length; for (var i = 0; i < ns; i++) { var m = Spry.$$.processTokens(sequences[i], rootNode); var nm = m.length; for (var j = 0; j < nm; j++) { var n = m[j]; if (!n.spry$$ID) { n.spry$$ID = ++nid; matches.push(n); } } } var nm = matches.length; for (i = 0; i < nm; i++) matches[i].spry$$ID = undefined; return matches; }; Spry.$$.cache = {}; Spry.$$.queryID = 0; Spry.$$.Token = function() { this.type = Spry.$$.Token.SELECTOR; this.name = "*"; this.id = ""; this.classes = []; this.attrs = []; this.pseudos = []; }; Spry.$$.Token.Attr = function(n, v) { this.name = n; this.value = v ? new RegExp(v) : undefined; }; Spry.$$.Token.PseudoClass = function(pstr) { this.name = pstr.replace(/\(.*/, ""); this.arg = pstr.replace(/^[^\(\)]*\(?\s*|\)\s*$/g, ""); this.func = Spry.$$.pseudoFuncs[this.name]; }; Spry.$$.Token.SELECTOR = 0; Spry.$$.Token.COMBINATOR = 1; Spry.$$.Token.prototype.match = function(ele, nameAlreadyMatches) { if (this.type == Spry.$$.Token.COMBINATOR) return false; if (!nameAlreadyMatches && this.name != '*' && this.name != ele.nodeName.toLowerCase()) return false; if (this.id && this.id != ele.id) return false; var classes = this.classes; var len = classes.length; for (var i = 0; i < len; i++) { if (!ele.className || !classes[i].value.test(ele.className)) return false; } var attrs = this.attrs; len = attrs.length; for (var i = 0; i < len; i++) { var a = attrs[i]; var an = ele.attributes.getNamedItem(a.name); if (!an || (!a.value && an.nodeValue == undefined) || (a.value && !a.value.test(an.nodeValue))) return false; } var ps = this.pseudos; var len = ps.length; for (var i = 0; i < len; i++) { var p = ps[i]; if (p && p.func && !p.func(p.arg, ele, this)) return false; } return true; }; Spry.$$.Token.prototype.getNodeNameIfTypeMatches = function(ele) { var nodeName = ele.nodeName.toLowerCase(); if (this.name != '*') { if (this.name != nodeName) return null; return this.name; } return nodeName; }; Spry.$$.escapeRegExpCharsRE = /\/|\.|\*|\+|\(|\)|\[|\]|\{|\}|\\|\|/g; Spry.$$.tokenizeSequence = function(s) { var cc = Spry.$$.cache[s]; if (cc) return cc; // Attribute Selector: /(\[[^\"'~\^\$\*\|\]=]+([~\^\$\*\|]?=\s*('[^']*'|"[^"]*"|[^"'\]]+))?\s*\])/g // Simple Selector: /((:[^\.#:\s,>~\+\[\]]+\(([^\(\)]+|\([^\(\)]*\))*\))|[\.#:]?[^\.#:\s,>~\+\[\]]+)/g // Combinator: /(\s*[\s,>~\+]\s*)/g var tokenExpr = /(\[[^\"'~\^\$\*\|\]=]+([~\^\$\*\|]?=\s*('[^']*'|"[^"]*"|[^"'\]]+))?\s*\])|((:[^\.#:\s,>~\+\[\]]+\(([^\(\)]+|\([^\(\)]*\))*\))|[\.#:]?[^\.#:\s,>~\+\[\]]+)|(\s*[\s,>~\+]\s*)/g; var tkn = new Spry.$$.Token; var sequence = []; sequence.push(tkn); var tokenSequences = []; tokenSequences.push(sequence); s = s.replace(/^\s*|\s*$/, ""); var expMatch = tokenExpr.exec(s); while (expMatch) { var tstr = expMatch[0]; var c = tstr.charAt(0); switch (c) { case '.': tkn.classes.push(new Spry.$$.Token.Attr("class", "\\b" + tstr.substr(1) + "\\b")); break; case '#': tkn.id = tstr.substr(1); break; case ':': tkn.pseudos.push(new Spry.$$.Token.PseudoClass(tstr)); break; case '[': var attrComps = tstr.match(/\[([^\"'~\^\$\*\|\]=]+)(([~\^\$\*\|]?=)\s*('[^']*'|"[^"]*"|[^"'\]]+))?\s*\]/); var name = attrComps[1]; var matchType = attrComps[3]; var val = attrComps[4]; if (val) { val = val.replace(/^['"]|['"]$/g, ""); val = val.replace(Spry.$$.escapeRegExpCharsRE, '\\$&'); } var matchStr = undefined; switch(matchType) { case "=": matchStr = "^" + val + "$"; break; case "^=": matchStr = "^" + val; break; case "$=": matchStr = val + "$"; break; case "~=": case "|=": matchStr = "\\b" + val + "\\b"; break; case "*=": matchStr = val; break; } tkn.attrs.push(new Spry.$$.Token.Attr(name, matchStr)); break; default: var combiMatch = tstr.match(/^\s*([\s,~>\+])\s*$/); if (combiMatch) { if (combiMatch[1] == ',') { sequence = new Array; tokenSequences.push(sequence); tkn = new Spry.$$.Token; sequence.push(tkn); } else { tkn = new Spry.$$.Token; tkn.type = Spry.$$.Token.COMBINATOR; tkn.name = combiMatch[1]; sequence.push(tkn); tkn = new Spry.$$.Token(); sequence.push(tkn); } } else tkn.name = tstr.toLowerCase(); break; } expMatch = tokenExpr.exec(s); } Spry.$$.cache[s] = tokenSequences; return tokenSequences; }; Spry.$$.combinatorFuncs = { // Element Descendant " ": function(nodes, token) { var uid = ++Spry.$$.uniqueID; var results = []; var nn = nodes.length; for (var i = 0; i < nn; i++) { var n = nodes[i]; if (uid != n.spry$$uid) { // n.spry$$uid = uid; var ea = nodes[i].getElementsByTagName(token.name); var ne = ea.length; for (var j = 0; j < ne; j++) { var e = ea[j]; // If the token matches, add it to our results. We have // to make sure e is an element because IE6 returns the DOCTYPE // tag as a comment when '*' is used in the call to getElementsByTagName(). if (e.nodeType == 1 /* Node.ELEMENT_NODE */ && token.match(e, true)) results.push(e); e.spry$$uid = uid; } } } return results; }, // Element Child ">": function(nodes, token) { var results = []; var nn = nodes.length; for (var i = 0; i < nn; i++) { var n = nodes[i].firstChild; while (n) { if (n.nodeType == 1 /* Node.ELEMENT_NODE */ && token.match(n)) results.push(n); n = n.nextSibling; } } return results; }, // Element Immediately Preceded By "+": function(nodes, token) { var results = []; var nn = nodes.length; for (var i = 0; i < nn; i++) { var n = nodes[i].nextSibling; while (n && n.nodeType != 1 /* Node.ELEMENT_NODE */) n = n.nextSibling; if (n && token.match(n)) results.push(n); } return results; }, // Element Preceded By "~": function(nodes, token) { var uid = ++Spry.$$.uniqueID; var results = []; var nn = nodes.length; for (var i = 0; i < nn; i++) { var n = nodes[i].nextSibling; while (n) { if (n.nodeType == 1 /* Node.ELEMENT_NODE */) { if (uid == n.spry$$uid) break; if (token.match(n)) { results.push(n); n.spry$$uid = uid; } } n = n.nextSibling; } } return results; } }; Spry.$$.uniqueID = 0; Spry.$$.pseudoFuncs = { ":first-child": function(arg, node, token) { var n = node.previousSibling; while (n) { if (n.nodeType == 1) return false; // Node.ELEMENT_NODE n = n.previousSibling; } return true; }, ":last-child": function(arg, node, token) { var n = node.nextSibling; while (n) { if (n.nodeType == 1) // Node.ELEMENT_NODE return false; n = n.nextSibling; } return true; }, ":empty": function(arg, node, token) { var n = node.firstChild; while (n) { switch(n.nodeType) { case 1: // Node.ELEMENT_NODE case 3: // Node.TEXT_NODE case 4: // Node.CDATA_NODE case 5: // Node.ENTITY_REFERENCE_NODE return false; } n = n.nextSibling; } return true; }, ":nth-child": function(arg, node, token) { return Spry.$$.nthChild(arg, node, token); }, ":nth-last-child": function(arg, node, token) { return Spry.$$.nthChild(arg, node, token, true); }, ":nth-of-type": function(arg, node, token) { return Spry.$$.nthChild(arg, node, token, false, true); }, ":nth-last-of-type": function(arg, node, token) { return Spry.$$.nthChild(arg, node, token, true, true); }, ":first-of-type": function(arg, node, token) { var nodeName = token.getNodeNameIfTypeMatches(node); if (!nodeName) return false; var n = node.previousSibling; while (n) { if (n.nodeType == 1 && nodeName == n.nodeName.toLowerCase()) return false; // Node.ELEMENT_NODE n = n.previousSibling; } return true; }, ":last-of-type": function(arg, node, token) { var nodeName = token.getNodeNameIfTypeMatches(node); if (!nodeName) return false; var n = node.nextSibling; while (n) { if (n.nodeType == 1 && nodeName == n.nodeName.toLowerCase()) // Node.ELEMENT_NODE return false; n = n.nextSibling; } return true; }, ":only-child": function(arg, node, token) { var f = Spry.$$.pseudoFuncs; return f[":first-child"](arg, node, token) && f[":last-child"](arg, node, token); }, ":only-of-type": function(arg, node, token) { var f = Spry.$$.pseudoFuncs; return f[":first-of-type"](arg, node, token) && f[":last-of-type"](arg, node, token); }, ":not": function(arg, node, token) { var s = Spry.$$.tokenizeSequence(arg)[0]; var t = s ? s[0] : null; return !t || !t.match(node); }, ":enabled": function(arg, node, token) { return !node.disabled; }, ":disabled": function(arg, node, token) { return node.disabled; }, ":checked": function(arg, node, token) { return node.checked; }, ":root": function(arg, node, token) { return node.parentNode && node.ownerDocument && node.parentNode == node.ownerDocument; } }; Spry.$$.nthRegExp = /((-|[0-9]+)?n)?([+-]?[0-9]*)/; Spry.$$.nthCache = { "even": { a: 2, b: 0, mode: 1, invalid: false } , "odd": { a: 2, b: 1, mode: 1, invalid: false } , "2n": { a: 2, b: 0, mode: 1, invalid: false } , "2n+1": { a: 2, b: 1, mode: 1, invalid: false } }; Spry.$$.parseNthChildString = function(str) { var o = Spry.$$.nthCache[str]; if (!o) { var m = str.match(Spry.$$.nthRegExp); var n = m[1]; var a = m[2]; var b = m[3]; if (!a) { // An 'a' value was not specified. Was there an 'n' present? // If so, we treat it as an increment of 1, otherwise we're // in no-repeat mode. a = n ? 1 : 0; } else if (a == "-") { // The string is using the "-n" short-hand which is // short for -1. a = -1; } else { // An integer repeat value for 'a' was specified. Convert // it into number. a = parseInt(a, 10); } // If a 'b' value was specified, turn it into a number. // If no 'b' value was specified, default to zero. b = b ? parseInt(b, 10) : 0; // Figure out the mode: // // -1 - repeat backwards // 0 - no repeat // 1 - repeat forwards var mode = (a == 0) ? 0 : ((a > 0) ? 1 : -1); var invalid = false; // Fix up 'a' and 'b' for proper repeating. if (a > 0 && b < 0) { b = b % a; b = ((b=(b%a)) < 0) ? a + b : b; } else if (a < 0) { if (b < 0) invalid = true; else a = Math.abs(a); } o = new Object; o.a = a; o.b = b; o.mode = mode; o.invalid = invalid; Spry.$$.nthCache[str] = o; } return o; }; Spry.$$.nthChild = function(arg, node, token, fromLastSib, matchNodeName) { if (matchNodeName) { var nodeName = token.getNodeNameIfTypeMatches(node); if (!nodeName) return false; } var o = Spry.$$.parseNthChildString(arg); if (o.invalid) return false; var qidProp = "spry$$ncQueryID"; var posProp = "spry$$ncPos"; var countProp = "spry$$ncCount"; if (matchNodeName) { qidProp += nodeName; posProp += nodeName; countProp += nodeName; } var parent = node.parentNode; if (parent[qidProp] != Spry.$$.queryID) { var pos = 0; parent[qidProp] = Spry.$$.queryID; var c = parent.firstChild; while (c) { if (c.nodeType == 1 && (!matchNodeName || nodeName == c.nodeName.toLowerCase())) c[posProp] = ++pos; c = c.nextSibling; } parent[countProp] = pos; } pos = node[posProp]; if (fromLastSib) pos = parent[countProp] - pos + 1; /* var sib = fromLastSib ? "nextSibling" : "previousSibling"; var pos = 1; var n = node[sib]; while (n) { if (n.nodeType == 1 && (!matchNodeName || nodeName == n.nodeName.toLowerCase())) { if (n == node) break; ++pos; } n = n[sib]; } */ if (o.mode == 0) // Exact match return pos == o.b; if (o.mode > 0) // Forward Repeat return (pos < o.b) ? false : (!((pos - o.b) % o.a)); return (pos > o.b) ? false : (!((o.b - pos) % o.a)); // Backward Repeat }; Spry.$$.processTokens = function(tokens, root) { var numTokens = tokens.length; var nodeSet = [ root ]; var combiFunc = null; for (var i = 0; i < numTokens && nodeSet.length > 0; i++) { var t = tokens[i]; if (t.type == Spry.$$.Token.SELECTOR) { if (combiFunc) { nodeSet = combiFunc(nodeSet, t); combiFunc = null; } else nodeSet = Spry.$$.getMatchingElements(nodeSet, t); } else // Spry.$$.Token.COMBINATOR combiFunc = Spry.$$.combinatorFuncs[t.name]; } return nodeSet; }; Spry.$$.getMatchingElements = function(nodes, token) { var results = []; if (token.id) { n = nodes[0]; if (n && n.ownerDocument) { var e = n.ownerDocument.getElementById(token.id); if (e) { // XXX: We need to make sure that the element // we found is actually underneath the root // we were given! if (token.match(e)) results.push(e); } return results; } } var nn = nodes.length; for (var i = 0; i < nn; i++) { var n = nodes[i]; // if (token.match(n)) results.push(n); var ea = n.getElementsByTagName(token.name); var ne = ea.length; for (var j = 0; j < ne; j++) { var e = ea[j]; // If the token matches, add it to our results. We have // to make sure e is an element because IE6 returns the DOCTYPE // tag as a comment when '*' is used in the call to getElementsByTagName(). if (e.nodeType == 1 /* Node.ELEMENT_NODE */ && token.match(e, true)) results.push(e); } } return results; }; /* Spry.$$.dumpSequences = function(sequences) { Spry.Debug.trace("<hr />Number of Sequences: " + sequences.length); for (var i = 0; i < sequences.length; i++) { var str = ""; var s = sequences[i]; Spry.Debug.trace("<hr />Sequence " + i + " -- Tokens: " + s.length); for (var j = 0; j < s.length; j++) { var t = s[j]; if (t.type == Spry.$$.Token.SELECTOR) { str += " SELECTOR:\n Name: " + t.name + "\n ID: " + t.id + "\n Attrs:\n"; for (var k = 0; k < t.classes.length; k++) str += " " + t.classes[k].name + ": " + t.classes[k].value + "\n"; for (var k = 0; k < t.attrs.length; k++) str += " " + t.attrs[k].name + ": " + t.attrs[k].value + "\n"; str += " Pseudos:\n"; for (var k = 0; k < t.pseudos.length; k++) str += " " + t.pseudos[k].name + (t.pseudos[k].arg ? "(" + t.pseudos[k].arg + ")" : "") + "\n"; } else { str += " COMBINATOR:\n Name: '" + t.name + "'\n"; } } Spry.Debug.trace("<pre>" + Spry.Utils.encodeEntities(str) + "</pre>"); } }; */ Spry.$$.addExtensions = function(a) { for (var f in Spry.$$.Results) a[f] = Spry.$$.Results[f]; }; Spry.$$.Results = {}; Spry.$$.Results.forEach = function(func) { var n = this.length; for (var i = 0; i < n; i++) func(this[i]); return this; }; Spry.$$.Results.setAttribute = function(name, value) { return this.forEach(function(n) { Spry.Utils.setAttribute(n, name, value); }); }; Spry.$$.Results.removeAttribute = function(name) { return this.forEach(function(n) { Spry.Utils.removeAttribute(n, name); }); }; Spry.$$.Results.addClassName = function(className) { return this.forEach(function(n) { Spry.Utils.addClassName(n, className); }); }; Spry.$$.Results.removeClassName = function(className) { return this.forEach(function(n) { Spry.Utils.removeClassName(n, className); }); }; Spry.$$.Results.toggleClassName = function(className) { return this.forEach(function(n) { Spry.Utils.toggleClassName(n, className); }); }; Spry.$$.Results.addEventListener = function(eventType, handler, capture, bindHandler) { return this.forEach(function(n) { Spry.Utils.addEventListener(n, eventType, handler, capture, bindHandler); }); }; Spry.$$.Results.removeEventListener = function(eventType, handler, capture) { return this.forEach(function(n) { Spry.Utils.removeEventListener(n, eventType, handler, capture); }); }; Spry.$$.Results.setStyle = function(style) { if (style) { style = Spry.Utils.styleStringToObject(style); this.forEach(function(n) { for (var p in style) try { n.style[p] = style[p]; } catch (e) {} }); } return this; }; Spry.$$.Results.setProperty = function(prop, value) { if (prop) { if (typeof prop == "string") { var p = {}; p[prop] = value; prop = p; } this.forEach(function(n) { for (var p in prop) try { n[p] = prop[p]; } catch (e) {} }); } return this; }; })(); // EndSpryComponent