Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
/**
* vis.js
* https://github.com/almende/vis
*
* A dynamic, browser-based visualization library.
*
* @version 3.12.0
* @date 2015-04-07
*
* @license
* Copyright (C) 2011-2014 Almende B.V, http://almende.com
*
* Vis.js is dual licensed under both
*
* * The Apache 2.0 License
* http://www.apache.org/licenses/LICENSE-2.0
*
* and
*
* * The MIT License
* http://opensource.org/licenses/MIT
*
* Vis.js may be distributed under either license.
*/
"use strict";
(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["vis"] = factory();
else
root["vis"] = 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] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = 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;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
// utils
exports.util = __webpack_require__(1);
exports.DOMutil = __webpack_require__(2);
// data
exports.DataSet = __webpack_require__(3);
exports.DataView = __webpack_require__(4);
exports.Queue = __webpack_require__(5);
// Graph3d
exports.Graph3d = __webpack_require__(6);
exports.graph3d = {
Camera: __webpack_require__(7),
Filter: __webpack_require__(8),
Point2d: __webpack_require__(9),
Point3d: __webpack_require__(10),
Slider: __webpack_require__(11),
StepNumber: __webpack_require__(12)
};
// Timeline
exports.Timeline = __webpack_require__(13);
exports.Graph2d = __webpack_require__(14);
exports.timeline = {
DateUtil: __webpack_require__(15),
DataStep: __webpack_require__(16),
Range: __webpack_require__(17),
stack: __webpack_require__(18),
TimeStep: __webpack_require__(19),
components: {
items: {
Item: __webpack_require__(20),
BackgroundItem: __webpack_require__(21),
BoxItem: __webpack_require__(22),
PointItem: __webpack_require__(23),
RangeItem: __webpack_require__(24)
},
Component: __webpack_require__(25),
CurrentTime: __webpack_require__(26),
CustomTime: __webpack_require__(27),
DataAxis: __webpack_require__(28),
GraphGroup: __webpack_require__(29),
Group: __webpack_require__(30),
BackgroundGroup: __webpack_require__(31),
ItemSet: __webpack_require__(32),
Legend: __webpack_require__(33),
LineGraph: __webpack_require__(34),
TimeAxis: __webpack_require__(35)
}
};
// Network
exports.Network = __webpack_require__(36);
exports.network = {
Edge: __webpack_require__(37),
Groups: __webpack_require__(38),
Images: __webpack_require__(39),
Node: __webpack_require__(40),
Popup: __webpack_require__(41),
dotparser: __webpack_require__(42),
gephiParser: __webpack_require__(43)
};
// Deprecated since v3.0.0
exports.Graph = function () {
throw new Error('Graph is renamed to Network. Please create a graph as new vis.Network(...)');
};
// bundled external libraries
exports.moment = __webpack_require__(44);
exports.hammer = __webpack_require__(45);
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
// utility functions
// first check if moment.js is already loaded in the browser window, if so,
// use this instance. Else, load via commonjs.
var moment = __webpack_require__(44);
/**
* Test whether given object is a number
* @param {*} object
* @return {Boolean} isNumber
*/
exports.isNumber = function(object) {
return (object instanceof Number || typeof object == 'number');
};
/**
* this function gives you a range between 0 and 1 based on the min and max values in the set, the total sum of all values and the current value.
*
* @param min
* @param max
* @param total
* @param value
* @returns {number}
*/
exports.giveRange = function(min,max,total,value) {
if (max == min) {
return 0.5;
}
else {
var scale = 1 / (max - min);
return Math.max(0,(value - min)*scale);
}
}
/**
* Test whether given object is a string
* @param {*} object
* @return {Boolean} isString
*/
exports.isString = function(object) {
return (object instanceof String || typeof object == 'string');
};
/**
* Test whether given object is a Date, or a String containing a Date
* @param {Date | String} object
* @return {Boolean} isDate
*/
exports.isDate = function(object) {
if (object instanceof Date) {
return true;
}
else if (exports.isString(object)) {
// test whether this string contains a date
var match = ASPDateRegex.exec(object);
if (match) {
return true;
}
else if (!isNaN(Date.parse(object))) {
return true;
}
}
return false;
};
/**
* Test whether given object is an instance of google.visualization.DataTable
* @param {*} object
* @return {Boolean} isDataTable
*/
exports.isDataTable = function(object) {
return (typeof (google) !== 'undefined') &&
(google.visualization) &&
(google.visualization.DataTable) &&
(object instanceof google.visualization.DataTable);
};
/**
* Create a semi UUID
* source: http://stackoverflow.com/a/105074/1262753
* @return {String} uuid
*/
exports.randomUUID = function() {
var S4 = function () {
return Math.floor(
Math.random() * 0x10000 /* 65536 */
).toString(16);
};
return (
S4() + S4() + '-' +
S4() + '-' +
S4() + '-' +
S4() + '-' +
S4() + S4() + S4()
);
};
/**
* Extend object a with the properties of object b or a series of objects
* Only properties with defined values are copied
* @param {Object} a
* @param {... Object} b
* @return {Object} a
*/
exports.extend = function (a, b) {
for (var i = 1, len = arguments.length; i < len; i++) {
var other = arguments[i];
for (var prop in other) {
if (other.hasOwnProperty(prop)) {
a[prop] = other[prop];
}
}
}
return a;
};
/**
* Extend object a with selected properties of object b or a series of objects
* Only properties with defined values are copied
* @param {Array.} props
* @param {Object} a
* @param {... Object} b
* @return {Object} a
*/
exports.selectiveExtend = function (props, a, b) {
if (!Array.isArray(props)) {
throw new Error('Array with property names expected as first argument');
}
for (var i = 2; i < arguments.length; i++) {
var other = arguments[i];
for (var p = 0; p < props.length; p++) {
var prop = props[p];
if (other.hasOwnProperty(prop)) {
a[prop] = other[prop];
}
}
}
return a;
};
/**
* Extend object a with selected properties of object b or a series of objects
* Only properties with defined values are copied
* @param {Array.} props
* @param {Object} a
* @param {... Object} b
* @return {Object} a
*/
exports.selectiveDeepExtend = function (props, a, b) {
// TODO: add support for Arrays to deepExtend
if (Array.isArray(b)) {
throw new TypeError('Arrays are not supported by deepExtend');
}
for (var i = 2; i < arguments.length; i++) {
var other = arguments[i];
for (var p = 0; p < props.length; p++) {
var prop = props[p];
if (other.hasOwnProperty(prop)) {
if (b[prop] && b[prop].constructor === Object) {
if (a[prop] === undefined) {
a[prop] = {};
}
if (a[prop].constructor === Object) {
exports.deepExtend(a[prop], b[prop]);
}
else {
a[prop] = b[prop];
}
} else if (Array.isArray(b[prop])) {
throw new TypeError('Arrays are not supported by deepExtend');
} else {
a[prop] = b[prop];
}
}
}
}
return a;
};
/**
* Extend object a with selected properties of object b or a series of objects
* Only properties with defined values are copied
* @param {Array.} props
* @param {Object} a
* @param {... Object} b
* @return {Object} a
*/
exports.selectiveNotDeepExtend = function (props, a, b) {
// TODO: add support for Arrays to deepExtend
if (Array.isArray(b)) {
throw new TypeError('Arrays are not supported by deepExtend');
}
for (var prop in b) {
if (b.hasOwnProperty(prop)) {
if (props.indexOf(prop) == -1) {
if (b[prop] && b[prop].constructor === Object) {
if (a[prop] === undefined) {
a[prop] = {};
}
if (a[prop].constructor === Object) {
exports.deepExtend(a[prop], b[prop]);
}
else {
a[prop] = b[prop];
}
} else if (Array.isArray(b[prop])) {
throw new TypeError('Arrays are not supported by deepExtend');
} else {
a[prop] = b[prop];
}
}
}
}
return a;
};
/**
* Deep extend an object a with the properties of object b
* @param {Object} a
* @param {Object} b
* @returns {Object}
*/
exports.deepExtend = function(a, b) {
// TODO: add support for Arrays to deepExtend
if (Array.isArray(b)) {
throw new TypeError('Arrays are not supported by deepExtend');
}
for (var prop in b) {
if (b.hasOwnProperty(prop)) {
if (b[prop] && b[prop].constructor === Object) {
if (a[prop] === undefined) {
a[prop] = {};
}
if (a[prop].constructor === Object) {
exports.deepExtend(a[prop], b[prop]);
}
else {
a[prop] = b[prop];
}
} else if (Array.isArray(b[prop])) {
throw new TypeError('Arrays are not supported by deepExtend');
} else {
a[prop] = b[prop];
}
}
}
return a;
};
/**
* Test whether all elements in two arrays are equal.
* @param {Array} a
* @param {Array} b
* @return {boolean} Returns true if both arrays have the same length and same
* elements.
*/
exports.equalArray = function (a, b) {
if (a.length != b.length) return false;
for (var i = 0, len = a.length; i < len; i++) {
if (a[i] != b[i]) return false;
}
return true;
};
/**
* Convert an object to another type
* @param {Boolean | Number | String | Date | Moment | Null | undefined} object
* @param {String | undefined} type Name of the type. Available types:
* 'Boolean', 'Number', 'String',
* 'Date', 'Moment', ISODate', 'ASPDate'.
* @return {*} object
* @throws Error
*/
exports.convert = function(object, type) {
var match;
if (object === undefined) {
return undefined;
}
if (object === null) {
return null;
}
if (!type) {
return object;
}
if (!(typeof type === 'string') && !(type instanceof String)) {
throw new Error('Type must be a string');
}
//noinspection FallthroughInSwitchStatementJS
switch (type) {
case 'boolean':
case 'Boolean':
return Boolean(object);
case 'number':
case 'Number':
return Number(object.valueOf());
case 'string':
case 'String':
return String(object);
case 'Date':
if (exports.isNumber(object)) {
return new Date(object);
}
if (object instanceof Date) {
return new Date(object.valueOf());
}
else if (moment.isMoment(object)) {
return new Date(object.valueOf());
}
if (exports.isString(object)) {
match = ASPDateRegex.exec(object);
if (match) {
// object is an ASP date
return new Date(Number(match[1])); // parse number
}
else {
return moment(object).toDate(); // parse string
}
}
else {
throw new Error(
'Cannot convert object of type ' + exports.getType(object) +
' to type Date');
}
case 'Moment':
if (exports.isNumber(object)) {
return moment(object);
}
if (object instanceof Date) {
return moment(object.valueOf());
}
else if (moment.isMoment(object)) {
return moment(object);
}
if (exports.isString(object)) {
match = ASPDateRegex.exec(object);
if (match) {
// object is an ASP date
return moment(Number(match[1])); // parse number
}
else {
return moment(object); // parse string
}
}
else {
throw new Error(
'Cannot convert object of type ' + exports.getType(object) +
' to type Date');
}
case 'ISODate':
if (exports.isNumber(object)) {
return new Date(object);
}
else if (object instanceof Date) {
return object.toISOString();
}
else if (moment.isMoment(object)) {
return object.toDate().toISOString();
}
else if (exports.isString(object)) {
match = ASPDateRegex.exec(object);
if (match) {
// object is an ASP date
return new Date(Number(match[1])).toISOString(); // parse number
}
else {
return new Date(object).toISOString(); // parse string
}
}
else {
throw new Error(
'Cannot convert object of type ' + exports.getType(object) +
' to type ISODate');
}
case 'ASPDate':
if (exports.isNumber(object)) {
return '/Date(' + object + ')/';
}
else if (object instanceof Date) {
return '/Date(' + object.valueOf() + ')/';
}
else if (exports.isString(object)) {
match = ASPDateRegex.exec(object);
var value;
if (match) {
// object is an ASP date
value = new Date(Number(match[1])).valueOf(); // parse number
}
else {
value = new Date(object).valueOf(); // parse string
}
return '/Date(' + value + ')/';
}
else {
throw new Error(
'Cannot convert object of type ' + exports.getType(object) +
' to type ASPDate');
}
default:
throw new Error('Unknown type "' + type + '"');
}
};
// parse ASP.Net Date pattern,
// for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
// code from http://momentjs.com/
var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
/**
* Get the type of an object, for example exports.getType([]) returns 'Array'
* @param {*} object
* @return {String} type
*/
exports.getType = function(object) {
var type = typeof object;
if (type == 'object') {
if (object == null) {
return 'null';
}
if (object instanceof Boolean) {
return 'Boolean';
}
if (object instanceof Number) {
return 'Number';
}
if (object instanceof String) {
return 'String';
}
if (Array.isArray(object)) {
return 'Array';
}
if (object instanceof Date) {
return 'Date';
}
return 'Object';
}
else if (type == 'number') {
return 'Number';
}
else if (type == 'boolean') {
return 'Boolean';
}
else if (type == 'string') {
return 'String';
}
return type;
};
/**
* Retrieve the absolute left value of a DOM element
* @param {Element} elem A dom element, for example a div
* @return {number} left The absolute left position of this element
* in the browser page.
*/
exports.getAbsoluteLeft = function(elem) {
return elem.getBoundingClientRect().left + window.pageXOffset;
};
/**
* Retrieve the absolute top value of a DOM element
* @param {Element} elem A dom element, for example a div
* @return {number} top The absolute top position of this element
* in the browser page.
*/
exports.getAbsoluteTop = function(elem) {
return elem.getBoundingClientRect().top + window.pageYOffset;
};
/**
* add a className to the given elements style
* @param {Element} elem
* @param {String} className
*/
exports.addClassName = function(elem, className) {
var classes = elem.className.split(' ');
if (classes.indexOf(className) == -1) {
classes.push(className); // add the class to the array
elem.className = classes.join(' ');
}
};
/**
* add a className to the given elements style
* @param {Element} elem
* @param {String} className
*/
exports.removeClassName = function(elem, className) {
var classes = elem.className.split(' ');
var index = classes.indexOf(className);
if (index != -1) {
classes.splice(index, 1); // remove the class from the array
elem.className = classes.join(' ');
}
};
/**
* For each method for both arrays and objects.
* In case of an array, the built-in Array.forEach() is applied.
* In case of an Object, the method loops over all properties of the object.
* @param {Object | Array} object An Object or Array
* @param {function} callback Callback method, called for each item in
* the object or array with three parameters:
* callback(value, index, object)
*/
exports.forEach = function(object, callback) {
var i,
len;
if (Array.isArray(object)) {
// array
for (i = 0, len = object.length; i < len; i++) {
callback(object[i], i, object);
}
}
else {
// object
for (i in object) {
if (object.hasOwnProperty(i)) {
callback(object[i], i, object);
}
}
}
};
/**
* Convert an object into an array: all objects properties are put into the
* array. The resulting array is unordered.
* @param {Object} object
* @param {Array} array
*/
exports.toArray = function(object) {
var array = [];
for (var prop in object) {
if (object.hasOwnProperty(prop)) array.push(object[prop]);
}
return array;
}
/**
* Update a property in an object
* @param {Object} object
* @param {String} key
* @param {*} value
* @return {Boolean} changed
*/
exports.updateProperty = function(object, key, value) {
if (object[key] !== value) {
object[key] = value;
return true;
}
else {
return false;
}
};
/**
* Add and event listener. Works for all browsers
* @param {Element} element An html element
* @param {string} action The action, for example "click",
* without the prefix "on"
* @param {function} listener The callback function to be executed
* @param {boolean} [useCapture]
*/
exports.addEventListener = function(element, action, listener, useCapture) {
if (element.addEventListener) {
if (useCapture === undefined)
useCapture = false;
if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
action = "DOMMouseScroll"; // For Firefox
}
element.addEventListener(action, listener, useCapture);
} else {
element.attachEvent("on" + action, listener); // IE browsers
}
};
/**
* Remove an event listener from an element
* @param {Element} element An html dom element
* @param {string} action The name of the event, for example "mousedown"
* @param {function} listener The listener function
* @param {boolean} [useCapture]
*/
exports.removeEventListener = function(element, action, listener, useCapture) {
if (element.removeEventListener) {
// non-IE browsers
if (useCapture === undefined)
useCapture = false;
if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
action = "DOMMouseScroll"; // For Firefox
}
element.removeEventListener(action, listener, useCapture);
} else {
// IE browsers
element.detachEvent("on" + action, listener);
}
};
/**
* Cancels the event if it is cancelable, without stopping further propagation of the event.
*/
exports.preventDefault = function (event) {
if (!event)
event = window.event;
if (event.preventDefault) {
event.preventDefault(); // non-IE browsers
}
else {
event.returnValue = false; // IE browsers
}
};
/**
* Get HTML element which is the target of the event
* @param {Event} event
* @return {Element} target element
*/
exports.getTarget = function(event) {
// code from http://www.quirksmode.org/js/events_properties.html
if (!event) {
event = window.event;
}
var target;
if (event.target) {
target = event.target;
}
else if (event.srcElement) {
target = event.srcElement;
}
if (target.nodeType != undefined && target.nodeType == 3) {
// defeat Safari bug
target = target.parentNode;
}
return target;
};
/**
* Check if given element contains given parent somewhere in the DOM tree
* @param {Element} element
* @param {Element} parent
*/
exports.hasParent = function (element, parent) {
var e = element;
while (e) {
if (e === parent) {
return true;
}
e = e.parentNode;
}
return false;
};
exports.option = {};
/**
* Convert a value into a boolean
* @param {Boolean | function | undefined} value
* @param {Boolean} [defaultValue]
* @returns {Boolean} bool
*/
exports.option.asBoolean = function (value, defaultValue) {
if (typeof value == 'function') {
value = value();
}
if (value != null) {
return (value != false);
}
return defaultValue || null;
};
/**
* Convert a value into a number
* @param {Boolean | function | undefined} value
* @param {Number} [defaultValue]
* @returns {Number} number
*/
exports.option.asNumber = function (value, defaultValue) {
if (typeof value == 'function') {
value = value();
}
if (value != null) {
return Number(value) || defaultValue || null;
}
return defaultValue || null;
};
/**
* Convert a value into a string
* @param {String | function | undefined} value
* @param {String} [defaultValue]
* @returns {String} str
*/
exports.option.asString = function (value, defaultValue) {
if (typeof value == 'function') {
value = value();
}
if (value != null) {
return String(value);
}
return defaultValue || null;
};
/**
* Convert a size or location into a string with pixels or a percentage
* @param {String | Number | function | undefined} value
* @param {String} [defaultValue]
* @returns {String} size
*/
exports.option.asSize = function (value, defaultValue) {
if (typeof value == 'function') {
value = value();
}
if (exports.isString(value)) {
return value;
}
else if (exports.isNumber(value)) {
return value + 'px';
}
else {
return defaultValue || null;
}
};
/**
* Convert a value into a DOM element
* @param {HTMLElement | function | undefined} value
* @param {HTMLElement} [defaultValue]
* @returns {HTMLElement | null} dom
*/
exports.option.asElement = function (value, defaultValue) {
if (typeof value == 'function') {
value = value();
}
return value || defaultValue || null;
};
/**
* http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
*
* @param {String} hex
* @returns {{r: *, g: *, b: *}} | 255 range
*/
exports.hexToRGB = function(hex) {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
};
/**
* This function takes color in hex format or rgb() or rgba() format and overrides the opacity. Returns rgba() string.
* @param color
* @param opacity
* @returns {*}
*/
exports.overrideOpacity = function(color,opacity) {
if (color.indexOf("rgb") != -1) {
var rgb = color.substr(color.indexOf("(")+1).replace(")","").split(",");
return "rgba(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + "," + opacity + ")"
}
else {
var rgb = exports.hexToRGB(color);
if (rgb == null) {
return color;
}
else {
return "rgba(" + rgb.r + "," + rgb.g + "," + rgb.b + "," + opacity + ")"
}
}
}
/**
*
* @param red 0 -- 255
* @param green 0 -- 255
* @param blue 0 -- 255
* @returns {string}
* @constructor
*/
exports.RGBToHex = function(red,green,blue) {
return "#" + ((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1);
};
/**
* Parse a color property into an object with border, background, and
* highlight colors
* @param {Object | String} color
* @return {Object} colorObject
*/
exports.parseColor = function(color) {
var c;
if (exports.isString(color)) {
if (exports.isValidRGB(color)) {
var rgb = color.substr(4).substr(0,color.length-5).split(',');
color = exports.RGBToHex(rgb[0],rgb[1],rgb[2]);
}
if (exports.isValidHex(color)) {
var hsv = exports.hexToHSV(color);
var lighterColorHSV = {h:hsv.h,s:hsv.s * 0.45,v:Math.min(1,hsv.v * 1.05)};
var darkerColorHSV = {h:hsv.h,s:Math.min(1,hsv.v * 1.25),v:hsv.v*0.6};
var darkerColorHex = exports.HSVToHex(darkerColorHSV.h ,darkerColorHSV.h ,darkerColorHSV.v);
var lighterColorHex = exports.HSVToHex(lighterColorHSV.h,lighterColorHSV.s,lighterColorHSV.v);
c = {
background: color,
border:darkerColorHex,
highlight: {
background:lighterColorHex,
border:darkerColorHex
},
hover: {
background:lighterColorHex,
border:darkerColorHex
}
};
}
else {
c = {
background:color,
border:color,
highlight: {
background:color,
border:color
},
hover: {
background:color,
border:color
}
};
}
}
else {
c = {};
c.background = color.background || 'white';
c.border = color.border || c.background;
if (exports.isString(color.highlight)) {
c.highlight = {
border: color.highlight,
background: color.highlight
}
}
else {
c.highlight = {};
c.highlight.background = color.highlight && color.highlight.background || c.background;
c.highlight.border = color.highlight && color.highlight.border || c.border;
}
if (exports.isString(color.hover)) {
c.hover = {
border: color.hover,
background: color.hover
}
}
else {
c.hover = {};
c.hover.background = color.hover && color.hover.background || c.background;
c.hover.border = color.hover && color.hover.border || c.border;
}
}
return c;
};
/**
* http://www.javascripter.net/faq/rgb2hsv.htm
*
* @param red
* @param green
* @param blue
* @returns {*}
* @constructor
*/
exports.RGBToHSV = function(red,green,blue) {
red=red/255; green=green/255; blue=blue/255;
var minRGB = Math.min(red,Math.min(green,blue));
var maxRGB = Math.max(red,Math.max(green,blue));
// Black-gray-white
if (minRGB == maxRGB) {
return {h:0,s:0,v:minRGB};
}
// Colors other than black-gray-white:
var d = (red==minRGB) ? green-blue : ((blue==minRGB) ? red-green : blue-red);
var h = (red==minRGB) ? 3 : ((blue==minRGB) ? 1 : 5);
var hue = 60*(h - d/(maxRGB - minRGB))/360;
var saturation = (maxRGB - minRGB)/maxRGB;
var value = maxRGB;
return {h:hue,s:saturation,v:value};
};
var cssUtil = {
// split a string with css styles into an object with key/values
split: function (cssText) {
var styles = {};
cssText.split(';').forEach(function (style) {
if (style.trim() != '') {
var parts = style.split(':');
var key = parts[0].trim();
var value = parts[1].trim();
styles[key] = value;
}
});
return styles;
},
// build a css text string from an object with key/values
join: function (styles) {
return Object.keys(styles)
.map(function (key) {
return key + ': ' + styles[key];
})
.join('; ');
}
};
/**
* Append a string with css styles to an element
* @param {Element} element
* @param {String} cssText
*/
exports.addCssText = function (element, cssText) {
var currentStyles = cssUtil.split(element.style.cssText);
var newStyles = cssUtil.split(cssText);
var styles = exports.extend(currentStyles, newStyles);
element.style.cssText = cssUtil.join(styles);
};
/**
* Remove a string with css styles from an element
* @param {Element} element
* @param {String} cssText
*/
exports.removeCssText = function (element, cssText) {
var styles = cssUtil.split(element.style.cssText);
var removeStyles = cssUtil.split(cssText);
for (var key in removeStyles) {
if (removeStyles.hasOwnProperty(key)) {
delete styles[key];
}
}
element.style.cssText = cssUtil.join(styles);
};
/**
* https://gist.github.com/mjijackson/5311256
* @param h
* @param s
* @param v
* @returns {{r: number, g: number, b: number}}
* @constructor
*/
exports.HSVToRGB = function(h, s, v) {
var r, g, b;
var i = Math.floor(h * 6);
var f = h * 6 - i;
var p = v * (1 - s);
var q = v * (1 - f * s);
var t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0: r = v, g = t, b = p; break;
case 1: r = q, g = v, b = p; break;
case 2: r = p, g = v, b = t; break;
case 3: r = p, g = q, b = v; break;
case 4: r = t, g = p, b = v; break;
case 5: r = v, g = p, b = q; break;
}
return {r:Math.floor(r * 255), g:Math.floor(g * 255), b:Math.floor(b * 255) };
};
exports.HSVToHex = function(h, s, v) {
var rgb = exports.HSVToRGB(h, s, v);
return exports.RGBToHex(rgb.r, rgb.g, rgb.b);
};
exports.hexToHSV = function(hex) {
var rgb = exports.hexToRGB(hex);
return exports.RGBToHSV(rgb.r, rgb.g, rgb.b);
};
exports.isValidHex = function(hex) {
var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
return isOk;
};
exports.isValidRGB = function(rgb) {
rgb = rgb.replace(" ","");
var isOk = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/i.test(rgb);
return isOk;
}
/**
* This recursively redirects the prototype of JSON objects to the referenceObject
* This is used for default options.
*
* @param referenceObject
* @returns {*}
*/
exports.selectiveBridgeObject = function(fields, referenceObject) {
if (typeof referenceObject == "object") {
var objectTo = Object.create(referenceObject);
for (var i = 0; i < fields.length; i++) {
if (referenceObject.hasOwnProperty(fields[i])) {
if (typeof referenceObject[fields[i]] == "object") {
objectTo[fields[i]] = exports.bridgeObject(referenceObject[fields[i]]);
}
}
}
return objectTo;
}
else {
return null;
}
};
/**
* This recursively redirects the prototype of JSON objects to the referenceObject
* This is used for default options.
*
* @param referenceObject
* @returns {*}
*/
exports.bridgeObject = function(referenceObject) {
if (typeof referenceObject == "object") {
var objectTo = Object.create(referenceObject);
for (var i in referenceObject) {
if (referenceObject.hasOwnProperty(i)) {
if (typeof referenceObject[i] == "object") {
objectTo[i] = exports.bridgeObject(referenceObject[i]);
}
}
}
return objectTo;
}
else {
return null;
}
};
/**
* this is used to set the options of subobjects in the options object. A requirement of these subobjects
* is that they have an 'enabled' element which is optional for the user but mandatory for the program.
*
* @param [object] mergeTarget | this is either this.options or the options used for the groups.
* @param [object] options | options
* @param [String] option | this is the option key in the options argument
* @private
*/
exports.mergeOptions = function (mergeTarget, options, option) {
if (options[option] !== undefined) {
if (typeof options[option] == 'boolean') {
mergeTarget[option].enabled = options[option];
}
else {
mergeTarget[option].enabled = true;
for (var prop in options[option]) {
if (options[option].hasOwnProperty(prop)) {
mergeTarget[option][prop] = options[option][prop];
}
}
}
}
}
/**
* This function does a binary search for a visible item in a sorted list. If we find a visible item, the code that uses
* this function will then iterate in both directions over this sorted list to find all visible items.
*
* @param {Item[]} orderedItems | Items ordered by start
* @param {function} searchFunction | -1 is lower, 0 is found, 1 is higher
* @param {String} field
* @param {String} field2
* @returns {number}
* @private
*/
exports.binarySearchCustom = function(orderedItems, searchFunction, field, field2) {
var maxIterations = 10000;
var iteration = 0;
var low = 0;
var high = orderedItems.length - 1;
while (low <= high && iteration < maxIterations) {
var middle = Math.floor((low + high) / 2);
var item = orderedItems[middle];
var value = (field2 === undefined) ? item[field] : item[field][field2];
var searchResult = searchFunction(value);
if (searchResult == 0) { // jihaa, found a visible item!
return middle;
}
else if (searchResult == -1) { // it is too small --> increase low
low = middle + 1;
}
else { // it is too big --> decrease high
high = middle - 1;
}
iteration++;
}
return -1;
};
/**
* This function does a binary search for a specific value in a sorted array. If it does not exist but is in between of
* two values, we return either the one before or the one after, depending on user input
* If it is found, we return the index, else -1.
*
* @param {Array} orderedItems
* @param {{start: number, end: number}} target
* @param {String} field
* @param {String} sidePreference 'before' or 'after'
* @returns {number}
* @private
*/
exports.binarySearchValue = function(orderedItems, target, field, sidePreference) {
var maxIterations = 10000;
var iteration = 0;
var low = 0;
var high = orderedItems.length - 1;
var prevValue, value, nextValue, middle;
while (low <= high && iteration < maxIterations) {
// get a new guess
middle = Math.floor(0.5*(high+low));
prevValue = orderedItems[Math.max(0,middle - 1)][field];
value = orderedItems[middle][field];
nextValue = orderedItems[Math.min(orderedItems.length-1,middle + 1)][field];
if (value == target) { // we found the target
return middle;
}
else if (prevValue < target && value > target) { // target is in between of the previous and the current
return sidePreference == 'before' ? Math.max(0,middle - 1) : middle;
}
else if (value < target && nextValue > target) { // target is in between of the current and the next
return sidePreference == 'before' ? middle : Math.min(orderedItems.length-1,middle + 1);
}
else { // didnt find the target, we need to change our boundaries.
if (value < target) { // it is too small --> increase low
low = middle + 1;
}
else { // it is too big --> decrease high
high = middle - 1;
}
}
iteration++;
}
// didnt find anything. Return -1.
return -1;
};
/**
* Quadratic ease-in-out
* http://gizma.com/easing/
* @param {number} t Current time
* @param {number} start Start value
* @param {number} end End value
* @param {number} duration Duration
* @returns {number} Value corresponding with current time
*/
exports.easeInOutQuad = function (t, start, end, duration) {
var change = end - start;
t /= duration/2;
if (t < 1) return change/2*t*t + start;
t--;
return -change/2 * (t*(t-2) - 1) + start;
};
/*
* Easing Functions - inspired from http://gizma.com/easing/
* only considering the t value for the range [0, 1] => [0, 1]
* https://gist.github.com/gre/1650294
*/
exports.easingFunctions = {
// no easing, no acceleration
linear: function (t) {
return t
},
// accelerating from zero velocity
easeInQuad: function (t) {
return t * t
},
// decelerating to zero velocity
easeOutQuad: function (t) {
return t * (2 - t)
},
// acceleration until halfway, then deceleration
easeInOutQuad: function (t) {
return t < .5 ? 2 * t * t : -1 + (4 - 2 * t) * t
},
// accelerating from zero velocity
easeInCubic: function (t) {
return t * t * t
},
// decelerating to zero velocity
easeOutCubic: function (t) {
return (--t) * t * t + 1
},
// acceleration until halfway, then deceleration
easeInOutCubic: function (t) {
return t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1
},
// accelerating from zero velocity
easeInQuart: function (t) {
return t * t * t * t
},
// decelerating to zero velocity
easeOutQuart: function (t) {
return 1 - (--t) * t * t * t
},
// acceleration until halfway, then deceleration
easeInOutQuart: function (t) {
return t < .5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t
},
// accelerating from zero velocity
easeInQuint: function (t) {
return t * t * t * t * t
},
// decelerating to zero velocity
easeOutQuint: function (t) {
return 1 + (--t) * t * t * t * t
},
// acceleration until halfway, then deceleration
easeInOutQuint: function (t) {
return t < .5 ? 16 * t * t * t * t * t : 1 + 16 * (--t) * t * t * t * t
}
};
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
// DOM utility methods
/**
* this prepares the JSON container for allocating SVG elements
* @param JSONcontainer
* @private
*/
exports.prepareElements = function(JSONcontainer) {
// cleanup the redundant svgElements;
for (var elementType in JSONcontainer) {
if (JSONcontainer.hasOwnProperty(elementType)) {
JSONcontainer[elementType].redundant = JSONcontainer[elementType].used;
JSONcontainer[elementType].used = [];
}
}
};
/**
* this cleans up all the unused SVG elements. By asking for the parentNode, we only need to supply the JSON container from
* which to remove the redundant elements.
*
* @param JSONcontainer
* @private
*/
exports.cleanupElements = function(JSONcontainer) {
// cleanup the redundant svgElements;
for (var elementType in JSONcontainer) {
if (JSONcontainer.hasOwnProperty(elementType)) {
if (JSONcontainer[elementType].redundant) {
for (var i = 0; i < JSONcontainer[elementType].redundant.length; i++) {
JSONcontainer[elementType].redundant[i].parentNode.removeChild(JSONcontainer[elementType].redundant[i]);
}
JSONcontainer[elementType].redundant = [];
}
}
}
};
/**
* Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer
* the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this.
*
* @param elementType
* @param JSONcontainer
* @param svgContainer
* @returns {*}
* @private
*/
exports.getSVGElement = function (elementType, JSONcontainer, svgContainer) {
var element;
// allocate SVG element, if it doesnt yet exist, create one.
if (JSONcontainer.hasOwnProperty(elementType)) { // this element has been created before
// check if there is an redundant element
if (JSONcontainer[elementType].redundant.length > 0) {
element = JSONcontainer[elementType].redundant[0];
JSONcontainer[elementType].redundant.shift();
}
else {
// create a new element and add it to the SVG
element = document.createElementNS('http://www.w3.org/2000/svg', elementType);
svgContainer.appendChild(element);
}
}
else {
// create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it.
element = document.createElementNS('http://www.w3.org/2000/svg', elementType);
JSONcontainer[elementType] = {used: [], redundant: []};
svgContainer.appendChild(element);
}
JSONcontainer[elementType].used.push(element);
return element;
};
/**
* Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer
* the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this.
*
* @param elementType
* @param JSONcontainer
* @param DOMContainer
* @returns {*}
* @private
*/
exports.getDOMElement = function (elementType, JSONcontainer, DOMContainer, insertBefore) {
var element;
// allocate DOM element, if it doesnt yet exist, create one.
if (JSONcontainer.hasOwnProperty(elementType)) { // this element has been created before
// check if there is an redundant element
if (JSONcontainer[elementType].redundant.length > 0) {
element = JSONcontainer[elementType].redundant[0];
JSONcontainer[elementType].redundant.shift();
}
else {
// create a new element and add it to the SVG
element = document.createElement(elementType);
if (insertBefore !== undefined) {
DOMContainer.insertBefore(element, insertBefore);
}
else {
DOMContainer.appendChild(element);
}
}
}
else {
// create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it.
element = document.createElement(elementType);
JSONcontainer[elementType] = {used: [], redundant: []};
if (insertBefore !== undefined) {
DOMContainer.insertBefore(element, insertBefore);
}
else {
DOMContainer.appendChild(element);
}
}
JSONcontainer[elementType].used.push(element);
return element;
};
/**
* draw a point object. this is a seperate function because it can also be called by the legend.
* The reason the JSONcontainer and the target SVG svgContainer have to be supplied is so the legend can use these functions
* as well.
*
* @param x
* @param y
* @param group
* @param JSONcontainer
* @param svgContainer
* @param labelObj
* @returns {*}
*/
exports.drawPoint = function(x, y, group, JSONcontainer, svgContainer, labelObj) {
var point;
if (group.options.drawPoints.style == 'circle') {
point = exports.getSVGElement('circle',JSONcontainer,svgContainer);
point.setAttributeNS(null, "cx", x);
point.setAttributeNS(null, "cy", y);
point.setAttributeNS(null, "r", 0.5 * group.options.drawPoints.size);
}
else {
point = exports.getSVGElement('rect',JSONcontainer,svgContainer);
point.setAttributeNS(null, "x", x - 0.5*group.options.drawPoints.size);
point.setAttributeNS(null, "y", y - 0.5*group.options.drawPoints.size);
point.setAttributeNS(null, "width", group.options.drawPoints.size);
point.setAttributeNS(null, "height", group.options.drawPoints.size);
}
if(group.options.drawPoints.styles !== undefined) {
point.setAttributeNS(null, "style", group.group.options.drawPoints.styles);
}
point.setAttributeNS(null, "class", group.className + " point");
//handle label
var label = exports.getSVGElement('text',JSONcontainer,svgContainer);
if (labelObj){
if (labelObj.xOffset) {
x = x + labelObj.xOffset;
}
if (labelObj.yOffset) {
y = y + labelObj.yOffset;
}
if (labelObj.content) {
label.textContent = labelObj.content;
}
if (labelObj.className) {
label.setAttributeNS(null, "class", labelObj.className + " label");
}
}
label.setAttributeNS(null, "x", x);
label.setAttributeNS(null, "y", y);
return point;
};
/**
* draw a bar SVG element centered on the X coordinate
*
* @param x
* @param y
* @param className
*/
exports.drawBar = function (x, y, width, height, className, JSONcontainer, svgContainer) {
if (height != 0) {
if (height < 0) {
height *= -1;
y -= height;
}
var rect = exports.getSVGElement('rect',JSONcontainer, svgContainer);
rect.setAttributeNS(null, "x", x - 0.5 * width);
rect.setAttributeNS(null, "y", y);
rect.setAttributeNS(null, "width", width);
rect.setAttributeNS(null, "height", height);
rect.setAttributeNS(null, "class", className);
}
};
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
var util = __webpack_require__(1);
var Queue = __webpack_require__(5);
/**
* DataSet
*
* Usage:
* var dataSet = new DataSet({
* fieldId: '_id',
* type: {
* // ...
* }
* });
*
* dataSet.add(item);
* dataSet.add(data);
* dataSet.update(item);
* dataSet.update(data);
* dataSet.remove(id);
* dataSet.remove(ids);
* var data = dataSet.get();
* var data = dataSet.get(id);
* var data = dataSet.get(ids);
* var data = dataSet.get(ids, options, data);
* dataSet.clear();
*
* A data set can:
* - add/remove/update data
* - gives triggers upon changes in the data
* - can import/export data in various data formats
*
* @param {Array | DataTable} [data] Optional array with initial data
* @param {Object} [options] Available options:
* {String} fieldId Field name of the id in the
* items, 'id' by default.
* {Object.} [type]
* {String[]} [fields] field names to be returned
* {function} [filter] filter items
* {String | function} [order] Order the items by
* a field name or custom sort function.
* {Array | DataTable} [data] If provided, items will be appended to this
* array or table. Required in case of Google
* DataTable.
*
* @throws Error
*/
DataSet.prototype.get = function (args) {
var me = this;
// parse the arguments
var id, ids, options, data;
var firstType = util.getType(arguments[0]);
if (firstType == 'String' || firstType == 'Number') {
// get(id [, options] [, data])
id = arguments[0];
options = arguments[1];
data = arguments[2];
}
else if (firstType == 'Array') {
// get(ids [, options] [, data])
ids = arguments[0];
options = arguments[1];
data = arguments[2];
}
else {
// get([, options] [, data])
options = arguments[0];
data = arguments[1];
}
// determine the return type
var returnType;
if (options && options.returnType) {
var allowedValues = ["DataTable", "Array", "Object"];
returnType = allowedValues.indexOf(options.returnType) == -1 ? "Array" : options.returnType;
if (data && (returnType != util.getType(data))) {
throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
'does not correspond with specified options.type (' + options.type + ')');
}
if (returnType == 'DataTable' && !util.isDataTable(data)) {
throw new Error('Parameter "data" must be a DataTable ' +
'when options.type is "DataTable"');
}
}
else if (data) {
returnType = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
}
else {
returnType = 'Array';
}
// build options
var type = options && options.type || this._options.type;
var filter = options && options.filter;
var items = [], item, itemId, i, len;
// convert items
if (id != undefined) {
// return a single item
item = me._getItem(id, type);
if (filter && !filter(item)) {
item = null;
}
}
else if (ids != undefined) {
// return a subset of items
for (i = 0, len = ids.length; i < len; i++) {
item = me._getItem(ids[i], type);
if (!filter || filter(item)) {
items.push(item);
}
}
}
else {
// return all items
for (itemId in this._data) {
if (this._data.hasOwnProperty(itemId)) {
item = me._getItem(itemId, type);
if (!filter || filter(item)) {
items.push(item);
}
}
}
}
// order the results
if (options && options.order && id == undefined) {
this._sort(items, options.order);
}
// filter fields of the items
if (options && options.fields) {
var fields = options.fields;
if (id != undefined) {
item = this._filterFields(item, fields);
}
else {
for (i = 0, len = items.length; i < len; i++) {
items[i] = this._filterFields(items[i], fields);
}
}
}
// return the results
if (returnType == 'DataTable') {
var columns = this._getColumnNames(data);
if (id != undefined) {
// append a single item to the data table
me._appendRow(data, columns, item);
}
else {
// copy the items to the provided data table
for (i = 0; i < items.length; i++) {
me._appendRow(data, columns, items[i]);
}
}
return data;
}
else if (returnType == "Object") {
var result = {};
for (i = 0; i < items.length; i++) {
result[items[i].id] = items[i];
}
return result;
}
else {
// return an array
if (id != undefined) {
// a single item
return item;
}
else {
// multiple items
if (data) {
// copy the items to the provided array
for (i = 0, len = items.length; i < len; i++) {
data.push(items[i]);
}
return data;
}
else {
// just return our array
return items;
}
}
}
};
/**
* Get ids of all items or from a filtered set of items.
* @param {Object} [options] An Object with options. Available options:
* {function} [filter] filter items
* {String | function} [order] Order the items by
* a field name or custom sort function.
* @return {Array} ids
*/
DataSet.prototype.getIds = function (options) {
var data = this._data,
filter = options && options.filter,
order = options && options.order,
type = options && options.type || this._options.type,
i,
len,
id,
item,
items,
ids = [];
if (filter) {
// get filtered items
if (order) {
// create ordered list
items = [];
for (id in data) {
if (data.hasOwnProperty(id)) {
item = this._getItem(id, type);
if (filter(item)) {
items.push(item);
}
}
}
this._sort(items, order);
for (i = 0, len = items.length; i < len; i++) {
ids[i] = items[i][this._fieldId];
}
}
else {
// create unordered list
for (id in data) {
if (data.hasOwnProperty(id)) {
item = this._getItem(id, type);
if (filter(item)) {
ids.push(item[this._fieldId]);
}
}
}
}
}
else {
// get all items
if (order) {
// create an ordered list
items = [];
for (id in data) {
if (data.hasOwnProperty(id)) {
items.push(data[id]);
}
}
this._sort(items, order);
for (i = 0, len = items.length; i < len; i++) {
ids[i] = items[i][this._fieldId];
}
}
else {
// create unordered list
for (id in data) {
if (data.hasOwnProperty(id)) {
item = data[id];
ids.push(item[this._fieldId]);
}
}
}
}
return ids;
};
/**
* Returns the DataSet itself. Is overwritten for example by the DataView,
* which returns the DataSet it is connected to instead.
*/
DataSet.prototype.getDataSet = function () {
return this;
};
/**
* Execute a callback function for every item in the dataset.
* @param {function} callback
* @param {Object} [options] Available options:
* {Object.} [type]
* {String[]} [fields] filter fields
* {function} [filter] filter items
* {String | function} [order] Order the items by
* a field name or custom sort function.
*/
DataSet.prototype.forEach = function (callback, options) {
var filter = options && options.filter,
type = options && options.type || this._options.type,
data = this._data,
item,
id;
if (options && options.order) {
// execute forEach on ordered list
var items = this.get(options);
for (var i = 0, len = items.length; i < len; i++) {
item = items[i];
id = item[this._fieldId];
callback(item, id);
}
}
else {
// unordered
for (id in data) {
if (data.hasOwnProperty(id)) {
item = this._getItem(id, type);
if (!filter || filter(item)) {
callback(item, id);
}
}
}
}
};
/**
* Map every item in the dataset.
* @param {function} callback
* @param {Object} [options] Available options:
* {Object.} [type]
* {String[]} [fields] filter fields
* {function} [filter] filter items
* {String | function} [order] Order the items by
* a field name or custom sort function.
* @return {Object[]} mappedItems
*/
DataSet.prototype.map = function (callback, options) {
var filter = options && options.filter,
type = options && options.type || this._options.type,
mappedItems = [],
data = this._data,
item;
// convert and filter items
for (var id in data) {
if (data.hasOwnProperty(id)) {
item = this._getItem(id, type);
if (!filter || filter(item)) {
mappedItems.push(callback(item, id));
}
}
}
// order items
if (options && options.order) {
this._sort(mappedItems, options.order);
}
return mappedItems;
};
/**
* Filter the fields of an item
* @param {Object | null} item
* @param {String[]} fields Field names
* @return {Object | null} filteredItem or null if no item is provided
* @private
*/
DataSet.prototype._filterFields = function (item, fields) {
if (!item) { // item is null
return item;
}
var filteredItem = {};
if(Array.isArray(fields)){
for (var field in item) {
if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
filteredItem[field] = item[field];
}
}
}else{
for (var field in item) {
if (item.hasOwnProperty(field) && fields.hasOwnProperty(field)) {
filteredItem[fields[field]] = item[field];
}
}
}
return filteredItem;
};
/**
* Sort the provided array with items
* @param {Object[]} items
* @param {String | function} order A field name or custom sort function.
* @private
*/
DataSet.prototype._sort = function (items, order) {
if (util.isString(order)) {
// order by provided field name
var name = order; // field name
items.sort(function (a, b) {
var av = a[name];
var bv = b[name];
return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
});
}
else if (typeof order === 'function') {
// order by sort function
items.sort(order);
}
// TODO: extend order by an Object {field:String, direction:String}
// where direction can be 'asc' or 'desc'
else {
throw new TypeError('Order must be a function or a string');
}
};
/**
* Remove an object by pointer or by id
* @param {String | Number | Object | Array} id Object or id, or an array with
* objects or ids to be removed
* @param {String} [senderId] Optional sender id
* @return {Array} removedIds
*/
DataSet.prototype.remove = function (id, senderId) {
var removedIds = [],
i, len, removedId;
if (Array.isArray(id)) {
for (i = 0, len = id.length; i < len; i++) {
removedId = this._remove(id[i]);
if (removedId != null) {
removedIds.push(removedId);
}
}
}
else {
removedId = this._remove(id);
if (removedId != null) {
removedIds.push(removedId);
}
}
if (removedIds.length) {
this._trigger('remove', {items: removedIds}, senderId);
}
return removedIds;
};
/**
* Remove an item by its id
* @param {Number | String | Object} id id or item
* @returns {Number | String | null} id
* @private
*/
DataSet.prototype._remove = function (id) {
if (util.isNumber(id) || util.isString(id)) {
if (this._data[id]) {
delete this._data[id];
this.length--;
return id;
}
}
else if (id instanceof Object) {
var itemId = id[this._fieldId];
if (itemId && this._data[itemId]) {
delete this._data[itemId];
this.length--;
return itemId;
}
}
return null;
};
/**
* Clear the data
* @param {String} [senderId] Optional sender id
* @return {Array} removedIds The ids of all removed items
*/
DataSet.prototype.clear = function (senderId) {
var ids = Object.keys(this._data);
this._data = {};
this.length = 0;
this._trigger('remove', {items: ids}, senderId);
return ids;
};
/**
* Find the item with maximum value of a specified field
* @param {String} field
* @return {Object | null} item Item containing max value, or null if no items
*/
DataSet.prototype.max = function (field) {
var data = this._data,
max = null,
maxField = null;
for (var id in data) {
if (data.hasOwnProperty(id)) {
var item = data[id];
var itemField = item[field];
if (itemField != null && (!max || itemField > maxField)) {
max = item;
maxField = itemField;
}
}
}
return max;
};
/**
* Find the item with minimum value of a specified field
* @param {String} field
* @return {Object | null} item Item containing max value, or null if no items
*/
DataSet.prototype.min = function (field) {
var data = this._data,
min = null,
minField = null;
for (var id in data) {
if (data.hasOwnProperty(id)) {
var item = data[id];
var itemField = item[field];
if (itemField != null && (!min || itemField < minField)) {
min = item;
minField = itemField;
}
}
}
return min;
};
/**
* Find all distinct values of a specified field
* @param {String} field
* @return {Array} values Array containing all distinct values. If data items
* do not contain the specified field are ignored.
* The returned array is unordered.
*/
DataSet.prototype.distinct = function (field) {
var data = this._data;
var values = [];
var fieldType = this._options.type && this._options.type[field] || null;
var count = 0;
var i;
for (var prop in data) {
if (data.hasOwnProperty(prop)) {
var item = data[prop];
var value = item[field];
var exists = false;
for (i = 0; i < count; i++) {
if (values[i] == value) {
exists = true;
break;
}
}
if (!exists && (value !== undefined)) {
values[count] = value;
count++;
}
}
}
if (fieldType) {
for (i = 0; i < values.length; i++) {
values[i] = util.convert(values[i], fieldType);
}
}
return values;
};
/**
* Add a single item. Will fail when an item with the same id already exists.
* @param {Object} item
* @return {String} id
* @private
*/
DataSet.prototype._addItem = function (item) {
var id = item[this._fieldId];
if (id != undefined) {
// check whether this id is already taken
if (this._data[id]) {
// item already exists
throw new Error('Cannot add item: item with id ' + id + ' already exists');
}
}
else {
// generate an id
id = util.randomUUID();
item[this._fieldId] = id;
}
var d = {};
for (var field in item) {
if (item.hasOwnProperty(field)) {
var fieldType = this._type[field]; // type may be undefined
d[field] = util.convert(item[field], fieldType);
}
}
this._data[id] = d;
this.length++;
return id;
};
/**
* Get an item. Fields can be converted to a specific type
* @param {String} id
* @param {Object.} [types] field types to convert
* @return {Object | null} item
* @private
*/
DataSet.prototype._getItem = function (id, types) {
var field, value;
// get the item from the dataset
var raw = this._data[id];
if (!raw) {
return null;
}
// convert the items field types
var converted = {};
if (types) {
for (field in raw) {
if (raw.hasOwnProperty(field)) {
value = raw[field];
converted[field] = util.convert(value, types[field]);
}
}
}
else {
// no field types specified, no converting needed
for (field in raw) {
if (raw.hasOwnProperty(field)) {
value = raw[field];
converted[field] = value;
}
}
}
return converted;
};
/**
* Update a single item: merge with existing item.
* Will fail when the item has no id, or when there does not exist an item
* with the same id.
* @param {Object} item
* @return {String} id
* @private
*/
DataSet.prototype._updateItem = function (item) {
var id = item[this._fieldId];
if (id == undefined) {
throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
}
var d = this._data[id];
if (!d) {
// item doesn't exist
throw new Error('Cannot update item: no item with id ' + id + ' found');
}
// merge with current item
for (var field in item) {
if (item.hasOwnProperty(field)) {
var fieldType = this._type[field]; // type may be undefined
d[field] = util.convert(item[field], fieldType);
}
}
return id;
};
/**
* Get an array with the column names of a Google DataTable
* @param {DataTable} dataTable
* @return {String[]} columnNames
* @private
*/
DataSet.prototype._getColumnNames = function (dataTable) {
var columns = [];
for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
}
return columns;
};
/**
* Append an item as a row to the dataTable
* @param dataTable
* @param columns
* @param item
* @private
*/
DataSet.prototype._appendRow = function (dataTable, columns, item) {
var row = dataTable.addRow();
for (var col = 0, cols = columns.length; col < cols; col++) {
var field = columns[col];
dataTable.setValue(row, col, item[field]);
}
};
module.exports = DataSet;
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
var util = __webpack_require__(1);
var DataSet = __webpack_require__(3);
/**
* DataView
*
* a dataview offers a filtered view on a dataset or an other dataview.
*
* @param {DataSet | DataView} data
* @param {Object} [options] Available options: see method get
*
* @constructor DataView
*/
function DataView (data, options) {
this._data = null;
this._ids = {}; // ids of the items currently in memory (just contains a boolean true)
this.length = 0; // number of items in the DataView
this._options = options || {};
this._fieldId = 'id'; // name of the field containing id
this._subscribers = {}; // event subscribers
var me = this;
this.listener = function () {
me._onEvent.apply(me, arguments);
};
this.setData(data);
}
// TODO: implement a function .config() to dynamically update things like configured filter
// and trigger changes accordingly
/**
* Set a data source for the view
* @param {DataSet | DataView} data
*/
DataView.prototype.setData = function (data) {
var ids, i, len;
if (this._data) {
// unsubscribe from current dataset
if (this._data.unsubscribe) {
this._data.unsubscribe('*', this.listener);
}
// trigger a remove of all items in memory
ids = [];
for (var id in this._ids) {
if (this._ids.hasOwnProperty(id)) {
ids.push(id);
}
}
this._ids = {};
this.length = 0;
this._trigger('remove', {items: ids});
}
this._data = data;
if (this._data) {
// update fieldId
this._fieldId = this._options.fieldId ||
(this._data && this._data.options && this._data.options.fieldId) ||
'id';
// trigger an add of all added items
ids = this._data.getIds({filter: this._options && this._options.filter});
for (i = 0, len = ids.length; i < len; i++) {
id = ids[i];
this._ids[id] = true;
}
this.length = ids.length;
this._trigger('add', {items: ids});
// subscribe to new dataset
if (this._data.on) {
this._data.on('*', this.listener);
}
}
};
/**
* Refresh the DataView. Useful when the DataView has a filter function
* containing a variable parameter.
*/
DataView.prototype.refresh = function () {
var id;
var ids = this._data.getIds({filter: this._options && this._options.filter});
var newIds = {};
var added = [];
var removed = [];
// check for additions
for (var i = 0; i < ids.length; i++) {
id = ids[i];
newIds[id] = true;
if (!this._ids[id]) {
added.push(id);
this._ids[id] = true;
this.length++;
}
}
// check for removals
for (id in this._ids) {
if (this._ids.hasOwnProperty(id)) {
if (!newIds[id]) {
removed.push(id);
delete this._ids[id];
this.length--;
}
}
}
// trigger events
if (added.length) {
this._trigger('add', {items: added});
}
if (removed.length) {
this._trigger('remove', {items: removed});
}
};
/**
* Get data from the data view
*
* Usage:
*
* get()
* get(options: Object)
* get(options: Object, data: Array | DataTable)
*
* get(id: Number)
* get(id: Number, options: Object)
* get(id: Number, options: Object, data: Array | DataTable)
*
* get(ids: Number[])
* get(ids: Number[], options: Object)
* get(ids: Number[], options: Object, data: Array | DataTable)
*
* Where:
*
* {Number | String} id The id of an item
* {Number[] | String{}} ids An array with ids of items
* {Object} options An Object with options. Available options:
* {String} [type] Type of data to be returned. Can
* be 'DataTable' or 'Array' (default)
* {Object.} [convert]
* {String[]} [fields] field names to be returned
* {function} [filter] filter items
* {String | function} [order] Order the items by
* a field name or custom sort function.
* {Array | DataTable} [data] If provided, items will be appended to this
* array or table. Required in case of Google
* DataTable.
* @param args
*/
DataView.prototype.get = function (args) {
var me = this;
// parse the arguments
var ids, options, data;
var firstType = util.getType(arguments[0]);
if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
// get(id(s) [, options] [, data])
ids = arguments[0]; // can be a single id or an array with ids
options = arguments[1];
data = arguments[2];
}
else {
// get([, options] [, data])
options = arguments[0];
data = arguments[1];
}
// extend the options with the default options and provided options
var viewOptions = util.extend({}, this._options, options);
// create a combined filter method when needed
if (this._options.filter && options && options.filter) {
viewOptions.filter = function (item) {
return me._options.filter(item) && options.filter(item);
}
}
// build up the call to the linked data set
var getArguments = [];
if (ids != undefined) {
getArguments.push(ids);
}
getArguments.push(viewOptions);
getArguments.push(data);
return this._data && this._data.get.apply(this._data, getArguments);
};
/**
* Get ids of all items or from a filtered set of items.
* @param {Object} [options] An Object with options. Available options:
* {function} [filter] filter items
* {String | function} [order] Order the items by
* a field name or custom sort function.
* @return {Array} ids
*/
DataView.prototype.getIds = function (options) {
var ids;
if (this._data) {
var defaultFilter = this._options.filter;
var filter;
if (options && options.filter) {
if (defaultFilter) {
filter = function (item) {
return defaultFilter(item) && options.filter(item);
}
}
else {
filter = options.filter;
}
}
else {
filter = defaultFilter;
}
ids = this._data.getIds({
filter: filter,
order: options && options.order
});
}
else {
ids = [];
}
return ids;
};
/**
* Get the DataSet to which this DataView is connected. In case there is a chain
* of multiple DataViews, the root DataSet of this chain is returned.
* @return {DataSet} dataSet
*/
DataView.prototype.getDataSet = function () {
var dataSet = this;
while (dataSet instanceof DataView) {
dataSet = dataSet._data;
}
return dataSet || null;
};
/**
* Event listener. Will propagate all events from the connected data set to
* the subscribers of the DataView, but will filter the items and only trigger
* when there are changes in the filtered data set.
* @param {String} event
* @param {Object | null} params
* @param {String} senderId
* @private
*/
DataView.prototype._onEvent = function (event, params, senderId) {
var i, len, id, item;
var ids = params && params.items;
var data = this._data;
var updatedData = [];
var added = [];
var updated = [];
var removed = [];
if (ids && data) {
switch (event) {
case 'add':
// filter the ids of the added items
for (i = 0, len = ids.length; i < len; i++) {
id = ids[i];
item = this.get(id);
if (item) {
this._ids[id] = true;
added.push(id);
}
}
break;
case 'update':
// determine the event from the views viewpoint: an updated
// item can be added, updated, or removed from this view.
for (i = 0, len = ids.length; i < len; i++) {
id = ids[i];
item = this.get(id);
if (item) {
if (this._ids[id]) {
updated.push(id);
updatedData.push(params.data[i]);
}
else {
this._ids[id] = true;
added.push(id);
}
}
else {
if (this._ids[id]) {
delete this._ids[id];
removed.push(id);
}
else {
// nothing interesting for me :-(
}
}
}
break;
case 'remove':
// filter the ids of the removed items
for (i = 0, len = ids.length; i < len; i++) {
id = ids[i];
if (this._ids[id]) {
delete this._ids[id];
removed.push(id);
}
}
break;
}
this.length += added.length - removed.length;
if (added.length) {
this._trigger('add', {items: added}, senderId);
}
if (updated.length) {
this._trigger('update', {items: updated, data: updatedData}, senderId);
}
if (removed.length) {
this._trigger('remove', {items: removed}, senderId);
}
}
};
// copy subscription functionality from DataSet
DataView.prototype.on = DataSet.prototype.on;
DataView.prototype.off = DataSet.prototype.off;
DataView.prototype._trigger = DataSet.prototype._trigger;
// TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
DataView.prototype.subscribe = DataView.prototype.on;
DataView.prototype.unsubscribe = DataView.prototype.off;
module.exports = DataView;
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
/**
* A queue
* @param {Object} options
* Available options:
* - delay: number When provided, the queue will be flushed
* automatically after an inactivity of this delay
* in milliseconds.
* Default value is null.
* - max: number When the queue exceeds the given maximum number
* of entries, the queue is flushed automatically.
* Default value of max is Infinity.
* @constructor
*/
function Queue(options) {
// options
this.delay = null;
this.max = Infinity;
// properties
this._queue = [];
this._timeout = null;
this._extended = null;
this.setOptions(options);
}
/**
* Update the configuration of the queue
* @param {Object} options
* Available options:
* - delay: number When provided, the queue will be flushed
* automatically after an inactivity of this delay
* in milliseconds.
* Default value is null.
* - max: number When the queue exceeds the given maximum number
* of entries, the queue is flushed automatically.
* Default value of max is Infinity.
* @param options
*/
Queue.prototype.setOptions = function (options) {
if (options && typeof options.delay !== 'undefined') {
this.delay = options.delay;
}
if (options && typeof options.max !== 'undefined') {
this.max = options.max;
}
this._flushIfNeeded();
};
/**
* Extend an object with queuing functionality.
* The object will be extended with a function flush, and the methods provided
* in options.replace will be replaced with queued ones.
* @param {Object} object
* @param {Object} options
* Available options:
* - replace: Array.
* A list with method names of the methods
* on the object to be replaced with queued ones.
* - delay: number When provided, the queue will be flushed
* automatically after an inactivity of this delay
* in milliseconds.
* Default value is null.
* - max: number When the queue exceeds the given maximum number
* of entries, the queue is flushed automatically.
* Default value of max is Infinity.
* @return {Queue} Returns the created queue
*/
Queue.extend = function (object, options) {
var queue = new Queue(options);
if (object.flush !== undefined) {
throw new Error('Target object already has a property flush');
}
object.flush = function () {
queue.flush();
};
var methods = [{
name: 'flush',
original: undefined
}];
if (options && options.replace) {
for (var i = 0; i < options.replace.length; i++) {
var name = options.replace[i];
methods.push({
name: name,
original: object[name]
});
queue.replace(object, name);
}
}
queue._extended = {
object: object,
methods: methods
};
return queue;
};
/**
* Destroy the queue. The queue will first flush all queued actions, and in
* case it has extended an object, will restore the original object.
*/
Queue.prototype.destroy = function () {
this.flush();
if (this._extended) {
var object = this._extended.object;
var methods = this._extended.methods;
for (var i = 0; i < methods.length; i++) {
var method = methods[i];
if (method.original) {
object[method.name] = method.original;
}
else {
delete object[method.name];
}
}
this._extended = null;
}
};
/**
* Replace a method on an object with a queued version
* @param {Object} object Object having the method
* @param {string} method The method name
*/
Queue.prototype.replace = function(object, method) {
var me = this;
var original = object[method];
if (!original) {
throw new Error('Method ' + method + ' undefined');
}
object[method] = function () {
// create an Array with the arguments
var args = [];
for (var i = 0; i < arguments.length; i++) {
args[i] = arguments[i];
}
// add this call to the queue
me.queue({
args: args,
fn: original,
context: this
});
};
};
/**
* Queue a call
* @param {function | {fn: function, args: Array} | {fn: function, args: Array, context: Object}} entry
*/
Queue.prototype.queue = function(entry) {
if (typeof entry === 'function') {
this._queue.push({fn: entry});
}
else {
this._queue.push(entry);
}
this._flushIfNeeded();
};
/**
* Check whether the queue needs to be flushed
* @private
*/
Queue.prototype._flushIfNeeded = function () {
// flush when the maximum is exceeded.
if (this._queue.length > this.max) {
this.flush();
}
// flush after a period of inactivity when a delay is configured
clearTimeout(this._timeout);
if (this.queue.length > 0 && typeof this.delay === 'number') {
var me = this;
this._timeout = setTimeout(function () {
me.flush();
}, this.delay);
}
};
/**
* Flush all queued calls
*/
Queue.prototype.flush = function () {
while (this._queue.length > 0) {
var entry = this._queue.shift();
entry.fn.apply(entry.context || entry.fn, entry.args || []);
}
};
module.exports = Queue;
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
var Emitter = __webpack_require__(56);
var DataSet = __webpack_require__(3);
var DataView = __webpack_require__(4);
var util = __webpack_require__(1);
var Point3d = __webpack_require__(10);
var Point2d = __webpack_require__(9);
var Camera = __webpack_require__(7);
var Filter = __webpack_require__(8);
var Slider = __webpack_require__(11);
var StepNumber = __webpack_require__(12);
/**
* @constructor Graph3d
* Graph3d displays data in 3d.
*
* Graph3d is developed in javascript as a Google Visualization Chart.
*
* @param {Element} container The DOM element in which the Graph3d will
* be created. Normally a div element.
* @param {DataSet | DataView | Array} [data]
* @param {Object} [options]
*/
function Graph3d(container, data, options) {
if (!(this instanceof Graph3d)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
// create variables and set default values
this.containerElement = container;
this.width = '400px';
this.height = '400px';
this.margin = 10; // px
this.defaultXCenter = '55%';
this.defaultYCenter = '50%';
this.xLabel = 'x';
this.yLabel = 'y';
this.zLabel = 'z';
var passValueFn = function(v) { return v; };
this.xValueLabel = passValueFn;
this.yValueLabel = passValueFn;
this.zValueLabel = passValueFn;
this.filterLabel = 'time';
this.legendLabel = 'value';
this.style = Graph3d.STYLE.DOT;
this.showPerspective = true;
this.showGrid = true;
this.keepAspectRatio = true;
this.showShadow = false;
this.showGrayBottom = false; // TODO: this does not work correctly
this.showTooltip = false;
this.verticalRatio = 0.5; // 0.1 to 1.0, where 1.0 results in a 'cube'
this.animationInterval = 1000; // milliseconds
this.animationPreload = false;
this.camera = new Camera();
this.eye = new Point3d(0, 0, -1); // TODO: set eye.z about 3/4 of the width of the window?
this.dataTable = null; // The original data table
this.dataPoints = null; // The table with point objects
// the column indexes
this.colX = undefined;
this.colY = undefined;
this.colZ = undefined;
this.colValue = undefined;
this.colFilter = undefined;
this.xMin = 0;
this.xStep = undefined; // auto by default
this.xMax = 1;
this.yMin = 0;
this.yStep = undefined; // auto by default
this.yMax = 1;
this.zMin = 0;
this.zStep = undefined; // auto by default
this.zMax = 1;
this.valueMin = 0;
this.valueMax = 1;
this.xBarWidth = 1;
this.yBarWidth = 1;
// TODO: customize axis range
// constants
this.colorAxis = '#4D4D4D';
this.colorGrid = '#D3D3D3';
this.colorDot = '#7DC1FF';
this.colorDotBorder = '#3267D2';
// create a frame and canvas
this.create();
// apply options (also when undefined)
this.setOptions(options);
// apply data
if (data) {
this.setData(data);
}
}
// Extend Graph3d with an Emitter mixin
Emitter(Graph3d.prototype);
/**
* Calculate the scaling values, dependent on the range in x, y, and z direction
*/
Graph3d.prototype._setScale = function() {
this.scale = new Point3d(1 / (this.xMax - this.xMin),
1 / (this.yMax - this.yMin),
1 / (this.zMax - this.zMin));
// keep aspect ration between x and y scale if desired
if (this.keepAspectRatio) {
if (this.scale.x < this.scale.y) {
//noinspection JSSuspiciousNameCombination
this.scale.y = this.scale.x;
}
else {
//noinspection JSSuspiciousNameCombination
this.scale.x = this.scale.y;
}
}
// scale the vertical axis
this.scale.z *= this.verticalRatio;
// TODO: can this be automated? verticalRatio?
// determine scale for (optional) value
this.scale.value = 1 / (this.valueMax - this.valueMin);
// position the camera arm
var xCenter = (this.xMax + this.xMin) / 2 * this.scale.x;
var yCenter = (this.yMax + this.yMin) / 2 * this.scale.y;
var zCenter = (this.zMax + this.zMin) / 2 * this.scale.z;
this.camera.setArmLocation(xCenter, yCenter, zCenter);
};
/**
* Convert a 3D location to a 2D location on screen
* http://en.wikipedia.org/wiki/3D_projection
* @param {Point3d} point3d A 3D point with parameters x, y, z
* @return {Point2d} point2d A 2D point with parameters x, y
*/
Graph3d.prototype._convert3Dto2D = function(point3d) {
var translation = this._convertPointToTranslation(point3d);
return this._convertTranslationToScreen(translation);
};
/**
* Convert a 3D location its translation seen from the camera
* http://en.wikipedia.org/wiki/3D_projection
* @param {Point3d} point3d A 3D point with parameters x, y, z
* @return {Point3d} translation A 3D point with parameters x, y, z This is
* the translation of the point, seen from the
* camera
*/
Graph3d.prototype._convertPointToTranslation = function(point3d) {
var ax = point3d.x * this.scale.x,
ay = point3d.y * this.scale.y,
az = point3d.z * this.scale.z,
cx = this.camera.getCameraLocation().x,
cy = this.camera.getCameraLocation().y,
cz = this.camera.getCameraLocation().z,
// calculate angles
sinTx = Math.sin(this.camera.getCameraRotation().x),
cosTx = Math.cos(this.camera.getCameraRotation().x),
sinTy = Math.sin(this.camera.getCameraRotation().y),
cosTy = Math.cos(this.camera.getCameraRotation().y),
sinTz = Math.sin(this.camera.getCameraRotation().z),
cosTz = Math.cos(this.camera.getCameraRotation().z),
// calculate translation
dx = cosTy * (sinTz * (ay - cy) + cosTz * (ax - cx)) - sinTy * (az - cz),
dy = sinTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) + cosTx * (cosTz * (ay - cy) - sinTz * (ax-cx)),
dz = cosTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) - sinTx * (cosTz * (ay - cy) - sinTz * (ax-cx));
return new Point3d(dx, dy, dz);
};
/**
* Convert a translation point to a point on the screen
* @param {Point3d} translation A 3D point with parameters x, y, z This is
* the translation of the point, seen from the
* camera
* @return {Point2d} point2d A 2D point with parameters x, y
*/
Graph3d.prototype._convertTranslationToScreen = function(translation) {
var ex = this.eye.x,
ey = this.eye.y,
ez = this.eye.z,
dx = translation.x,
dy = translation.y,
dz = translation.z;
// calculate position on screen from translation
var bx;
var by;
if (this.showPerspective) {
bx = (dx - ex) * (ez / dz);
by = (dy - ey) * (ez / dz);
}
else {
bx = dx * -(ez / this.camera.getArmLength());
by = dy * -(ez / this.camera.getArmLength());
}
// shift and scale the point to the center of the screen
// use the width of the graph to scale both horizontally and vertically.
return new Point2d(
this.xcenter + bx * this.frame.canvas.clientWidth,
this.ycenter - by * this.frame.canvas.clientWidth);
};
/**
* Set the background styling for the graph
* @param {string | {fill: string, stroke: string, strokeWidth: string}} backgroundColor
*/
Graph3d.prototype._setBackgroundColor = function(backgroundColor) {
var fill = 'white';
var stroke = 'gray';
var strokeWidth = 1;
if (typeof(backgroundColor) === 'string') {
fill = backgroundColor;
stroke = 'none';
strokeWidth = 0;
}
else if (typeof(backgroundColor) === 'object') {
if (backgroundColor.fill !== undefined) fill = backgroundColor.fill;
if (backgroundColor.stroke !== undefined) stroke = backgroundColor.stroke;
if (backgroundColor.strokeWidth !== undefined) strokeWidth = backgroundColor.strokeWidth;
}
else if (backgroundColor === undefined) {
// use use defaults
}
else {
throw 'Unsupported type of backgroundColor';
}
this.frame.style.backgroundColor = fill;
this.frame.style.borderColor = stroke;
this.frame.style.borderWidth = strokeWidth + 'px';
this.frame.style.borderStyle = 'solid';
};
/// enumerate the available styles
Graph3d.STYLE = {
BAR: 0,
BARCOLOR: 1,
BARSIZE: 2,
DOT : 3,
DOTLINE : 4,
DOTCOLOR: 5,
DOTSIZE: 6,
GRID : 7,
LINE: 8,
SURFACE : 9
};
/**
* Retrieve the style index from given styleName
* @param {string} styleName Style name such as 'dot', 'grid', 'dot-line'
* @return {Number} styleNumber Enumeration value representing the style, or -1
* when not found
*/
Graph3d.prototype._getStyleNumber = function(styleName) {
switch (styleName) {
case 'dot': return Graph3d.STYLE.DOT;
case 'dot-line': return Graph3d.STYLE.DOTLINE;
case 'dot-color': return Graph3d.STYLE.DOTCOLOR;
case 'dot-size': return Graph3d.STYLE.DOTSIZE;
case 'line': return Graph3d.STYLE.LINE;
case 'grid': return Graph3d.STYLE.GRID;
case 'surface': return Graph3d.STYLE.SURFACE;
case 'bar': return Graph3d.STYLE.BAR;
case 'bar-color': return Graph3d.STYLE.BARCOLOR;
case 'bar-size': return Graph3d.STYLE.BARSIZE;
}
return -1;
};
/**
* Determine the indexes of the data columns, based on the given style and data
* @param {DataSet} data
* @param {Number} style
*/
Graph3d.prototype._determineColumnIndexes = function(data, style) {
if (this.style === Graph3d.STYLE.DOT ||
this.style === Graph3d.STYLE.DOTLINE ||
this.style === Graph3d.STYLE.LINE ||
this.style === Graph3d.STYLE.GRID ||
this.style === Graph3d.STYLE.SURFACE ||
this.style === Graph3d.STYLE.BAR) {
// 3 columns expected, and optionally a 4th with filter values
this.colX = 0;
this.colY = 1;
this.colZ = 2;
this.colValue = undefined;
if (data.getNumberOfColumns() > 3) {
this.colFilter = 3;
}
}
else if (this.style === Graph3d.STYLE.DOTCOLOR ||
this.style === Graph3d.STYLE.DOTSIZE ||
this.style === Graph3d.STYLE.BARCOLOR ||
this.style === Graph3d.STYLE.BARSIZE) {
// 4 columns expected, and optionally a 5th with filter values
this.colX = 0;
this.colY = 1;
this.colZ = 2;
this.colValue = 3;
if (data.getNumberOfColumns() > 4) {
this.colFilter = 4;
}
}
else {
throw 'Unknown style "' + this.style + '"';
}
};
Graph3d.prototype.getNumberOfRows = function(data) {
return data.length;
}
Graph3d.prototype.getNumberOfColumns = function(data) {
var counter = 0;
for (var column in data[0]) {
if (data[0].hasOwnProperty(column)) {
counter++;
}
}
return counter;
}
Graph3d.prototype.getDistinctValues = function(data, column) {
var distinctValues = [];
for (var i = 0; i < data.length; i++) {
if (distinctValues.indexOf(data[i][column]) == -1) {
distinctValues.push(data[i][column]);
}
}
return distinctValues;
}
Graph3d.prototype.getColumnRange = function(data,column) {
var minMax = {min:data[0][column],max:data[0][column]};
for (var i = 0; i < data.length; i++) {
if (minMax.min > data[i][column]) { minMax.min = data[i][column]; }
if (minMax.max < data[i][column]) { minMax.max = data[i][column]; }
}
return minMax;
};
/**
* Initialize the data from the data table. Calculate minimum and maximum values
* and column index values
* @param {Array | DataSet | DataView} rawData The data containing the items for the Graph.
* @param {Number} style Style Number
*/
Graph3d.prototype._dataInitialize = function (rawData, style) {
var me = this;
// unsubscribe from the dataTable
if (this.dataSet) {
this.dataSet.off('*', this._onChange);
}
if (rawData === undefined)
return;
if (Array.isArray(rawData)) {
rawData = new DataSet(rawData);
}
var data;
if (rawData instanceof DataSet || rawData instanceof DataView) {
data = rawData.get();
}
else {
throw new Error('Array, DataSet, or DataView expected');
}
if (data.length == 0)
return;
this.dataSet = rawData;
this.dataTable = data;
// subscribe to changes in the dataset
this._onChange = function () {
me.setData(me.dataSet);
};
this.dataSet.on('*', this._onChange);
// _determineColumnIndexes
// getNumberOfRows (points)
// getNumberOfColumns (x,y,z,v,t,t1,t2...)
// getDistinctValues (unique values?)
// getColumnRange
// determine the location of x,y,z,value,filter columns
this.colX = 'x';
this.colY = 'y';
this.colZ = 'z';
this.colValue = 'style';
this.colFilter = 'filter';
// check if a filter column is provided
if (data[0].hasOwnProperty('filter')) {
if (this.dataFilter === undefined) {
this.dataFilter = new Filter(rawData, this.colFilter, this);
this.dataFilter.setOnLoadCallback(function() {me.redraw();});
}
}
var withBars = this.style == Graph3d.STYLE.BAR ||
this.style == Graph3d.STYLE.BARCOLOR ||
this.style == Graph3d.STYLE.BARSIZE;
// determine barWidth from data
if (withBars) {
if (this.defaultXBarWidth !== undefined) {
this.xBarWidth = this.defaultXBarWidth;
}
else {
var dataX = this.getDistinctValues(data,this.colX);
this.xBarWidth = (dataX[1] - dataX[0]) || 1;
}
if (this.defaultYBarWidth !== undefined) {
this.yBarWidth = this.defaultYBarWidth;
}
else {
var dataY = this.getDistinctValues(data,this.colY);
this.yBarWidth = (dataY[1] - dataY[0]) || 1;
}
}
// calculate minimums and maximums
var xRange = this.getColumnRange(data,this.colX);
if (withBars) {
xRange.min -= this.xBarWidth / 2;
xRange.max += this.xBarWidth / 2;
}
this.xMin = (this.defaultXMin !== undefined) ? this.defaultXMin : xRange.min;
this.xMax = (this.defaultXMax !== undefined) ? this.defaultXMax : xRange.max;
if (this.xMax <= this.xMin) this.xMax = this.xMin + 1;
this.xStep = (this.defaultXStep !== undefined) ? this.defaultXStep : (this.xMax-this.xMin)/5;
var yRange = this.getColumnRange(data,this.colY);
if (withBars) {
yRange.min -= this.yBarWidth / 2;
yRange.max += this.yBarWidth / 2;
}
this.yMin = (this.defaultYMin !== undefined) ? this.defaultYMin : yRange.min;
this.yMax = (this.defaultYMax !== undefined) ? this.defaultYMax : yRange.max;
if (this.yMax <= this.yMin) this.yMax = this.yMin + 1;
this.yStep = (this.defaultYStep !== undefined) ? this.defaultYStep : (this.yMax-this.yMin)/5;
var zRange = this.getColumnRange(data,this.colZ);
this.zMin = (this.defaultZMin !== undefined) ? this.defaultZMin : zRange.min;
this.zMax = (this.defaultZMax !== undefined) ? this.defaultZMax : zRange.max;
if (this.zMax <= this.zMin) this.zMax = this.zMin + 1;
this.zStep = (this.defaultZStep !== undefined) ? this.defaultZStep : (this.zMax-this.zMin)/5;
if (this.colValue !== undefined) {
var valueRange = this.getColumnRange(data,this.colValue);
this.valueMin = (this.defaultValueMin !== undefined) ? this.defaultValueMin : valueRange.min;
this.valueMax = (this.defaultValueMax !== undefined) ? this.defaultValueMax : valueRange.max;
if (this.valueMax <= this.valueMin) this.valueMax = this.valueMin + 1;
}
// set the scale dependent on the ranges.
this._setScale();
};
/**
* Filter the data based on the current filter
* @param {Array} data
* @return {Array} dataPoints Array with point objects which can be drawn on screen
*/
Graph3d.prototype._getDataPoints = function (data) {
// TODO: store the created matrix dataPoints in the filters instead of reloading each time
var x, y, i, z, obj, point;
var dataPoints = [];
if (this.style === Graph3d.STYLE.GRID ||
this.style === Graph3d.STYLE.SURFACE) {
// copy all values from the google data table to a matrix
// the provided values are supposed to form a grid of (x,y) positions
// create two lists with all present x and y values
var dataX = [];
var dataY = [];
for (i = 0; i < this.getNumberOfRows(data); i++) {
x = data[i][this.colX] || 0;
y = data[i][this.colY] || 0;
if (dataX.indexOf(x) === -1) {
dataX.push(x);
}
if (dataY.indexOf(y) === -1) {
dataY.push(y);
}
}
var sortNumber = function (a, b) {
return a - b;
};
dataX.sort(sortNumber);
dataY.sort(sortNumber);
// create a grid, a 2d matrix, with all values.
var dataMatrix = []; // temporary data matrix
for (i = 0; i < data.length; i++) {
x = data[i][this.colX] || 0;
y = data[i][this.colY] || 0;
z = data[i][this.colZ] || 0;
var xIndex = dataX.indexOf(x); // TODO: implement Array().indexOf() for Internet Explorer
var yIndex = dataY.indexOf(y);
if (dataMatrix[xIndex] === undefined) {
dataMatrix[xIndex] = [];
}
var point3d = new Point3d();
point3d.x = x;
point3d.y = y;
point3d.z = z;
obj = {};
obj.point = point3d;
obj.trans = undefined;
obj.screen = undefined;
obj.bottom = new Point3d(x, y, this.zMin);
dataMatrix[xIndex][yIndex] = obj;
dataPoints.push(obj);
}
// fill in the pointers to the neighbors.
for (x = 0; x < dataMatrix.length; x++) {
for (y = 0; y < dataMatrix[x].length; y++) {
if (dataMatrix[x][y]) {
dataMatrix[x][y].pointRight = (x < dataMatrix.length-1) ? dataMatrix[x+1][y] : undefined;
dataMatrix[x][y].pointTop = (y < dataMatrix[x].length-1) ? dataMatrix[x][y+1] : undefined;
dataMatrix[x][y].pointCross =
(x < dataMatrix.length-1 && y < dataMatrix[x].length-1) ?
dataMatrix[x+1][y+1] :
undefined;
}
}
}
}
else { // 'dot', 'dot-line', etc.
// copy all values from the google data table to a list with Point3d objects
for (i = 0; i < data.length; i++) {
point = new Point3d();
point.x = data[i][this.colX] || 0;
point.y = data[i][this.colY] || 0;
point.z = data[i][this.colZ] || 0;
if (this.colValue !== undefined) {
point.value = data[i][this.colValue] || 0;
}
obj = {};
obj.point = point;
obj.bottom = new Point3d(point.x, point.y, this.zMin);
obj.trans = undefined;
obj.screen = undefined;
dataPoints.push(obj);
}
}
return dataPoints;
};
/**
* Create the main frame for the Graph3d.
* This function is executed once when a Graph3d object is created. The frame
* contains a canvas, and this canvas contains all objects like the axis and
* nodes.
*/
Graph3d.prototype.create = function () {
// remove all elements from the container element.
while (this.containerElement.hasChildNodes()) {
this.containerElement.removeChild(this.containerElement.firstChild);
}
this.frame = document.createElement('div');
this.frame.style.position = 'relative';
this.frame.style.overflow = 'hidden';
// create the graph canvas (HTML canvas element)
this.frame.canvas = document.createElement( 'canvas' );
this.frame.canvas.style.position = 'relative';
this.frame.appendChild(this.frame.canvas);
//if (!this.frame.canvas.getContext) {
{
var noCanvas = document.createElement( 'DIV' );
noCanvas.style.color = 'red';
noCanvas.style.fontWeight = 'bold' ;
noCanvas.style.padding = '10px';
noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
this.frame.canvas.appendChild(noCanvas);
}
this.frame.filter = document.createElement( 'div' );
this.frame.filter.style.position = 'absolute';
this.frame.filter.style.bottom = '0px';
this.frame.filter.style.left = '0px';
this.frame.filter.style.width = '100%';
this.frame.appendChild(this.frame.filter);
// add event listeners to handle moving and zooming the contents
var me = this;
var onmousedown = function (event) {me._onMouseDown(event);};
var ontouchstart = function (event) {me._onTouchStart(event);};
var onmousewheel = function (event) {me._onWheel(event);};
var ontooltip = function (event) {me._onTooltip(event);};
// TODO: these events are never cleaned up... can give a 'memory leakage'
util.addEventListener(this.frame.canvas, 'keydown', onkeydown);
util.addEventListener(this.frame.canvas, 'mousedown', onmousedown);
util.addEventListener(this.frame.canvas, 'touchstart', ontouchstart);
util.addEventListener(this.frame.canvas, 'mousewheel', onmousewheel);
util.addEventListener(this.frame.canvas, 'mousemove', ontooltip);
// add the new graph to the container element
this.containerElement.appendChild(this.frame);
};
/**
* Set a new size for the graph
* @param {string} width Width in pixels or percentage (for example '800px'
* or '50%')
* @param {string} height Height in pixels or percentage (for example '400px'
* or '30%')
*/
Graph3d.prototype.setSize = function(width, height) {
this.frame.style.width = width;
this.frame.style.height = height;
this._resizeCanvas();
};
/**
* Resize the canvas to the current size of the frame
*/
Graph3d.prototype._resizeCanvas = function() {
this.frame.canvas.style.width = '100%';
this.frame.canvas.style.height = '100%';
this.frame.canvas.width = this.frame.canvas.clientWidth;
this.frame.canvas.height = this.frame.canvas.clientHeight;
// adjust with for margin
this.frame.filter.style.width = (this.frame.canvas.clientWidth - 2 * 10) + 'px';
};
/**
* Start animation
*/
Graph3d.prototype.animationStart = function() {
if (!this.frame.filter || !this.frame.filter.slider)
throw 'No animation available';
this.frame.filter.slider.play();
};
/**
* Stop animation
*/
Graph3d.prototype.animationStop = function() {
if (!this.frame.filter || !this.frame.filter.slider) return;
this.frame.filter.slider.stop();
};
/**
* Resize the center position based on the current values in this.defaultXCenter
* and this.defaultYCenter (which are strings with a percentage or a value
* in pixels). The center positions are the variables this.xCenter
* and this.yCenter
*/
Graph3d.prototype._resizeCenter = function() {
// calculate the horizontal center position
if (this.defaultXCenter.charAt(this.defaultXCenter.length-1) === '%') {
this.xcenter =
parseFloat(this.defaultXCenter) / 100 *
this.frame.canvas.clientWidth;
}
else {
this.xcenter = parseFloat(this.defaultXCenter); // supposed to be in px
}
// calculate the vertical center position
if (this.defaultYCenter.charAt(this.defaultYCenter.length-1) === '%') {
this.ycenter =
parseFloat(this.defaultYCenter) / 100 *
(this.frame.canvas.clientHeight - this.frame.filter.clientHeight);
}
else {
this.ycenter = parseFloat(this.defaultYCenter); // supposed to be in px
}
};
/**
* Set the rotation and distance of the camera
* @param {Object} pos An object with the camera position. The object
* contains three parameters:
* - horizontal {Number}
* The horizontal rotation, between 0 and 2*PI.
* Optional, can be left undefined.
* - vertical {Number}
* The vertical rotation, between 0 and 0.5*PI
* if vertical=0.5*PI, the graph is shown from the
* top. Optional, can be left undefined.
* - distance {Number}
* The (normalized) distance of the camera to the
* center of the graph, a value between 0.71 and 5.0.
* Optional, can be left undefined.
*/
Graph3d.prototype.setCameraPosition = function(pos) {
if (pos === undefined) {
return;
}
if (pos.horizontal !== undefined && pos.vertical !== undefined) {
this.camera.setArmRotation(pos.horizontal, pos.vertical);
}
if (pos.distance !== undefined) {
this.camera.setArmLength(pos.distance);
}
this.redraw();
};
/**
* Retrieve the current camera rotation
* @return {object} An object with parameters horizontal, vertical, and
* distance
*/
Graph3d.prototype.getCameraPosition = function() {
var pos = this.camera.getArmRotation();
pos.distance = this.camera.getArmLength();
return pos;
};
/**
* Load data into the 3D Graph
*/
Graph3d.prototype._readData = function(data) {
// read the data
this._dataInitialize(data, this.style);
if (this.dataFilter) {
// apply filtering
this.dataPoints = this.dataFilter._getDataPoints();
}
else {
// no filtering. load all data
this.dataPoints = this._getDataPoints(this.dataTable);
}
// draw the filter
this._redrawFilter();
};
/**
* Replace the dataset of the Graph3d
* @param {Array | DataSet | DataView} data
*/
Graph3d.prototype.setData = function (data) {
this._readData(data);
this.redraw();
// start animation when option is true
if (this.animationAutoStart && this.dataFilter) {
this.animationStart();
}
};
/**
* Update the options. Options will be merged with current options
* @param {Object} options
*/
Graph3d.prototype.setOptions = function (options) {
var cameraPosition = undefined;
this.animationStop();
if (options !== undefined) {
// retrieve parameter values
if (options.width !== undefined) this.width = options.width;
if (options.height !== undefined) this.height = options.height;
if (options.xCenter !== undefined) this.defaultXCenter = options.xCenter;
if (options.yCenter !== undefined) this.defaultYCenter = options.yCenter;
if (options.filterLabel !== undefined) this.filterLabel = options.filterLabel;
if (options.legendLabel !== undefined) this.legendLabel = options.legendLabel;
if (options.xLabel !== undefined) this.xLabel = options.xLabel;
if (options.yLabel !== undefined) this.yLabel = options.yLabel;
if (options.zLabel !== undefined) this.zLabel = options.zLabel;
if (options.xValueLabel !== undefined) this.xValueLabel = options.xValueLabel;
if (options.yValueLabel !== undefined) this.yValueLabel = options.yValueLabel;
if (options.zValueLabel !== undefined) this.zValueLabel = options.zValueLabel;
if (options.style !== undefined) {
var styleNumber = this._getStyleNumber(options.style);
if (styleNumber !== -1) {
this.style = styleNumber;
}
}
if (options.showGrid !== undefined) this.showGrid = options.showGrid;
if (options.showPerspective !== undefined) this.showPerspective = options.showPerspective;
if (options.showShadow !== undefined) this.showShadow = options.showShadow;
if (options.tooltip !== undefined) this.showTooltip = options.tooltip;
if (options.showAnimationControls !== undefined) this.showAnimationControls = options.showAnimationControls;
if (options.keepAspectRatio !== undefined) this.keepAspectRatio = options.keepAspectRatio;
if (options.verticalRatio !== undefined) this.verticalRatio = options.verticalRatio;
if (options.animationInterval !== undefined) this.animationInterval = options.animationInterval;
if (options.animationPreload !== undefined) this.animationPreload = options.animationPreload;
if (options.animationAutoStart !== undefined)this.animationAutoStart = options.animationAutoStart;
if (options.xBarWidth !== undefined) this.defaultXBarWidth = options.xBarWidth;
if (options.yBarWidth !== undefined) this.defaultYBarWidth = options.yBarWidth;
if (options.xMin !== undefined) this.defaultXMin = options.xMin;
if (options.xStep !== undefined) this.defaultXStep = options.xStep;
if (options.xMax !== undefined) this.defaultXMax = options.xMax;
if (options.yMin !== undefined) this.defaultYMin = options.yMin;
if (options.yStep !== undefined) this.defaultYStep = options.yStep;
if (options.yMax !== undefined) this.defaultYMax = options.yMax;
if (options.zMin !== undefined) this.defaultZMin = options.zMin;
if (options.zStep !== undefined) this.defaultZStep = options.zStep;
if (options.zMax !== undefined) this.defaultZMax = options.zMax;
if (options.valueMin !== undefined) this.defaultValueMin = options.valueMin;
if (options.valueMax !== undefined) this.defaultValueMax = options.valueMax;
if (options.cameraPosition !== undefined) cameraPosition = options.cameraPosition;
if (cameraPosition !== undefined) {
this.camera.setArmRotation(cameraPosition.horizontal, cameraPosition.vertical);
this.camera.setArmLength(cameraPosition.distance);
}
else {
this.camera.setArmRotation(1.0, 0.5);
this.camera.setArmLength(1.7);
}
}
this._setBackgroundColor(options && options.backgroundColor);
this.setSize(this.width, this.height);
// re-load the data
if (this.dataTable) {
this.setData(this.dataTable);
}
// start animation when option is true
if (this.animationAutoStart && this.dataFilter) {
this.animationStart();
}
};
/**
* Redraw the Graph.
*/
Graph3d.prototype.redraw = function() {
if (this.dataPoints === undefined) {
throw 'Error: graph data not initialized';
}
this._resizeCanvas();
this._resizeCenter();
this._redrawSlider();
this._redrawClear();
this._redrawAxis();
if (this.style === Graph3d.STYLE.GRID ||
this.style === Graph3d.STYLE.SURFACE) {
this._redrawDataGrid();
}
else if (this.style === Graph3d.STYLE.LINE) {
this._redrawDataLine();
}
else if (this.style === Graph3d.STYLE.BAR ||
this.style === Graph3d.STYLE.BARCOLOR ||
this.style === Graph3d.STYLE.BARSIZE) {
this._redrawDataBar();
}
else {
// style is DOT, DOTLINE, DOTCOLOR, DOTSIZE
this._redrawDataDot();
}
this._redrawInfo();
this._redrawLegend();
};
/**
* Clear the canvas before redrawing
*/
Graph3d.prototype._redrawClear = function() {
var canvas = this.frame.canvas;
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
};
/**
* Redraw the legend showing the colors
*/
Graph3d.prototype._redrawLegend = function() {
var y;
if (this.style === Graph3d.STYLE.DOTCOLOR ||
this.style === Graph3d.STYLE.DOTSIZE) {
var dotSize = this.frame.clientWidth * 0.02;
var widthMin, widthMax;
if (this.style === Graph3d.STYLE.DOTSIZE) {
widthMin = dotSize / 2; // px
widthMax = dotSize / 2 + dotSize * 2; // Todo: put this in one function
}
else {
widthMin = 20; // px
widthMax = 20; // px
}
var height = Math.max(this.frame.clientHeight * 0.25, 100);
var top = this.margin;
var right = this.frame.clientWidth - this.margin;
var left = right - widthMax;
var bottom = top + height;
}
var canvas = this.frame.canvas;
var ctx = canvas.getContext('2d');
ctx.lineWidth = 1;
ctx.font = '14px arial'; // TODO: put in options
if (this.style === Graph3d.STYLE.DOTCOLOR) {
// draw the color bar
var ymin = 0;
var ymax = height; // Todo: make height customizable
for (y = ymin; y < ymax; y++) {
var f = (y - ymin) / (ymax - ymin);
//var width = (dotSize / 2 + (1-f) * dotSize * 2); // Todo: put this in one function
var hue = f * 240;
var color = this._hsv2rgb(hue, 1, 1);
ctx.strokeStyle = color;
ctx.beginPath();
ctx.moveTo(left, top + y);
ctx.lineTo(right, top + y);
ctx.stroke();
}
ctx.strokeStyle = this.colorAxis;
ctx.strokeRect(left, top, widthMax, height);
}
if (this.style === Graph3d.STYLE.DOTSIZE) {
// draw border around color bar
ctx.strokeStyle = this.colorAxis;
ctx.fillStyle = this.colorDot;
ctx.beginPath();
ctx.moveTo(left, top);
ctx.lineTo(right, top);
ctx.lineTo(right - widthMax + widthMin, bottom);
ctx.lineTo(left, bottom);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
if (this.style === Graph3d.STYLE.DOTCOLOR ||
this.style === Graph3d.STYLE.DOTSIZE) {
// print values along the color bar
var gridLineLen = 5; // px
var step = new StepNumber(this.valueMin, this.valueMax, (this.valueMax-this.valueMin)/5, true);
step.start();
if (step.getCurrent() < this.valueMin) {
step.next();
}
while (!step.end()) {
y = bottom - (step.getCurrent() - this.valueMin) / (this.valueMax - this.valueMin) * height;
ctx.beginPath();
ctx.moveTo(left - gridLineLen, y);
ctx.lineTo(left, y);
ctx.stroke();
ctx.textAlign = 'right';
ctx.textBaseline = 'middle';
ctx.fillStyle = this.colorAxis;
ctx.fillText(step.getCurrent(), left - 2 * gridLineLen, y);
step.next();
}
ctx.textAlign = 'right';
ctx.textBaseline = 'top';
var label = this.legendLabel;
ctx.fillText(label, right, bottom + this.margin);
}
};
/**
* Redraw the filter
*/
Graph3d.prototype._redrawFilter = function() {
this.frame.filter.innerHTML = '';
if (this.dataFilter) {
var options = {
'visible': this.showAnimationControls
};
var slider = new Slider(this.frame.filter, options);
this.frame.filter.slider = slider;
// TODO: css here is not nice here...
this.frame.filter.style.padding = '10px';
//this.frame.filter.style.backgroundColor = '#EFEFEF';
slider.setValues(this.dataFilter.values);
slider.setPlayInterval(this.animationInterval);
// create an event handler
var me = this;
var onchange = function () {
var index = slider.getIndex();
me.dataFilter.selectValue(index);
me.dataPoints = me.dataFilter._getDataPoints();
me.redraw();
};
slider.setOnChangeCallback(onchange);
}
else {
this.frame.filter.slider = undefined;
}
};
/**
* Redraw the slider
*/
Graph3d.prototype._redrawSlider = function() {
if ( this.frame.filter.slider !== undefined) {
this.frame.filter.slider.redraw();
}
};
/**
* Redraw common information
*/
Graph3d.prototype._redrawInfo = function() {
if (this.dataFilter) {
var canvas = this.frame.canvas;
var ctx = canvas.getContext('2d');
ctx.font = '14px arial'; // TODO: put in options
ctx.lineStyle = 'gray';
ctx.fillStyle = 'gray';
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
var x = this.margin;
var y = this.margin;
ctx.fillText(this.dataFilter.getLabel() + ': ' + this.dataFilter.getSelectedValue(), x, y);
}
};
/**
* Redraw the axis
*/
Graph3d.prototype._redrawAxis = function() {
var canvas = this.frame.canvas,
ctx = canvas.getContext('2d'),
from, to, step, prettyStep,
text, xText, yText, zText,
offset, xOffset, yOffset,
xMin2d, xMax2d;
// TODO: get the actual rendered style of the containerElement
//ctx.font = this.containerElement.style.font;
ctx.font = 24 / this.camera.getArmLength() + 'px arial';
// calculate the length for the short grid lines
var gridLenX = 0.025 / this.scale.x;
var gridLenY = 0.025 / this.scale.y;
var textMargin = 5 / this.camera.getArmLength(); // px
var armAngle = this.camera.getArmRotation().horizontal;
// draw x-grid lines
ctx.lineWidth = 1;
prettyStep = (this.defaultXStep === undefined);
step = new StepNumber(this.xMin, this.xMax, this.xStep, prettyStep);
step.start();
if (step.getCurrent() < this.xMin) {
step.next();
}
while (!step.end()) {
var x = step.getCurrent();
if (this.showGrid) {
from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin));
to = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin));
ctx.strokeStyle = this.colorGrid;
ctx.beginPath();
ctx.moveTo(from.x, from.y);
ctx.lineTo(to.x, to.y);
ctx.stroke();
}
else {
from = this._convert3Dto2D(new Point3d(x, this.yMin, this.zMin));
to = this._convert3Dto2D(new Point3d(x, this.yMin+gridLenX, this.zMin));
ctx.strokeStyle = this.colorAxis;
ctx.beginPath();
ctx.moveTo(from.x, from.y);
ctx.lineTo(to.x, to.y);
ctx.stroke();
from = this._convert3Dto2D(new Point3d(x, this.yMax, this.zMin));
to = this._convert3Dto2D(new Point3d(x, this.yMax-gridLenX, this.zMin));
ctx.strokeStyle = this.colorAxis;
ctx.beginPath();
ctx.moveTo(from.x, from.y);
ctx.lineTo(to.x, to.y);
ctx.stroke();
}
yText = (Math.cos(armAngle) > 0) ? this.yMin : this.yMax;
text = this._convert3Dto2D(new Point3d(x, yText, this.zMin));
if (Math.cos(armAngle * 2) > 0) {
ctx.textAlign = 'center';
ctx.textBaseline = 'top';
text.y += textMargin;
}
else if (Math.sin(armAngle * 2) < 0){
ctx.textAlign = 'right';
ctx.textBaseline = 'middle';
}
else {
ctx.textAlign = 'left';
ctx.textBaseline = 'middle';
}
ctx.fillStyle = this.colorAxis;
ctx.fillText(' ' + this.xValueLabel(step.getCurrent()) + ' ', text.x, text.y);
step.next();
}
// draw y-grid lines
ctx.lineWidth = 1;
prettyStep = (this.defaultYStep === undefined);
step = new StepNumber(this.yMin, this.yMax, this.yStep, prettyStep);
step.start();
if (step.getCurrent() < this.yMin) {
step.next();
}
while (!step.end()) {
if (this.showGrid) {
from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin));
to = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin));
ctx.strokeStyle = this.colorGrid;
ctx.beginPath();
ctx.moveTo(from.x, from.y);
ctx.lineTo(to.x, to.y);
ctx.stroke();
}
else {
from = this._convert3Dto2D(new Point3d(this.xMin, step.getCurrent(), this.zMin));
to = this._convert3Dto2D(new Point3d(this.xMin+gridLenY, step.getCurrent(), this.zMin));
ctx.strokeStyle = this.colorAxis;
ctx.beginPath();
ctx.moveTo(from.x, from.y);
ctx.lineTo(to.x, to.y);
ctx.stroke();
from = this._convert3Dto2D(new Point3d(this.xMax, step.getCurrent(), this.zMin));
to = this._convert3Dto2D(new Point3d(this.xMax-gridLenY, step.getCurrent(), this.zMin));
ctx.strokeStyle = this.colorAxis;
ctx.beginPath();
ctx.moveTo(from.x, from.y);
ctx.lineTo(to.x, to.y);
ctx.stroke();
}
xText = (Math.sin(armAngle ) > 0) ? this.xMin : this.xMax;
text = this._convert3Dto2D(new Point3d(xText, step.getCurrent(), this.zMin));
if (Math.cos(armAngle * 2) < 0) {
ctx.textAlign = 'center';
ctx.textBaseline = 'top';
text.y += textMargin;
}
else if (Math.sin(armAngle * 2) > 0){
ctx.textAlign = 'right';
ctx.textBaseline = 'middle';
}
else {
ctx.textAlign = 'left';
ctx.textBaseline = 'middle';
}
ctx.fillStyle = this.colorAxis;
ctx.fillText(' ' + this.yValueLabel(step.getCurrent()) + ' ', text.x, text.y);
step.next();
}
// draw z-grid lines and axis
ctx.lineWidth = 1;
prettyStep = (this.defaultZStep === undefined);
step = new StepNumber(this.zMin, this.zMax, this.zStep, prettyStep);
step.start();
if (step.getCurrent() < this.zMin) {
step.next();
}
xText = (Math.cos(armAngle ) > 0) ? this.xMin : this.xMax;
yText = (Math.sin(armAngle ) < 0) ? this.yMin : this.yMax;
while (!step.end()) {
// TODO: make z-grid lines really 3d?
from = this._convert3Dto2D(new Point3d(xText, yText, step.getCurrent()));
ctx.strokeStyle = this.colorAxis;
ctx.beginPath();
ctx.moveTo(from.x, from.y);
ctx.lineTo(from.x - textMargin, from.y);
ctx.stroke();
ctx.textAlign = 'right';
ctx.textBaseline = 'middle';
ctx.fillStyle = this.colorAxis;
ctx.fillText(this.zValueLabel(step.getCurrent()) + ' ', from.x - 5, from.y);
step.next();
}
ctx.lineWidth = 1;
from = this._convert3Dto2D(new Point3d(xText, yText, this.zMin));
to = this._convert3Dto2D(new Point3d(xText, yText, this.zMax));
ctx.strokeStyle = this.colorAxis;
ctx.beginPath();
ctx.moveTo(from.x, from.y);
ctx.lineTo(to.x, to.y);
ctx.stroke();
// draw x-axis
ctx.lineWidth = 1;
// line at yMin
xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin));
xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin));
ctx.strokeStyle = this.colorAxis;
ctx.beginPath();
ctx.moveTo(xMin2d.x, xMin2d.y);
ctx.lineTo(xMax2d.x, xMax2d.y);
ctx.stroke();
// line at ymax
xMin2d = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin));
xMax2d = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin));
ctx.strokeStyle = this.colorAxis;
ctx.beginPath();
ctx.moveTo(xMin2d.x, xMin2d.y);
ctx.lineTo(xMax2d.x, xMax2d.y);
ctx.stroke();
// draw y-axis
ctx.lineWidth = 1;
// line at xMin
from = this._convert3Dto2D(new Point3d(this.xMin, this.yMin, this.zMin));
to = this._convert3Dto2D(new Point3d(this.xMin, this.yMax, this.zMin));
ctx.strokeStyle = this.colorAxis;
ctx.beginPath();
ctx.moveTo(from.x, from.y);
ctx.lineTo(to.x, to.y);
ctx.stroke();
// line at xMax
from = this._convert3Dto2D(new Point3d(this.xMax, this.yMin, this.zMin));
to = this._convert3Dto2D(new Point3d(this.xMax, this.yMax, this.zMin));
ctx.strokeStyle = this.colorAxis;
ctx.beginPath();
ctx.moveTo(from.x, from.y);
ctx.lineTo(to.x, to.y);
ctx.stroke();
// draw x-label
var xLabel = this.xLabel;
if (xLabel.length > 0) {
yOffset = 0.1 / this.scale.y;
xText = (this.xMin + this.xMax) / 2;
yText = (Math.cos(armAngle) > 0) ? this.yMin - yOffset: this.yMax + yOffset;
text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin));
if (Math.cos(armAngle * 2) > 0) {
ctx.textAlign = 'center';
ctx.textBaseline = 'top';
}
else if (Math.sin(armAngle * 2) < 0){
ctx.textAlign = 'right';
ctx.textBaseline = 'middle';
}
else {
ctx.textAlign = 'left';
ctx.textBaseline = 'middle';
}
ctx.fillStyle = this.colorAxis;
ctx.fillText(xLabel, text.x, text.y);
}
// draw y-label
var yLabel = this.yLabel;
if (yLabel.length > 0) {
xOffset = 0.1 / this.scale.x;
xText = (Math.sin(armAngle ) > 0) ? this.xMin - xOffset : this.xMax + xOffset;
yText = (this.yMin + this.yMax) / 2;
text = this._convert3Dto2D(new Point3d(xText, yText, this.zMin));
if (Math.cos(armAngle * 2) < 0) {
ctx.textAlign = 'center';
ctx.textBaseline = 'top';
}
else if (Math.sin(armAngle * 2) > 0){
ctx.textAlign = 'right';
ctx.textBaseline = 'middle';
}
else {
ctx.textAlign = 'left';
ctx.textBaseline = 'middle';
}
ctx.fillStyle = this.colorAxis;
ctx.fillText(yLabel, text.x, text.y);
}
// draw z-label
var zLabel = this.zLabel;
if (zLabel.length > 0) {
offset = 30; // pixels. // TODO: relate to the max width of the values on the z axis?
xText = (Math.cos(armAngle ) > 0) ? this.xMin : this.xMax;
yText = (Math.sin(armAngle ) < 0) ? this.yMin : this.yMax;
zText = (this.zMin + this.zMax) / 2;
text = this._convert3Dto2D(new Point3d(xText, yText, zText));
ctx.textAlign = 'right';
ctx.textBaseline = 'middle';
ctx.fillStyle = this.colorAxis;
ctx.fillText(zLabel, text.x - offset, text.y);
}
};
/**
* Calculate the color based on the given value.
* @param {Number} H Hue, a value be between 0 and 360
* @param {Number} S Saturation, a value between 0 and 1
* @param {Number} V Value, a value between 0 and 1
*/
Graph3d.prototype._hsv2rgb = function(H, S, V) {
var R, G, B, C, Hi, X;
C = V * S;
Hi = Math.floor(H/60); // hi = 0,1,2,3,4,5
X = C * (1 - Math.abs(((H/60) % 2) - 1));
switch (Hi) {
case 0: R = C; G = X; B = 0; break;
case 1: R = X; G = C; B = 0; break;
case 2: R = 0; G = C; B = X; break;
case 3: R = 0; G = X; B = C; break;
case 4: R = X; G = 0; B = C; break;
case 5: R = C; G = 0; B = X; break;
default: R = 0; G = 0; B = 0; break;
}
return 'RGB(' + parseInt(R*255) + ',' + parseInt(G*255) + ',' + parseInt(B*255) + ')';
};
/**
* Draw all datapoints as a grid
* This function can be used when the style is 'grid'
*/
Graph3d.prototype._redrawDataGrid = function() {
var canvas = this.frame.canvas,
ctx = canvas.getContext('2d'),
point, right, top, cross,
i,
topSideVisible, fillStyle, strokeStyle, lineWidth,
h, s, v, zAvg;
if (this.dataPoints === undefined || this.dataPoints.length <= 0)
return; // TODO: throw exception?
// calculate the translations and screen position of all points
for (i = 0; i < this.dataPoints.length; i++) {
var trans = this._convertPointToTranslation(this.dataPoints[i].point);
var screen = this._convertTranslationToScreen(trans);
this.dataPoints[i].trans = trans;
this.dataPoints[i].screen = screen;
// calculate the translation of the point at the bottom (needed for sorting)
var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom);
this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z;
}
// sort the points on depth of their (x,y) position (not on z)
var sortDepth = function (a, b) {
return b.dist - a.dist;
};
this.dataPoints.sort(sortDepth);
if (this.style === Graph3d.STYLE.SURFACE) {
for (i = 0; i < this.dataPoints.length; i++) {
point = this.dataPoints[i];
right = this.dataPoints[i].pointRight;
top = this.dataPoints[i].pointTop;
cross = this.dataPoints[i].pointCross;
if (point !== undefined && right !== undefined && top !== undefined && cross !== undefined) {
if (this.showGrayBottom || this.showShadow) {
// calculate the cross product of the two vectors from center
// to left and right, in order to know whether we are looking at the
// bottom or at the top side. We can also use the cross product
// for calculating light intensity
var aDiff = Point3d.subtract(cross.trans, point.trans);
var bDiff = Point3d.subtract(top.trans, right.trans);
var crossproduct = Point3d.crossProduct(aDiff, bDiff);
var len = crossproduct.length();
// FIXME: there is a bug with determining the surface side (shadow or colored)
topSideVisible = (crossproduct.z > 0);
}
else {
topSideVisible = true;
}
if (topSideVisible) {
// calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
zAvg = (point.point.z + right.point.z + top.point.z + cross.point.z) / 4;
h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240;
s = 1; // saturation
if (this.showShadow) {
v = Math.min(1 + (crossproduct.x / len) / 2, 1); // value. TODO: scale
fillStyle = this._hsv2rgb(h, s, v);
strokeStyle = fillStyle;
}
else {
v = 1;
fillStyle = this._hsv2rgb(h, s, v);
strokeStyle = this.colorAxis;
}
}
else {
fillStyle = 'gray';
strokeStyle = this.colorAxis;
}
lineWidth = 0.5;
ctx.lineWidth = lineWidth;
ctx.fillStyle = fillStyle;
ctx.strokeStyle = strokeStyle;
ctx.beginPath();
ctx.moveTo(point.screen.x, point.screen.y);
ctx.lineTo(right.screen.x, right.screen.y);
ctx.lineTo(cross.screen.x, cross.screen.y);
ctx.lineTo(top.screen.x, top.screen.y);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
}
}
else { // grid style
for (i = 0; i < this.dataPoints.length; i++) {
point = this.dataPoints[i];
right = this.dataPoints[i].pointRight;
top = this.dataPoints[i].pointTop;
if (point !== undefined) {
if (this.showPerspective) {
lineWidth = 2 / -point.trans.z;
}
else {
lineWidth = 2 * -(this.eye.z / this.camera.getArmLength());
}
}
if (point !== undefined && right !== undefined) {
// calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
zAvg = (point.point.z + right.point.z) / 2;
h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240;
ctx.lineWidth = lineWidth;
ctx.strokeStyle = this._hsv2rgb(h, 1, 1);
ctx.beginPath();
ctx.moveTo(point.screen.x, point.screen.y);
ctx.lineTo(right.screen.x, right.screen.y);
ctx.stroke();
}
if (point !== undefined && top !== undefined) {
// calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
zAvg = (point.point.z + top.point.z) / 2;
h = (1 - (zAvg - this.zMin) * this.scale.z / this.verticalRatio) * 240;
ctx.lineWidth = lineWidth;
ctx.strokeStyle = this._hsv2rgb(h, 1, 1);
ctx.beginPath();
ctx.moveTo(point.screen.x, point.screen.y);
ctx.lineTo(top.screen.x, top.screen.y);
ctx.stroke();
}
}
}
};
/**
* Draw all datapoints as dots.
* This function can be used when the style is 'dot' or 'dot-line'
*/
Graph3d.prototype._redrawDataDot = function() {
var canvas = this.frame.canvas;
var ctx = canvas.getContext('2d');
var i;
if (this.dataPoints === undefined || this.dataPoints.length <= 0)
return; // TODO: throw exception?
// calculate the translations of all points
for (i = 0; i < this.dataPoints.length; i++) {
var trans = this._convertPointToTranslation(this.dataPoints[i].point);
var screen = this._convertTranslationToScreen(trans);
this.dataPoints[i].trans = trans;
this.dataPoints[i].screen = screen;
// calculate the distance from the point at the bottom to the camera
var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom);
this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z;
}
// order the translated points by depth
var sortDepth = function (a, b) {
return b.dist - a.dist;
};
this.dataPoints.sort(sortDepth);
// draw the datapoints as colored circles
var dotSize = this.frame.clientWidth * 0.02; // px
for (i = 0; i < this.dataPoints.length; i++) {
var point = this.dataPoints[i];
if (this.style === Graph3d.STYLE.DOTLINE) {
// draw a vertical line from the bottom to the graph value
//var from = this._convert3Dto2D(new Point3d(point.point.x, point.point.y, this.zMin));
var from = this._convert3Dto2D(point.bottom);
ctx.lineWidth = 1;
ctx.strokeStyle = this.colorGrid;
ctx.beginPath();
ctx.moveTo(from.x, from.y);
ctx.lineTo(point.screen.x, point.screen.y);
ctx.stroke();
}
// calculate radius for the circle
var size;
if (this.style === Graph3d.STYLE.DOTSIZE) {
size = dotSize/2 + 2*dotSize * (point.point.value - this.valueMin) / (this.valueMax - this.valueMin);
}
else {
size = dotSize;
}
var radius;
if (this.showPerspective) {
radius = size / -point.trans.z;
}
else {
radius = size * -(this.eye.z / this.camera.getArmLength());
}
if (radius < 0) {
radius = 0;
}
var hue, color, borderColor;
if (this.style === Graph3d.STYLE.DOTCOLOR ) {
// calculate the color based on the value
hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240;
color = this._hsv2rgb(hue, 1, 1);
borderColor = this._hsv2rgb(hue, 1, 0.8);
}
else if (this.style === Graph3d.STYLE.DOTSIZE) {
color = this.colorDot;
borderColor = this.colorDotBorder;
}
else {
// calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240;
color = this._hsv2rgb(hue, 1, 1);
borderColor = this._hsv2rgb(hue, 1, 0.8);
}
// draw the circle
ctx.lineWidth = 1.0;
ctx.strokeStyle = borderColor;
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(point.screen.x, point.screen.y, radius, 0, Math.PI*2, true);
ctx.fill();
ctx.stroke();
}
};
/**
* Draw all datapoints as bars.
* This function can be used when the style is 'bar', 'bar-color', or 'bar-size'
*/
Graph3d.prototype._redrawDataBar = function() {
var canvas = this.frame.canvas;
var ctx = canvas.getContext('2d');
var i, j, surface, corners;
if (this.dataPoints === undefined || this.dataPoints.length <= 0)
return; // TODO: throw exception?
// calculate the translations of all points
for (i = 0; i < this.dataPoints.length; i++) {
var trans = this._convertPointToTranslation(this.dataPoints[i].point);
var screen = this._convertTranslationToScreen(trans);
this.dataPoints[i].trans = trans;
this.dataPoints[i].screen = screen;
// calculate the distance from the point at the bottom to the camera
var transBottom = this._convertPointToTranslation(this.dataPoints[i].bottom);
this.dataPoints[i].dist = this.showPerspective ? transBottom.length() : -transBottom.z;
}
// order the translated points by depth
var sortDepth = function (a, b) {
return b.dist - a.dist;
};
this.dataPoints.sort(sortDepth);
// draw the datapoints as bars
var xWidth = this.xBarWidth / 2;
var yWidth = this.yBarWidth / 2;
for (i = 0; i < this.dataPoints.length; i++) {
var point = this.dataPoints[i];
// determine color
var hue, color, borderColor;
if (this.style === Graph3d.STYLE.BARCOLOR ) {
// calculate the color based on the value
hue = (1 - (point.point.value - this.valueMin) * this.scale.value) * 240;
color = this._hsv2rgb(hue, 1, 1);
borderColor = this._hsv2rgb(hue, 1, 0.8);
}
else if (this.style === Graph3d.STYLE.BARSIZE) {
color = this.colorDot;
borderColor = this.colorDotBorder;
}
else {
// calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
hue = (1 - (point.point.z - this.zMin) * this.scale.z / this.verticalRatio) * 240;
color = this._hsv2rgb(hue, 1, 1);
borderColor = this._hsv2rgb(hue, 1, 0.8);
}
// calculate size for the bar
if (this.style === Graph3d.STYLE.BARSIZE) {
xWidth = (this.xBarWidth / 2) * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2);
yWidth = (this.yBarWidth / 2) * ((point.point.value - this.valueMin) / (this.valueMax - this.valueMin) * 0.8 + 0.2);
}
// calculate all corner points
var me = this;
var point3d = point.point;
var top = [
{point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, point3d.z)},
{point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, point3d.z)},
{point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, point3d.z)},
{point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, point3d.z)}
];
var bottom = [
{point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, this.zMin)},
{point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, this.zMin)},
{point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, this.zMin)},
{point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, this.zMin)}
];
// calculate screen location of the points
top.forEach(function (obj) {
obj.screen = me._convert3Dto2D(obj.point);
});
bottom.forEach(function (obj) {
obj.screen = me._convert3Dto2D(obj.point);
});
// create five sides, calculate both corner points and center points
var surfaces = [
{corners: top, center: Point3d.avg(bottom[0].point, bottom[2].point)},
{corners: [top[0], top[1], bottom[1], bottom[0]], center: Point3d.avg(bottom[1].point, bottom[0].point)},
{corners: [top[1], top[2], bottom[2], bottom[1]], center: Point3d.avg(bottom[2].point, bottom[1].point)},
{corners: [top[2], top[3], bottom[3], bottom[2]], center: Point3d.avg(bottom[3].point, bottom[2].point)},
{corners: [top[3], top[0], bottom[0], bottom[3]], center: Point3d.avg(bottom[0].point, bottom[3].point)}
];
point.surfaces = surfaces;
// calculate the distance of each of the surface centers to the camera
for (j = 0; j < surfaces.length; j++) {
surface = surfaces[j];
var transCenter = this._convertPointToTranslation(surface.center);
surface.dist = this.showPerspective ? transCenter.length() : -transCenter.z;
// TODO: this dept calculation doesn't work 100% of the cases due to perspective,
// but the current solution is fast/simple and works in 99.9% of all cases
// the issue is visible in example 14, with graph.setCameraPosition({horizontal: 2.97, vertical: 0.5, distance: 0.9})
}
// order the surfaces by their (translated) depth
surfaces.sort(function (a, b) {
var diff = b.dist - a.dist;
if (diff) return diff;
// if equal depth, sort the top surface last
if (a.corners === top) return 1;
if (b.corners === top) return -1;
// both are equal
return 0;
});
// draw the ordered surfaces
ctx.lineWidth = 1;
ctx.strokeStyle = borderColor;
ctx.fillStyle = color;
// NOTE: we start at j=2 instead of j=0 as we don't need to draw the two surfaces at the backside
for (j = 2; j < surfaces.length; j++) {
surface = surfaces[j];
corners = surface.corners;
ctx.beginPath();
ctx.moveTo(corners[3].screen.x, corners[3].screen.y);
ctx.lineTo(corners[0].screen.x, corners[0].screen.y);
ctx.lineTo(corners[1].screen.x, corners[1].screen.y);
ctx.lineTo(corners[2].screen.x, corners[2].screen.y);
ctx.lineTo(corners[3].screen.x, corners[3].screen.y);
ctx.fill();
ctx.stroke();
}
}
};
/**
* Draw a line through all datapoints.
* This function can be used when the style is 'line'
*/
Graph3d.prototype._redrawDataLine = function() {
var canvas = this.frame.canvas,
ctx = canvas.getContext('2d'),
point, i;
if (this.dataPoints === undefined || this.dataPoints.length <= 0)
return; // TODO: throw exception?
// calculate the translations of all points
for (i = 0; i < this.dataPoints.length; i++) {
var trans = this._convertPointToTranslation(this.dataPoints[i].point);
var screen = this._convertTranslationToScreen(trans);
this.dataPoints[i].trans = trans;
this.dataPoints[i].screen = screen;
}
// start the line
if (this.dataPoints.length > 0) {
point = this.dataPoints[0];
ctx.lineWidth = 1; // TODO: make customizable
ctx.strokeStyle = 'blue'; // TODO: make customizable
ctx.beginPath();
ctx.moveTo(point.screen.x, point.screen.y);
}
// draw the datapoints as colored circles
for (i = 1; i < this.dataPoints.length; i++) {
point = this.dataPoints[i];
ctx.lineTo(point.screen.x, point.screen.y);
}
// finish the line
if (this.dataPoints.length > 0) {
ctx.stroke();
}
};
/**
* Start a moving operation inside the provided parent element
* @param {Event} event The event that occurred (required for
* retrieving the mouse position)
*/
Graph3d.prototype._onMouseDown = function(event) {
event = event || window.event;
// check if mouse is still down (may be up when focus is lost for example
// in an iframe)
if (this.leftButtonDown) {
this._onMouseUp(event);
}
// only react on left mouse button down
this.leftButtonDown = event.which ? (event.which === 1) : (event.button === 1);
if (!this.leftButtonDown && !this.touchDown) return;
// get mouse position (different code for IE and all other browsers)
this.startMouseX = getMouseX(event);
this.startMouseY = getMouseY(event);
this.startStart = new Date(this.start);
this.startEnd = new Date(this.end);
this.startArmRotation = this.camera.getArmRotation();
this.frame.style.cursor = 'move';
// add event listeners to handle moving the contents
// we store the function onmousemove and onmouseup in the graph, so we can
// remove the eventlisteners lateron in the function mouseUp()
var me = this;
this.onmousemove = function (event) {me._onMouseMove(event);};
this.onmouseup = function (event) {me._onMouseUp(event);};
util.addEventListener(document, 'mousemove', me.onmousemove);
util.addEventListener(document, 'mouseup', me.onmouseup);
util.preventDefault(event);
};
/**
* Perform moving operating.
* This function activated from within the funcion Graph.mouseDown().
* @param {Event} event Well, eehh, the event
*/
Graph3d.prototype._onMouseMove = function (event) {
event = event || window.event;
// calculate change in mouse position
var diffX = parseFloat(getMouseX(event)) - this.startMouseX;
var diffY = parseFloat(getMouseY(event)) - this.startMouseY;
var horizontalNew = this.startArmRotation.horizontal + diffX / 200;
var verticalNew = this.startArmRotation.vertical + diffY / 200;
var snapAngle = 4; // degrees
var snapValue = Math.sin(snapAngle / 360 * 2 * Math.PI);
// snap horizontally to nice angles at 0pi, 0.5pi, 1pi, 1.5pi, etc...
// the -0.001 is to take care that the vertical axis is always drawn at the left front corner
if (Math.abs(Math.sin(horizontalNew)) < snapValue) {
horizontalNew = Math.round((horizontalNew / Math.PI)) * Math.PI - 0.001;
}
if (Math.abs(Math.cos(horizontalNew)) < snapValue) {
horizontalNew = (Math.round((horizontalNew/ Math.PI - 0.5)) + 0.5) * Math.PI - 0.001;
}
// snap vertically to nice angles
if (Math.abs(Math.sin(verticalNew)) < snapValue) {
verticalNew = Math.round((verticalNew / Math.PI)) * Math.PI;
}
if (Math.abs(Math.cos(verticalNew)) < snapValue) {
verticalNew = (Math.round((verticalNew/ Math.PI - 0.5)) + 0.5) * Math.PI;
}
this.camera.setArmRotation(horizontalNew, verticalNew);
this.redraw();
// fire a cameraPositionChange event
var parameters = this.getCameraPosition();
this.emit('cameraPositionChange', parameters);
util.preventDefault(event);
};
/**
* Stop moving operating.
* This function activated from within the funcion Graph.mouseDown().
* @param {event} event The event
*/
Graph3d.prototype._onMouseUp = function (event) {
this.frame.style.cursor = 'auto';
this.leftButtonDown = false;
// remove event listeners here
util.removeEventListener(document, 'mousemove', this.onmousemove);
util.removeEventListener(document, 'mouseup', this.onmouseup);
util.preventDefault(event);
};
/**
* After having moved the mouse, a tooltip should pop up when the mouse is resting on a data point
* @param {Event} event A mouse move event
*/
Graph3d.prototype._onTooltip = function (event) {
var delay = 300; // ms
var boundingRect = this.frame.getBoundingClientRect();
var mouseX = getMouseX(event) - boundingRect.left;
var mouseY = getMouseY(event) - boundingRect.top;
if (!this.showTooltip) {
return;
}
if (this.tooltipTimeout) {
clearTimeout(this.tooltipTimeout);
}
// (delayed) display of a tooltip only if no mouse button is down
if (this.leftButtonDown) {
this._hideTooltip();
return;
}
if (this.tooltip && this.tooltip.dataPoint) {
// tooltip is currently visible
var dataPoint = this._dataPointFromXY(mouseX, mouseY);
if (dataPoint !== this.tooltip.dataPoint) {
// datapoint changed
if (dataPoint) {
this._showTooltip(dataPoint);
}
else {
this._hideTooltip();
}
}
}
else {
// tooltip is currently not visible
var me = this;
this.tooltipTimeout = setTimeout(function () {
me.tooltipTimeout = null;
// show a tooltip if we have a data point
var dataPoint = me._dataPointFromXY(mouseX, mouseY);
if (dataPoint) {
me._showTooltip(dataPoint);
}
}, delay);
}
};
/**
* Event handler for touchstart event on mobile devices
*/
Graph3d.prototype._onTouchStart = function(event) {
this.touchDown = true;
var me = this;
this.ontouchmove = function (event) {me._onTouchMove(event);};
this.ontouchend = function (event) {me._onTouchEnd(event);};
util.addEventListener(document, 'touchmove', me.ontouchmove);
util.addEventListener(document, 'touchend', me.ontouchend);
this._onMouseDown(event);
};
/**
* Event handler for touchmove event on mobile devices
*/
Graph3d.prototype._onTouchMove = function(event) {
this._onMouseMove(event);
};
/**
* Event handler for touchend event on mobile devices
*/
Graph3d.prototype._onTouchEnd = function(event) {
this.touchDown = false;
util.removeEventListener(document, 'touchmove', this.ontouchmove);
util.removeEventListener(document, 'touchend', this.ontouchend);
this._onMouseUp(event);
};
/**
* Event handler for mouse wheel event, used to zoom the graph
* Code from http://adomas.org/javascript-mouse-wheel/
* @param {event} event The event
*/
Graph3d.prototype._onWheel = function(event) {
if (!event) /* For IE. */
event = window.event;
// retrieve delta
var delta = 0;
if (event.wheelDelta) { /* IE/Opera. */
delta = event.wheelDelta/120;
} else if (event.detail) { /* Mozilla case. */
// In Mozilla, sign of delta is different than in IE.
// Also, delta is multiple of 3.
delta = -event.detail/3;
}
// If delta is nonzero, handle it.
// Basically, delta is now positive if wheel was scrolled up,
// and negative, if wheel was scrolled down.
if (delta) {
var oldLength = this.camera.getArmLength();
var newLength = oldLength * (1 - delta / 10);
this.camera.setArmLength(newLength);
this.redraw();
this._hideTooltip();
}
// fire a cameraPositionChange event
var parameters = this.getCameraPosition();
this.emit('cameraPositionChange', parameters);
// Prevent default actions caused by mouse wheel.
// That might be ugly, but we handle scrolls somehow
// anyway, so don't bother here..
util.preventDefault(event);
};
/**
* Test whether a point lies inside given 2D triangle
* @param {Point2d} point
* @param {Point2d[]} triangle
* @return {boolean} Returns true if given point lies inside or on the edge of the triangle
* @private
*/
Graph3d.prototype._insideTriangle = function (point, triangle) {
var a = triangle[0],
b = triangle[1],
c = triangle[2];
function sign (x) {
return x > 0 ? 1 : x < 0 ? -1 : 0;
}
var as = sign((b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x));
var bs = sign((c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x));
var cs = sign((a.x - c.x) * (point.y - c.y) - (a.y - c.y) * (point.x - c.x));
// each of the three signs must be either equal to each other or zero
return (as == 0 || bs == 0 || as == bs) &&
(bs == 0 || cs == 0 || bs == cs) &&
(as == 0 || cs == 0 || as == cs);
};
/**
* Find a data point close to given screen position (x, y)
* @param {Number} x
* @param {Number} y
* @return {Object | null} The closest data point or null if not close to any data point
* @private
*/
Graph3d.prototype._dataPointFromXY = function (x, y) {
var i,
distMax = 100, // px
dataPoint = null,
closestDataPoint = null,
closestDist = null,
center = new Point2d(x, y);
if (this.style === Graph3d.STYLE.BAR ||
this.style === Graph3d.STYLE.BARCOLOR ||
this.style === Graph3d.STYLE.BARSIZE) {
// the data points are ordered from far away to closest
for (i = this.dataPoints.length - 1; i >= 0; i--) {
dataPoint = this.dataPoints[i];
var surfaces = dataPoint.surfaces;
if (surfaces) {
for (var s = surfaces.length - 1; s >= 0; s--) {
// split each surface in two triangles, and see if the center point is inside one of these
var surface = surfaces[s];
var corners = surface.corners;
var triangle1 = [corners[0].screen, corners[1].screen, corners[2].screen];
var triangle2 = [corners[2].screen, corners[3].screen, corners[0].screen];
if (this._insideTriangle(center, triangle1) ||
this._insideTriangle(center, triangle2)) {
// return immediately at the first hit
return dataPoint;
}
}
}
}
}
else {
// find the closest data point, using distance to the center of the point on 2d screen
for (i = 0; i < this.dataPoints.length; i++) {
dataPoint = this.dataPoints[i];
var point = dataPoint.screen;
if (point) {
var distX = Math.abs(x - point.x);
var distY = Math.abs(y - point.y);
var dist = Math.sqrt(distX * distX + distY * distY);
if ((closestDist === null || dist < closestDist) && dist < distMax) {
closestDist = dist;
closestDataPoint = dataPoint;
}
}
}
}
return closestDataPoint;
};
/**
* Display a tooltip for given data point
* @param {Object} dataPoint
* @private
*/
Graph3d.prototype._showTooltip = function (dataPoint) {
var content, line, dot;
if (!this.tooltip) {
content = document.createElement('div');
content.style.position = 'absolute';
content.style.padding = '10px';
content.style.border = '1px solid #4d4d4d';
content.style.color = '#1a1a1a';
content.style.background = 'rgba(255,255,255,0.7)';
content.style.borderRadius = '2px';
content.style.boxShadow = '5px 5px 10px rgba(128,128,128,0.5)';
line = document.createElement('div');
line.style.position = 'absolute';
line.style.height = '40px';
line.style.width = '0';
line.style.borderLeft = '1px solid #4d4d4d';
dot = document.createElement('div');
dot.style.position = 'absolute';
dot.style.height = '0';
dot.style.width = '0';
dot.style.border = '5px solid #4d4d4d';
dot.style.borderRadius = '5px';
this.tooltip = {
dataPoint: null,
dom: {
content: content,
line: line,
dot: dot
}
};
}
else {
content = this.tooltip.dom.content;
line = this.tooltip.dom.line;
dot = this.tooltip.dom.dot;
}
this._hideTooltip();
this.tooltip.dataPoint = dataPoint;
if (typeof this.showTooltip === 'function') {
content.innerHTML = this.showTooltip(dataPoint.point);
}
else {
content.innerHTML = '
' +
'
x:
' + dataPoint.point.x + '
' +
'
y:
' + dataPoint.point.y + '
' +
'
z:
' + dataPoint.point.z + '
' +
'
';
}
content.style.left = '0';
content.style.top = '0';
this.frame.appendChild(content);
this.frame.appendChild(line);
this.frame.appendChild(dot);
// calculate sizes
var contentWidth = content.offsetWidth;
var contentHeight = content.offsetHeight;
var lineHeight = line.offsetHeight;
var dotWidth = dot.offsetWidth;
var dotHeight = dot.offsetHeight;
var left = dataPoint.screen.x - contentWidth / 2;
left = Math.min(Math.max(left, 10), this.frame.clientWidth - 10 - contentWidth);
line.style.left = dataPoint.screen.x + 'px';
line.style.top = (dataPoint.screen.y - lineHeight) + 'px';
content.style.left = left + 'px';
content.style.top = (dataPoint.screen.y - lineHeight - contentHeight) + 'px';
dot.style.left = (dataPoint.screen.x - dotWidth / 2) + 'px';
dot.style.top = (dataPoint.screen.y - dotHeight / 2) + 'px';
};
/**
* Hide the tooltip when displayed
* @private
*/
Graph3d.prototype._hideTooltip = function () {
if (this.tooltip) {
this.tooltip.dataPoint = null;
for (var prop in this.tooltip.dom) {
if (this.tooltip.dom.hasOwnProperty(prop)) {
var elem = this.tooltip.dom[prop];
if (elem && elem.parentNode) {
elem.parentNode.removeChild(elem);
}
}
}
}
};
/**--------------------------------------------------------------------------**/
/**
* Get the horizontal mouse position from a mouse event
* @param {Event} event
* @return {Number} mouse x
*/
function getMouseX (event) {
if ('clientX' in event) return event.clientX;
return event.targetTouches[0] && event.targetTouches[0].clientX || 0;
}
/**
* Get the vertical mouse position from a mouse event
* @param {Event} event
* @return {Number} mouse y
*/
function getMouseY (event) {
if ('clientY' in event) return event.clientY;
return event.targetTouches[0] && event.targetTouches[0].clientY || 0;
}
module.exports = Graph3d;
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
var Point3d = __webpack_require__(10);
/**
* @class Camera
* The camera is mounted on a (virtual) camera arm. The camera arm can rotate
* The camera is always looking in the direction of the origin of the arm.
* This way, the camera always rotates around one fixed point, the location
* of the camera arm.
*
* Documentation:
* http://en.wikipedia.org/wiki/3D_projection
*/
function Camera() {
this.armLocation = new Point3d();
this.armRotation = {};
this.armRotation.horizontal = 0;
this.armRotation.vertical = 0;
this.armLength = 1.7;
this.cameraLocation = new Point3d();
this.cameraRotation = new Point3d(0.5*Math.PI, 0, 0);
this.calculateCameraOrientation();
}
/**
* Set the location (origin) of the arm
* @param {Number} x Normalized value of x
* @param {Number} y Normalized value of y
* @param {Number} z Normalized value of z
*/
Camera.prototype.setArmLocation = function(x, y, z) {
this.armLocation.x = x;
this.armLocation.y = y;
this.armLocation.z = z;
this.calculateCameraOrientation();
};
/**
* Set the rotation of the camera arm
* @param {Number} horizontal The horizontal rotation, between 0 and 2*PI.
* Optional, can be left undefined.
* @param {Number} vertical The vertical rotation, between 0 and 0.5*PI
* if vertical=0.5*PI, the graph is shown from the
* top. Optional, can be left undefined.
*/
Camera.prototype.setArmRotation = function(horizontal, vertical) {
if (horizontal !== undefined) {
this.armRotation.horizontal = horizontal;
}
if (vertical !== undefined) {
this.armRotation.vertical = vertical;
if (this.armRotation.vertical < 0) this.armRotation.vertical = 0;
if (this.armRotation.vertical > 0.5*Math.PI) this.armRotation.vertical = 0.5*Math.PI;
}
if (horizontal !== undefined || vertical !== undefined) {
this.calculateCameraOrientation();
}
};
/**
* Retrieve the current arm rotation
* @return {object} An object with parameters horizontal and vertical
*/
Camera.prototype.getArmRotation = function() {
var rot = {};
rot.horizontal = this.armRotation.horizontal;
rot.vertical = this.armRotation.vertical;
return rot;
};
/**
* Set the (normalized) length of the camera arm.
* @param {Number} length A length between 0.71 and 5.0
*/
Camera.prototype.setArmLength = function(length) {
if (length === undefined)
return;
this.armLength = length;
// Radius must be larger than the corner of the graph,
// which has a distance of sqrt(0.5^2+0.5^2) = 0.71 from the center of the
// graph
if (this.armLength < 0.71) this.armLength = 0.71;
if (this.armLength > 5.0) this.armLength = 5.0;
this.calculateCameraOrientation();
};
/**
* Retrieve the arm length
* @return {Number} length
*/
Camera.prototype.getArmLength = function() {
return this.armLength;
};
/**
* Retrieve the camera location
* @return {Point3d} cameraLocation
*/
Camera.prototype.getCameraLocation = function() {
return this.cameraLocation;
};
/**
* Retrieve the camera rotation
* @return {Point3d} cameraRotation
*/
Camera.prototype.getCameraRotation = function() {
return this.cameraRotation;
};
/**
* Calculate the location and rotation of the camera based on the
* position and orientation of the camera arm
*/
Camera.prototype.calculateCameraOrientation = function() {
// calculate location of the camera
this.cameraLocation.x = this.armLocation.x - this.armLength * Math.sin(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical);
this.cameraLocation.y = this.armLocation.y - this.armLength * Math.cos(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical);
this.cameraLocation.z = this.armLocation.z + this.armLength * Math.sin(this.armRotation.vertical);
// calculate rotation of the camera
this.cameraRotation.x = Math.PI/2 - this.armRotation.vertical;
this.cameraRotation.y = 0;
this.cameraRotation.z = -this.armRotation.horizontal;
};
module.exports = Camera;
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
var DataView = __webpack_require__(4);
/**
* @class Filter
*
* @param {DataSet} data The google data table
* @param {Number} column The index of the column to be filtered
* @param {Graph} graph The graph
*/
function Filter (data, column, graph) {
this.data = data;
this.column = column;
this.graph = graph; // the parent graph
this.index = undefined;
this.value = undefined;
// read all distinct values and select the first one
this.values = graph.getDistinctValues(data.get(), this.column);
// sort both numeric and string values correctly
this.values.sort(function (a, b) {
return a > b ? 1 : a < b ? -1 : 0;
});
if (this.values.length > 0) {
this.selectValue(0);
}
// create an array with the filtered datapoints. this will be loaded afterwards
this.dataPoints = [];
this.loaded = false;
this.onLoadCallback = undefined;
if (graph.animationPreload) {
this.loaded = false;
this.loadInBackground();
}
else {
this.loaded = true;
}
};
/**
* Return the label
* @return {string} label
*/
Filter.prototype.isLoaded = function() {
return this.loaded;
};
/**
* Return the loaded progress
* @return {Number} percentage between 0 and 100
*/
Filter.prototype.getLoadedProgress = function() {
var len = this.values.length;
var i = 0;
while (this.dataPoints[i]) {
i++;
}
return Math.round(i / len * 100);
};
/**
* Return the label
* @return {string} label
*/
Filter.prototype.getLabel = function() {
return this.graph.filterLabel;
};
/**
* Return the columnIndex of the filter
* @return {Number} columnIndex
*/
Filter.prototype.getColumn = function() {
return this.column;
};
/**
* Return the currently selected value. Returns undefined if there is no selection
* @return {*} value
*/
Filter.prototype.getSelectedValue = function() {
if (this.index === undefined)
return undefined;
return this.values[this.index];
};
/**
* Retrieve all values of the filter
* @return {Array} values
*/
Filter.prototype.getValues = function() {
return this.values;
};
/**
* Retrieve one value of the filter
* @param {Number} index
* @return {*} value
*/
Filter.prototype.getValue = function(index) {
if (index >= this.values.length)
throw 'Error: index out of range';
return this.values[index];
};
/**
* Retrieve the (filtered) dataPoints for the currently selected filter index
* @param {Number} [index] (optional)
* @return {Array} dataPoints
*/
Filter.prototype._getDataPoints = function(index) {
if (index === undefined)
index = this.index;
if (index === undefined)
return [];
var dataPoints;
if (this.dataPoints[index]) {
dataPoints = this.dataPoints[index];
}
else {
var f = {};
f.column = this.column;
f.value = this.values[index];
var dataView = new DataView(this.data,{filter: function (item) {return (item[f.column] == f.value);}}).get();
dataPoints = this.graph._getDataPoints(dataView);
this.dataPoints[index] = dataPoints;
}
return dataPoints;
};
/**
* Set a callback function when the filter is fully loaded.
*/
Filter.prototype.setOnLoadCallback = function(callback) {
this.onLoadCallback = callback;
};
/**
* Add a value to the list with available values for this filter
* No double entries will be created.
* @param {Number} index
*/
Filter.prototype.selectValue = function(index) {
if (index >= this.values.length)
throw 'Error: index out of range';
this.index = index;
this.value = this.values[index];
};
/**
* Load all filtered rows in the background one by one
* Start this method without providing an index!
*/
Filter.prototype.loadInBackground = function(index) {
if (index === undefined)
index = 0;
var frame = this.graph.frame;
if (index < this.values.length) {
var dataPointsTemp = this._getDataPoints(index);
//this.graph.redrawInfo(); // TODO: not neat
// create a progress box
if (frame.progress === undefined) {
frame.progress = document.createElement('DIV');
frame.progress.style.position = 'absolute';
frame.progress.style.color = 'gray';
frame.appendChild(frame.progress);
}
var progress = this.getLoadedProgress();
frame.progress.innerHTML = 'Loading animation... ' + progress + '%';
// TODO: this is no nice solution...
frame.progress.style.bottom = 60 + 'px'; // TODO: use height of slider
frame.progress.style.left = 10 + 'px';
var me = this;
setTimeout(function() {me.loadInBackground(index+1);}, 10);
this.loaded = false;
}
else {
this.loaded = true;
// remove the progress box
if (frame.progress !== undefined) {
frame.removeChild(frame.progress);
frame.progress = undefined;
}
if (this.onLoadCallback)
this.onLoadCallback();
}
};
module.exports = Filter;
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
/**
* @prototype Point2d
* @param {Number} [x]
* @param {Number} [y]
*/
function Point2d (x, y) {
this.x = x !== undefined ? x : 0;
this.y = y !== undefined ? y : 0;
}
module.exports = Point2d;
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
/**
* @prototype Point3d
* @param {Number} [x]
* @param {Number} [y]
* @param {Number} [z]
*/
function Point3d(x, y, z) {
this.x = x !== undefined ? x : 0;
this.y = y !== undefined ? y : 0;
this.z = z !== undefined ? z : 0;
};
/**
* Subtract the two provided points, returns a-b
* @param {Point3d} a
* @param {Point3d} b
* @return {Point3d} a-b
*/
Point3d.subtract = function(a, b) {
var sub = new Point3d();
sub.x = a.x - b.x;
sub.y = a.y - b.y;
sub.z = a.z - b.z;
return sub;
};
/**
* Add the two provided points, returns a+b
* @param {Point3d} a
* @param {Point3d} b
* @return {Point3d} a+b
*/
Point3d.add = function(a, b) {
var sum = new Point3d();
sum.x = a.x + b.x;
sum.y = a.y + b.y;
sum.z = a.z + b.z;
return sum;
};
/**
* Calculate the average of two 3d points
* @param {Point3d} a
* @param {Point3d} b
* @return {Point3d} The average, (a+b)/2
*/
Point3d.avg = function(a, b) {
return new Point3d(
(a.x + b.x) / 2,
(a.y + b.y) / 2,
(a.z + b.z) / 2
);
};
/**
* Calculate the cross product of the two provided points, returns axb
* Documentation: http://en.wikipedia.org/wiki/Cross_product
* @param {Point3d} a
* @param {Point3d} b
* @return {Point3d} cross product axb
*/
Point3d.crossProduct = function(a, b) {
var crossproduct = new Point3d();
crossproduct.x = a.y * b.z - a.z * b.y;
crossproduct.y = a.z * b.x - a.x * b.z;
crossproduct.z = a.x * b.y - a.y * b.x;
return crossproduct;
};
/**
* Rtrieve the length of the vector (or the distance from this point to the origin
* @return {Number} length
*/
Point3d.prototype.length = function() {
return Math.sqrt(
this.x * this.x +
this.y * this.y +
this.z * this.z
);
};
module.exports = Point3d;
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
var util = __webpack_require__(1);
/**
* @constructor Slider
*
* An html slider control with start/stop/prev/next buttons
* @param {Element} container The element where the slider will be created
* @param {Object} options Available options:
* {boolean} visible If true (default) the
* slider is visible.
*/
function Slider(container, options) {
if (container === undefined) {
throw 'Error: No container element defined';
}
this.container = container;
this.visible = (options && options.visible != undefined) ? options.visible : true;
if (this.visible) {
this.frame = document.createElement('DIV');
//this.frame.style.backgroundColor = '#E5E5E5';
this.frame.style.width = '100%';
this.frame.style.position = 'relative';
this.container.appendChild(this.frame);
this.frame.prev = document.createElement('INPUT');
this.frame.prev.type = 'BUTTON';
this.frame.prev.value = 'Prev';
this.frame.appendChild(this.frame.prev);
this.frame.play = document.createElement('INPUT');
this.frame.play.type = 'BUTTON';
this.frame.play.value = 'Play';
this.frame.appendChild(this.frame.play);
this.frame.next = document.createElement('INPUT');
this.frame.next.type = 'BUTTON';
this.frame.next.value = 'Next';
this.frame.appendChild(this.frame.next);
this.frame.bar = document.createElement('INPUT');
this.frame.bar.type = 'BUTTON';
this.frame.bar.style.position = 'absolute';
this.frame.bar.style.border = '1px solid red';
this.frame.bar.style.width = '100px';
this.frame.bar.style.height = '6px';
this.frame.bar.style.borderRadius = '2px';
this.frame.bar.style.MozBorderRadius = '2px';
this.frame.bar.style.border = '1px solid #7F7F7F';
this.frame.bar.style.backgroundColor = '#E5E5E5';
this.frame.appendChild(this.frame.bar);
this.frame.slide = document.createElement('INPUT');
this.frame.slide.type = 'BUTTON';
this.frame.slide.style.margin = '0px';
this.frame.slide.value = ' ';
this.frame.slide.style.position = 'relative';
this.frame.slide.style.left = '-100px';
this.frame.appendChild(this.frame.slide);
// create events
var me = this;
this.frame.slide.onmousedown = function (event) {me._onMouseDown(event);};
this.frame.prev.onclick = function (event) {me.prev(event);};
this.frame.play.onclick = function (event) {me.togglePlay(event);};
this.frame.next.onclick = function (event) {me.next(event);};
}
this.onChangeCallback = undefined;
this.values = [];
this.index = undefined;
this.playTimeout = undefined;
this.playInterval = 1000; // milliseconds
this.playLoop = true;
}
/**
* Select the previous index
*/
Slider.prototype.prev = function() {
var index = this.getIndex();
if (index > 0) {
index--;
this.setIndex(index);
}
};
/**
* Select the next index
*/
Slider.prototype.next = function() {
var index = this.getIndex();
if (index < this.values.length - 1) {
index++;
this.setIndex(index);
}
};
/**
* Select the next index
*/
Slider.prototype.playNext = function() {
var start = new Date();
var index = this.getIndex();
if (index < this.values.length - 1) {
index++;
this.setIndex(index);
}
else if (this.playLoop) {
// jump to the start
index = 0;
this.setIndex(index);
}
var end = new Date();
var diff = (end - start);
// calculate how much time it to to set the index and to execute the callback
// function.
var interval = Math.max(this.playInterval - diff, 0);
// document.title = diff // TODO: cleanup
var me = this;
this.playTimeout = setTimeout(function() {me.playNext();}, interval);
};
/**
* Toggle start or stop playing
*/
Slider.prototype.togglePlay = function() {
if (this.playTimeout === undefined) {
this.play();
} else {
this.stop();
}
};
/**
* Start playing
*/
Slider.prototype.play = function() {
// Test whether already playing
if (this.playTimeout) return;
this.playNext();
if (this.frame) {
this.frame.play.value = 'Stop';
}
};
/**
* Stop playing
*/
Slider.prototype.stop = function() {
clearInterval(this.playTimeout);
this.playTimeout = undefined;
if (this.frame) {
this.frame.play.value = 'Play';
}
};
/**
* Set a callback function which will be triggered when the value of the
* slider bar has changed.
*/
Slider.prototype.setOnChangeCallback = function(callback) {
this.onChangeCallback = callback;
};
/**
* Set the interval for playing the list
* @param {Number} interval The interval in milliseconds
*/
Slider.prototype.setPlayInterval = function(interval) {
this.playInterval = interval;
};
/**
* Retrieve the current play interval
* @return {Number} interval The interval in milliseconds
*/
Slider.prototype.getPlayInterval = function(interval) {
return this.playInterval;
};
/**
* Set looping on or off
* @pararm {boolean} doLoop If true, the slider will jump to the start when
* the end is passed, and will jump to the end
* when the start is passed.
*/
Slider.prototype.setPlayLoop = function(doLoop) {
this.playLoop = doLoop;
};
/**
* Execute the onchange callback function
*/
Slider.prototype.onChange = function() {
if (this.onChangeCallback !== undefined) {
this.onChangeCallback();
}
};
/**
* redraw the slider on the correct place
*/
Slider.prototype.redraw = function() {
if (this.frame) {
// resize the bar
this.frame.bar.style.top = (this.frame.clientHeight/2 -
this.frame.bar.offsetHeight/2) + 'px';
this.frame.bar.style.width = (this.frame.clientWidth -
this.frame.prev.clientWidth -
this.frame.play.clientWidth -
this.frame.next.clientWidth - 30) + 'px';
// position the slider button
var left = this.indexToLeft(this.index);
this.frame.slide.style.left = (left) + 'px';
}
};
/**
* Set the list with values for the slider
* @param {Array} values A javascript array with values (any type)
*/
Slider.prototype.setValues = function(values) {
this.values = values;
if (this.values.length > 0)
this.setIndex(0);
else
this.index = undefined;
};
/**
* Select a value by its index
* @param {Number} index
*/
Slider.prototype.setIndex = function(index) {
if (index < this.values.length) {
this.index = index;
this.redraw();
this.onChange();
}
else {
throw 'Error: index out of range';
}
};
/**
* retrieve the index of the currently selected vaue
* @return {Number} index
*/
Slider.prototype.getIndex = function() {
return this.index;
};
/**
* retrieve the currently selected value
* @return {*} value
*/
Slider.prototype.get = function() {
return this.values[this.index];
};
Slider.prototype._onMouseDown = function(event) {
// only react on left mouse button down
var leftButtonDown = event.which ? (event.which === 1) : (event.button === 1);
if (!leftButtonDown) return;
this.startClientX = event.clientX;
this.startSlideX = parseFloat(this.frame.slide.style.left);
this.frame.style.cursor = 'move';
// add event listeners to handle moving the contents
// we store the function onmousemove and onmouseup in the graph, so we can
// remove the eventlisteners lateron in the function mouseUp()
var me = this;
this.onmousemove = function (event) {me._onMouseMove(event);};
this.onmouseup = function (event) {me._onMouseUp(event);};
util.addEventListener(document, 'mousemove', this.onmousemove);
util.addEventListener(document, 'mouseup', this.onmouseup);
util.preventDefault(event);
};
Slider.prototype.leftToIndex = function (left) {
var width = parseFloat(this.frame.bar.style.width) -
this.frame.slide.clientWidth - 10;
var x = left - 3;
var index = Math.round(x / width * (this.values.length-1));
if (index < 0) index = 0;
if (index > this.values.length-1) index = this.values.length-1;
return index;
};
Slider.prototype.indexToLeft = function (index) {
var width = parseFloat(this.frame.bar.style.width) -
this.frame.slide.clientWidth - 10;
var x = index / (this.values.length-1) * width;
var left = x + 3;
return left;
};
Slider.prototype._onMouseMove = function (event) {
var diff = event.clientX - this.startClientX;
var x = this.startSlideX + diff;
var index = this.leftToIndex(x);
this.setIndex(index);
util.preventDefault();
};
Slider.prototype._onMouseUp = function (event) {
this.frame.style.cursor = 'auto';
// remove event listeners
util.removeEventListener(document, 'mousemove', this.onmousemove);
util.removeEventListener(document, 'mouseup', this.onmouseup);
util.preventDefault();
};
module.exports = Slider;
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
/**
* @prototype StepNumber
* The class StepNumber is an iterator for Numbers. You provide a start and end
* value, and a best step size. StepNumber itself rounds to fixed values and
* a finds the step that best fits the provided step.
*
* If prettyStep is true, the step size is chosen as close as possible to the
* provided step, but being a round value like 1, 2, 5, 10, 20, 50, ....
*
* Example usage:
* var step = new StepNumber(0, 10, 2.5, true);
* step.start();
* while (!step.end()) {
* alert(step.getCurrent());
* step.next();
* }
*
* Version: 1.0
*
* @param {Number} start The start value
* @param {Number} end The end value
* @param {Number} step Optional. Step size. Must be a positive value.
* @param {boolean} prettyStep Optional. If true, the step size is rounded
* To a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
*/
function StepNumber(start, end, step, prettyStep) {
// set default values
this._start = 0;
this._end = 0;
this._step = 1;
this.prettyStep = true;
this.precision = 5;
this._current = 0;
this.setRange(start, end, step, prettyStep);
};
/**
* Set a new range: start, end and step.
*
* @param {Number} start The start value
* @param {Number} end The end value
* @param {Number} step Optional. Step size. Must be a positive value.
* @param {boolean} prettyStep Optional. If true, the step size is rounded
* To a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
*/
StepNumber.prototype.setRange = function(start, end, step, prettyStep) {
this._start = start ? start : 0;
this._end = end ? end : 0;
this.setStep(step, prettyStep);
};
/**
* Set a new step size
* @param {Number} step New step size. Must be a positive value
* @param {boolean} prettyStep Optional. If true, the provided step is rounded
* to a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
*/
StepNumber.prototype.setStep = function(step, prettyStep) {
if (step === undefined || step <= 0)
return;
if (prettyStep !== undefined)
this.prettyStep = prettyStep;
if (this.prettyStep === true)
this._step = StepNumber.calculatePrettyStep(step);
else
this._step = step;
};
/**
* Calculate a nice step size, closest to the desired step size.
* Returns a value in one of the ranges 1*10^n, 2*10^n, or 5*10^n, where n is an
* integer Number. For example 1, 2, 5, 10, 20, 50, etc...
* @param {Number} step Desired step size
* @return {Number} Nice step size
*/
StepNumber.calculatePrettyStep = function (step) {
var log10 = function (x) {return Math.log(x) / Math.LN10;};
// try three steps (multiple of 1, 2, or 5
var step1 = Math.pow(10, Math.round(log10(step))),
step2 = 2 * Math.pow(10, Math.round(log10(step / 2))),
step5 = 5 * Math.pow(10, Math.round(log10(step / 5)));
// choose the best step (closest to minimum step)
var prettyStep = step1;
if (Math.abs(step2 - step) <= Math.abs(prettyStep - step)) prettyStep = step2;
if (Math.abs(step5 - step) <= Math.abs(prettyStep - step)) prettyStep = step5;
// for safety
if (prettyStep <= 0) {
prettyStep = 1;
}
return prettyStep;
};
/**
* returns the current value of the step
* @return {Number} current value
*/
StepNumber.prototype.getCurrent = function () {
return parseFloat(this._current.toPrecision(this.precision));
};
/**
* returns the current step size
* @return {Number} current step size
*/
StepNumber.prototype.getStep = function () {
return this._step;
};
/**
* Set the current value to the largest value smaller than start, which
* is a multiple of the step size
*/
StepNumber.prototype.start = function() {
this._current = this._start - this._start % this._step;
};
/**
* Do a step, add the step size to the current value
*/
StepNumber.prototype.next = function () {
this._current += this._step;
};
/**
* Returns true whether the end is reached
* @return {boolean} True if the current value has passed the end value.
*/
StepNumber.prototype.end = function () {
return (this._current > this._end);
};
module.exports = StepNumber;
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
var Emitter = __webpack_require__(56);
var Hammer = __webpack_require__(45);
var util = __webpack_require__(1);
var DataSet = __webpack_require__(3);
var DataView = __webpack_require__(4);
var Range = __webpack_require__(17);
var Core = __webpack_require__(46);
var TimeAxis = __webpack_require__(35);
var CurrentTime = __webpack_require__(26);
var CustomTime = __webpack_require__(27);
var ItemSet = __webpack_require__(32);
/**
* Create a timeline visualization
* @param {HTMLElement} container
* @param {vis.DataSet | vis.DataView | Array | google.visualization.DataTable} [items]
* @param {vis.DataSet | vis.DataView | Array | google.visualization.DataTable} [groups]
* @param {Object} [options] See Timeline.setOptions for the available options.
* @constructor
* @extends Core
*/
function Timeline (container, items, groups, options) {
if (!(this instanceof Timeline)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
// if the third element is options, the forth is groups (optionally);
if (!(Array.isArray(groups) || groups instanceof DataSet || groups instanceof DataView) && groups instanceof Object) {
var forthArgument = options;
options = groups;
groups = forthArgument;
}
var me = this;
this.defaultOptions = {
start: null,
end: null,
autoResize: true,
orientation: 'bottom', // axis orientation: 'bottom', 'top', or 'both'
width: null,
height: null,
maxHeight: null,
minHeight: null
};
this.options = util.deepExtend({}, this.defaultOptions);
// Create the DOM, props, and emitter
this._create(container);
// all components listed here will be repainted automatically
this.components = [];
this.body = {
dom: this.dom,
domProps: this.props,
emitter: {
on: this.on.bind(this),
off: this.off.bind(this),
emit: this.emit.bind(this)
},
hiddenDates: [],
util: {
getScale: function () {
return me.timeAxis.step.scale;
},
getStep: function () {
return me.timeAxis.step.step;
},
toScreen: me._toScreen.bind(me),
toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width
toTime: me._toTime.bind(me),
toGlobalTime : me._toGlobalTime.bind(me)
}
};
// range
this.range = new Range(this.body);
this.components.push(this.range);
this.body.range = this.range;
// time axis
this.timeAxis = new TimeAxis(this.body);
this.timeAxis2 = null; // used in case of orientation option 'both'
this.components.push(this.timeAxis);
// current time bar
this.currentTime = new CurrentTime(this.body);
this.components.push(this.currentTime);
// custom time bar
// Note: time bar will be attached in this.setOptions when selected
this.customTime = new CustomTime(this.body);
this.components.push(this.customTime);
// item set
this.itemSet = new ItemSet(this.body);
this.components.push(this.itemSet);
this.itemsData = null; // DataSet
this.groupsData = null; // DataSet
this.on('tap', function (event) {
me.emit('click', me.getEventProperties(event))
});
this.on('doubletap', function (event) {
me.emit('doubleClick', me.getEventProperties(event))
});
this.dom.root.oncontextmenu = function (event) {
me.emit('contextmenu', me.getEventProperties(event))
};
// apply options
if (options) {
this.setOptions(options);
}
// IMPORTANT: THIS HAPPENS BEFORE SET ITEMS!
if (groups) {
this.setGroups(groups);
}
// create itemset
if (items) {
this.setItems(items);
}
else {
this._redraw();
}
}
// Extend the functionality from Core
Timeline.prototype = new Core();
/**
* Force a redraw. The size of all items will be recalculated.
* Can be useful to manually redraw when option autoResize=false and the window
* has been resized, or when the items CSS has been changed.
*/
Timeline.prototype.redraw = function() {
this.itemSet && this.itemSet.markDirty({refreshItems: true});
this._redraw();
};
/**
* Set items
* @param {vis.DataSet | Array | google.visualization.DataTable | null} items
*/
Timeline.prototype.setItems = function(items) {
var initialLoad = (this.itemsData == null);
// convert to type DataSet when needed
var newDataSet;
if (!items) {
newDataSet = null;
}
else if (items instanceof DataSet || items instanceof DataView) {
newDataSet = items;
}
else {
// turn an array into a dataset
newDataSet = new DataSet(items, {
type: {
start: 'Date',
end: 'Date'
}
});
}
// set items
this.itemsData = newDataSet;
this.itemSet && this.itemSet.setItems(newDataSet);
if (initialLoad) {
if (this.options.start != undefined || this.options.end != undefined) {
if (this.options.start == undefined || this.options.end == undefined) {
var dataRange = this._getDataRange();
}
var start = this.options.start != undefined ? this.options.start : dataRange.start;
var end = this.options.end != undefined ? this.options.end : dataRange.end;
this.setWindow(start, end, {animate: false});
}
else {
this.fit({animate: false});
}
}
};
/**
* Set groups
* @param {vis.DataSet | Array | google.visualization.DataTable} groups
*/
Timeline.prototype.setGroups = function(groups) {
// convert to type DataSet when needed
var newDataSet;
if (!groups) {
newDataSet = null;
}
else if (groups instanceof DataSet || groups instanceof DataView) {
newDataSet = groups;
}
else {
// turn an array into a dataset
newDataSet = new DataSet(groups);
}
this.groupsData = newDataSet;
this.itemSet.setGroups(newDataSet);
};
/**
* Set selected items by their id. Replaces the current selection
* Unknown id's are silently ignored.
* @param {string[] | string} [ids] An array with zero or more id's of the items to be
* selected. If ids is an empty array, all items will be
* unselected.
* @param {Object} [options] Available options:
* `focus: boolean`
* If true, focus will be set to the selected item(s)
* `animate: boolean | number`
* If true (default), the range is animated
* smoothly to the new window.
* If a number, the number is taken as duration
* for the animation. Default duration is 500 ms.
* Only applicable when option focus is true.
*/
Timeline.prototype.setSelection = function(ids, options) {
this.itemSet && this.itemSet.setSelection(ids);
if (options && options.focus) {
this.focus(ids, options);
}
};
/**
* Get the selected items by their id
* @return {Array} ids The ids of the selected items
*/
Timeline.prototype.getSelection = function() {
return this.itemSet && this.itemSet.getSelection() || [];
};
/**
* Adjust the visible window such that the selected item (or multiple items)
* are centered on screen.
* @param {String | String[]} id An item id or array with item ids
* @param {Object} [options] Available options:
* `animate: boolean | number`
* If true (default), the range is animated
* smoothly to the new window.
* If a number, the number is taken as duration
* for the animation. Default duration is 500 ms.
* Only applicable when option focus is true
*/
Timeline.prototype.focus = function(id, options) {
if (!this.itemsData || id == undefined) return;
var ids = Array.isArray(id) ? id : [id];
// get the specified item(s)
var itemsData = this.itemsData.getDataSet().get(ids, {
type: {
start: 'Date',
end: 'Date'
}
});
// calculate minimum start and maximum end of specified items
var start = null;
var end = null;
itemsData.forEach(function (itemData) {
var s = itemData.start.valueOf();
var e = 'end' in itemData ? itemData.end.valueOf() : itemData.start.valueOf();
if (start === null || s < start) {
start = s;
}
if (end === null || e > end) {
end = e;
}
});
if (start !== null && end !== null) {
// calculate the new middle and interval for the window
var middle = (start + end) / 2;
var interval = Math.max((this.range.end - this.range.start), (end - start) * 1.1);
var animate = (options && options.animate !== undefined) ? options.animate : true;
this.range.setRange(middle - interval / 2, middle + interval / 2, animate);
}
};
/**
* Get the data range of the item set.
* @returns {{min: Date, max: Date}} range A range with a start and end Date.
* When no minimum is found, min==null
* When no maximum is found, max==null
*/
Timeline.prototype.getItemRange = function() {
// calculate min from start filed
var dataset = this.itemsData.getDataSet(),
min = null,
max = null;
if (dataset) {
// calculate the minimum value of the field 'start'
var minItem = dataset.min('start');
min = minItem ? util.convert(minItem.start, 'Date').valueOf() : null;
// Note: we convert first to Date and then to number because else
// a conversion from ISODate to Number will fail
// calculate maximum value of fields 'start' and 'end'
var maxStartItem = dataset.max('start');
if (maxStartItem) {
max = util.convert(maxStartItem.start, 'Date').valueOf();
}
var maxEndItem = dataset.max('end');
if (maxEndItem) {
if (max == null) {
max = util.convert(maxEndItem.end, 'Date').valueOf();
}
else {
max = Math.max(max, util.convert(maxEndItem.end, 'Date').valueOf());
}
}
}
return {
min: (min != null) ? new Date(min) : null,
max: (max != null) ? new Date(max) : null
};
};
/**
* Generate Timeline related information from an event
* @param {Event} event
* @return {Object} An object with related information, like on which area
* The event happened, whether clicked on an item, etc.
*/
Timeline.prototype.getEventProperties = function (event) {
var item = this.itemSet.itemFromTarget(event);
var group = this.itemSet.groupFromTarget(event);
var pageX = event.gesture ? event.gesture.center.pageX : event.pageX;
var pageY = event.gesture ? event.gesture.center.pageY : event.pageY;
var x = pageX - util.getAbsoluteLeft(this.dom.centerContainer);
var y = pageY - util.getAbsoluteTop(this.dom.centerContainer);
var snap = this.itemSet.options.snap || null;
var scale = this.body.util.getScale();
var step = this.body.util.getStep();
var time = this._toTime(x);
var snappedTime = snap ? snap(time, scale, step) : time;
var element = util.getTarget(event);
var what = null;
if (item != null) {what = 'item';}
else if (util.hasParent(element, this.timeAxis.dom.foreground)) {what = 'axis';}
else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) {what = 'axis';}
else if (util.hasParent(element, this.itemSet.dom.labelSet)) {what = 'group-label';}
else if (util.hasParent(element, this.customTime.bar)) {what = 'custom-time';} // TODO: fix for multiple custom time bars
else if (util.hasParent(element, this.currentTime.bar)) {what = 'current-time';}
else if (util.hasParent(element, this.dom.center)) {what = 'background';}
return {
event: event,
item: item ? item.id : null,
group: group ? group.groupId : null,
what: what,
pageX: pageX,
pageY: pageY,
x: x,
y: y,
time: time,
snappedTime: snappedTime
}
};
module.exports = Timeline;
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
var Emitter = __webpack_require__(56);
var Hammer = __webpack_require__(45);
var util = __webpack_require__(1);
var DataSet = __webpack_require__(3);
var DataView = __webpack_require__(4);
var Range = __webpack_require__(17);
var Core = __webpack_require__(46);
var TimeAxis = __webpack_require__(35);
var CurrentTime = __webpack_require__(26);
var CustomTime = __webpack_require__(27);
var LineGraph = __webpack_require__(34);
/**
* Create a timeline visualization
* @param {HTMLElement} container
* @param {vis.DataSet | Array | google.visualization.DataTable} [items]
* @param {Object} [options] See Graph2d.setOptions for the available options.
* @constructor
* @extends Core
*/
function Graph2d (container, items, groups, options) {
// if the third element is options, the forth is groups (optionally);
if (!(Array.isArray(groups) || groups instanceof DataSet) && groups instanceof Object) {
var forthArgument = options;
options = groups;
groups = forthArgument;
}
var me = this;
this.defaultOptions = {
start: null,
end: null,
autoResize: true,
orientation: 'bottom',
width: null,
height: null,
maxHeight: null,
minHeight: null
};
this.options = util.deepExtend({}, this.defaultOptions);
// Create the DOM, props, and emitter
this._create(container);
// all components listed here will be repainted automatically
this.components = [];
this.body = {
dom: this.dom,
domProps: this.props,
emitter: {
on: this.on.bind(this),
off: this.off.bind(this),
emit: this.emit.bind(this)
},
hiddenDates: [],
util: {
toScreen: me._toScreen.bind(me),
toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width
toTime: me._toTime.bind(me),
toGlobalTime : me._toGlobalTime.bind(me)
}
};
// range
this.range = new Range(this.body);
this.components.push(this.range);
this.body.range = this.range;
// time axis
this.timeAxis = new TimeAxis(this.body);
this.components.push(this.timeAxis);
//this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis);
// current time bar
this.currentTime = new CurrentTime(this.body);
this.components.push(this.currentTime);
// custom time bar
// Note: time bar will be attached in this.setOptions when selected
this.customTime = new CustomTime(this.body);
this.components.push(this.customTime);
// item set
this.linegraph = new LineGraph(this.body);
this.components.push(this.linegraph);
this.itemsData = null; // DataSet
this.groupsData = null; // DataSet
this.on('tap', function (event) {
me.emit('click', me.getEventProperties(event))
});
this.on('doubletap', function (event) {
me.emit('doubleClick', me.getEventProperties(event))
});
this.dom.root.oncontextmenu = function (event) {
me.emit('contextmenu', me.getEventProperties(event))
};
// apply options
if (options) {
this.setOptions(options);
}
// IMPORTANT: THIS HAPPENS BEFORE SET ITEMS!
if (groups) {
this.setGroups(groups);
}
// create itemset
if (items) {
this.setItems(items);
}
else {
this._redraw();
}
}
// Extend the functionality from Core
Graph2d.prototype = new Core();
/**
* Set items
* @param {vis.DataSet | Array | google.visualization.DataTable | null} items
*/
Graph2d.prototype.setItems = function(items) {
var initialLoad = (this.itemsData == null);
// convert to type DataSet when needed
var newDataSet;
if (!items) {
newDataSet = null;
}
else if (items instanceof DataSet || items instanceof DataView) {
newDataSet = items;
}
else {
// turn an array into a dataset
newDataSet = new DataSet(items, {
type: {
start: 'Date',
end: 'Date'
}
});
}
// set items
this.itemsData = newDataSet;
this.linegraph && this.linegraph.setItems(newDataSet);
if (initialLoad) {
if (this.options.start != undefined || this.options.end != undefined) {
var start = this.options.start != undefined ? this.options.start : null;
var end = this.options.end != undefined ? this.options.end : null;
this.setWindow(start, end, {animate: false});
}
else {
this.fit({animate: false});
}
}
};
/**
* Set groups
* @param {vis.DataSet | Array | google.visualization.DataTable} groups
*/
Graph2d.prototype.setGroups = function(groups) {
// convert to type DataSet when needed
var newDataSet;
if (!groups) {
newDataSet = null;
}
else if (groups instanceof DataSet || groups instanceof DataView) {
newDataSet = groups;
}
else {
// turn an array into a dataset
newDataSet = new DataSet(groups);
}
this.groupsData = newDataSet;
this.linegraph.setGroups(newDataSet);
};
/**
* Returns an object containing an SVG element with the icon of the group (size determined by iconWidth and iconHeight), the label of the group (content) and the yAxisOrientation of the group (left or right).
* @param groupId
* @param width
* @param height
*/
Graph2d.prototype.getLegend = function(groupId, width, height) {
if (width === undefined) {width = 15;}
if (height === undefined) {height = 15;}
if (this.linegraph.groups[groupId] !== undefined) {
return this.linegraph.groups[groupId].getLegend(width,height);
}
else {
return "cannot find group:" + groupId;
}
};
/**
* This checks if the visible option of the supplied group (by ID) is true or false.
* @param groupId
* @returns {*}
*/
Graph2d.prototype.isGroupVisible = function(groupId) {
if (this.linegraph.groups[groupId] !== undefined) {
return (this.linegraph.groups[groupId].visible && (this.linegraph.options.groups.visibility[groupId] === undefined || this.linegraph.options.groups.visibility[groupId] == true));
}
else {
return false;
}
};
/**
* Get the data range of the item set.
* @returns {{min: Date, max: Date}} range A range with a start and end Date.
* When no minimum is found, min==null
* When no maximum is found, max==null
*/
Graph2d.prototype.getItemRange = function() {
var min = null;
var max = null;
// calculate min from start filed
for (var groupId in this.linegraph.groups) {
if (this.linegraph.groups.hasOwnProperty(groupId)) {
if (this.linegraph.groups[groupId].visible == true) {
for (var i = 0; i < this.linegraph.groups[groupId].itemsData.length; i++) {
var item = this.linegraph.groups[groupId].itemsData[i];
var value = util.convert(item.x, 'Date').valueOf();
min = min == null ? value : min > value ? value : min;
max = max == null ? value : max < value ? value : max;
}
}
}
}
return {
min: (min != null) ? new Date(min) : null,
max: (max != null) ? new Date(max) : null
};
};
/**
* Generate Timeline related information from an event
* @param {Event} event
* @return {Object} An object with related information, like on which area
* The event happened, whether clicked on an item, etc.
*/
Graph2d.prototype.getEventProperties = function (event) {
var pageX = event.gesture ? event.gesture.center.pageX : event.pageX;
var pageY = event.gesture ? event.gesture.center.pageY : event.pageY;
var x = pageX - util.getAbsoluteLeft(this.dom.centerContainer);
var y = pageY - util.getAbsoluteTop(this.dom.centerContainer);
var time = this._toTime(x);
var element = util.getTarget(event);
var what = null;
if (util.hasParent(element, this.timeAxis.dom.foreground)) {what = 'axis';}
else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) {what = 'axis';}
else if (util.hasParent(element, this.linegraph.yAxisLeft.dom.frame)) {what = 'data-axis';}
else if (util.hasParent(element, this.linegraph.yAxisRight.dom.frame)) {what = 'data-axis';}
else if (util.hasParent(element, this.linegraph.legendLeft.dom.frame)) {what = 'legend';}
else if (util.hasParent(element, this.linegraph.legendRight.dom.frame)) {what = 'legend';}
else if (util.hasParent(element, this.customTime.bar)) {what = 'custom-time';} // TODO: fix for multiple custom time bars
else if (util.hasParent(element, this.currentTime.bar)) {what = 'current-time';}
else if (util.hasParent(element, this.dom.center)) {what = 'background';}
var value = [];
var yAxisLeft = this.linegraph.yAxisLeft;
var yAxisRight = this.linegraph.yAxisRight;
if (!yAxisLeft.hidden) {
value.push(yAxisLeft.screenToValue(y));
}
if (!yAxisRight.hidden) {
value.push(yAxisRight.screenToValue(y));
}
return {
event: event,
what: what,
pageX: pageX,
pageY: pageY,
x: x,
y: y,
time: time,
value: value
}
};
module.exports = Graph2d;
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
/**
* Created by Alex on 10/3/2014.
*/
var moment = __webpack_require__(44);
/**
* used in Core to convert the options into a volatile variable
*
* @param Core
*/
exports.convertHiddenOptions = function(body, hiddenDates) {
body.hiddenDates = [];
if (hiddenDates) {
if (Array.isArray(hiddenDates) == true) {
for (var i = 0; i < hiddenDates.length; i++) {
if (hiddenDates[i].repeat === undefined) {
var dateItem = {};
dateItem.start = moment(hiddenDates[i].start).toDate().valueOf();
dateItem.end = moment(hiddenDates[i].end).toDate().valueOf();
body.hiddenDates.push(dateItem);
}
}
body.hiddenDates.sort(function (a, b) {
return a.start - b.start;
}); // sort by start time
}
}
};
/**
* create new entrees for the repeating hidden dates
* @param body
* @param hiddenDates
*/
exports.updateHiddenDates = function (body, hiddenDates) {
if (hiddenDates && body.domProps.centerContainer.width !== undefined) {
exports.convertHiddenOptions(body, hiddenDates);
var start = moment(body.range.start);
var end = moment(body.range.end);
var totalRange = (body.range.end - body.range.start);
var pixelTime = totalRange / body.domProps.centerContainer.width;
for (var i = 0; i < hiddenDates.length; i++) {
if (hiddenDates[i].repeat !== undefined) {
var startDate = moment(hiddenDates[i].start);
var endDate = moment(hiddenDates[i].end);
if (startDate._d == "Invalid Date") {
throw new Error("Supplied start date is not valid: " + hiddenDates[i].start);
}
if (endDate._d == "Invalid Date") {
throw new Error("Supplied end date is not valid: " + hiddenDates[i].end);
}
var duration = endDate - startDate;
if (duration >= 4 * pixelTime) {
var offset = 0;
var runUntil = end.clone();
switch (hiddenDates[i].repeat) {
case "daily": // case of time
if (startDate.day() != endDate.day()) {
offset = 1;
}
startDate.dayOfYear(start.dayOfYear());
startDate.year(start.year());
startDate.subtract(7,'days');
endDate.dayOfYear(start.dayOfYear());
endDate.year(start.year());
endDate.subtract(7 - offset,'days');
runUntil.add(1, 'weeks');
break;
case "weekly":
var dayOffset = endDate.diff(startDate,'days')
var day = startDate.day();
// set the start date to the range.start
startDate.date(start.date());
startDate.month(start.month());
startDate.year(start.year());
endDate = startDate.clone();
// force
startDate.day(day);
endDate.day(day);
endDate.add(dayOffset,'days');
startDate.subtract(1,'weeks');
endDate.subtract(1,'weeks');
runUntil.add(1, 'weeks');
break
case "monthly":
if (startDate.month() != endDate.month()) {
offset = 1;
}
startDate.month(start.month());
startDate.year(start.year());
startDate.subtract(1,'months');
endDate.month(start.month());
endDate.year(start.year());
endDate.subtract(1,'months');
endDate.add(offset,'months');
runUntil.add(1, 'months');
break;
case "yearly":
if (startDate.year() != endDate.year()) {
offset = 1;
}
startDate.year(start.year());
startDate.subtract(1,'years');
endDate.year(start.year());
endDate.subtract(1,'years');
endDate.add(offset,'years');
runUntil.add(1, 'years');
break;
default:
console.log("Wrong repeat format, allowed are: daily, weekly, monthly, yearly. Given:", hiddenDates[i].repeat);
return;
}
while (startDate < runUntil) {
body.hiddenDates.push({start: startDate.valueOf(), end: endDate.valueOf()});
switch (hiddenDates[i].repeat) {
case "daily":
startDate.add(1, 'days');
endDate.add(1, 'days');
break;
case "weekly":
startDate.add(1, 'weeks');
endDate.add(1, 'weeks');
break
case "monthly":
startDate.add(1, 'months');
endDate.add(1, 'months');
break;
case "yearly":
startDate.add(1, 'y');
endDate.add(1, 'y');
break;
default:
console.log("Wrong repeat format, allowed are: daily, weekly, monthly, yearly. Given:", hiddenDates[i].repeat);
return;
}
}
body.hiddenDates.push({start: startDate.valueOf(), end: endDate.valueOf()});
}
}
}
// remove duplicates, merge where possible
exports.removeDuplicates(body);
// ensure the new positions are not on hidden dates
var startHidden = exports.isHidden(body.range.start, body.hiddenDates);
var endHidden = exports.isHidden(body.range.end,body.hiddenDates);
var rangeStart = body.range.start;
var rangeEnd = body.range.end;
if (startHidden.hidden == true) {rangeStart = body.range.startToFront == true ? startHidden.startDate - 1 : startHidden.endDate + 1;}
if (endHidden.hidden == true) {rangeEnd = body.range.endToFront == true ? endHidden.startDate - 1 : endHidden.endDate + 1;}
if (startHidden.hidden == true || endHidden.hidden == true) {
body.range._applyRange(rangeStart, rangeEnd);
}
}
}
/**
* remove duplicates from the hidden dates list. Duplicates are evil. They mess everything up.
* Scales with N^2
* @param body
*/
exports.removeDuplicates = function(body) {
var hiddenDates = body.hiddenDates;
var safeDates = [];
for (var i = 0; i < hiddenDates.length; i++) {
for (var j = 0; j < hiddenDates.length; j++) {
if (i != j && hiddenDates[j].remove != true && hiddenDates[i].remove != true) {
// j inside i
if (hiddenDates[j].start >= hiddenDates[i].start && hiddenDates[j].end <= hiddenDates[i].end) {
hiddenDates[j].remove = true;
}
// j start inside i
else if (hiddenDates[j].start >= hiddenDates[i].start && hiddenDates[j].start <= hiddenDates[i].end) {
hiddenDates[i].end = hiddenDates[j].end;
hiddenDates[j].remove = true;
}
// j end inside i
else if (hiddenDates[j].end >= hiddenDates[i].start && hiddenDates[j].end <= hiddenDates[i].end) {
hiddenDates[i].start = hiddenDates[j].start;
hiddenDates[j].remove = true;
}
}
}
}
for (var i = 0; i < hiddenDates.length; i++) {
if (hiddenDates[i].remove !== true) {
safeDates.push(hiddenDates[i]);
}
}
body.hiddenDates = safeDates;
body.hiddenDates.sort(function (a, b) {
return a.start - b.start;
}); // sort by start time
}
exports.printDates = function(dates) {
for (var i =0; i < dates.length; i++) {
console.log(i, new Date(dates[i].start),new Date(dates[i].end), dates[i].start, dates[i].end, dates[i].remove);
}
}
/**
* Used in TimeStep to avoid the hidden times.
* @param timeStep
* @param previousTime
*/
exports.stepOverHiddenDates = function(timeStep, previousTime) {
var stepInHidden = false;
var currentValue = timeStep.current.valueOf();
for (var i = 0; i < timeStep.hiddenDates.length; i++) {
var startDate = timeStep.hiddenDates[i].start;
var endDate = timeStep.hiddenDates[i].end;
if (currentValue >= startDate && currentValue < endDate) {
stepInHidden = true;
break;
}
}
if (stepInHidden == true && currentValue < timeStep._end.valueOf() && currentValue != previousTime) {
var prevValue = moment(previousTime);
var newValue = moment(endDate);
//check if the next step should be major
if (prevValue.year() != newValue.year()) {timeStep.switchedYear = true;}
else if (prevValue.month() != newValue.month()) {timeStep.switchedMonth = true;}
else if (prevValue.dayOfYear() != newValue.dayOfYear()) {timeStep.switchedDay = true;}
timeStep.current = newValue.toDate();
}
};
///**
// * Used in TimeStep to avoid the hidden times.
// * @param timeStep
// * @param previousTime
// */
//exports.checkFirstStep = function(timeStep) {
// var stepInHidden = false;
// var currentValue = timeStep.current.valueOf();
// for (var i = 0; i < timeStep.hiddenDates.length; i++) {
// var startDate = timeStep.hiddenDates[i].start;
// var endDate = timeStep.hiddenDates[i].end;
// if (currentValue >= startDate && currentValue < endDate) {
// stepInHidden = true;
// break;
// }
// }
//
// if (stepInHidden == true && currentValue <= timeStep._end.valueOf()) {
// var newValue = moment(endDate);
// timeStep.current = newValue.toDate();
// }
//};
/**
* replaces the Core toScreen methods
* @param Core
* @param time
* @param width
* @returns {number}
*/
exports.toScreen = function(Core, time, width) {
if (Core.body.hiddenDates.length == 0) {
var conversion = Core.range.conversion(width);
return (time.valueOf() - conversion.offset) * conversion.scale;
}
else {
var hidden = exports.isHidden(time, Core.body.hiddenDates)
if (hidden.hidden == true) {
time = hidden.startDate;
}
var duration = exports.getHiddenDurationBetween(Core.body.hiddenDates, Core.range.start, Core.range.end);
time = exports.correctTimeForHidden(Core.body.hiddenDates, Core.range, time);
var conversion = Core.range.conversion(width, duration);
return (time.valueOf() - conversion.offset) * conversion.scale;
}
};
/**
* Replaces the core toTime methods
* @param body
* @param range
* @param x
* @param width
* @returns {Date}
*/
exports.toTime = function(Core, x, width) {
if (Core.body.hiddenDates.length == 0) {
var conversion = Core.range.conversion(width);
return new Date(x / conversion.scale + conversion.offset);
}
else {
var hiddenDuration = exports.getHiddenDurationBetween(Core.body.hiddenDates, Core.range.start, Core.range.end);
var totalDuration = Core.range.end - Core.range.start - hiddenDuration;
var partialDuration = totalDuration * x / width;
var accumulatedHiddenDuration = exports.getAccumulatedHiddenDuration(Core.body.hiddenDates, Core.range, partialDuration);
var newTime = new Date(accumulatedHiddenDuration + partialDuration + Core.range.start);
return newTime;
}
};
/**
* Support function
*
* @param hiddenDates
* @param range
* @returns {number}
*/
exports.getHiddenDurationBetween = function(hiddenDates, start, end) {
var duration = 0;
for (var i = 0; i < hiddenDates.length; i++) {
var startDate = hiddenDates[i].start;
var endDate = hiddenDates[i].end;
// if time after the cutout, and the
if (startDate >= start && endDate < end) {
duration += endDate - startDate;
}
}
return duration;
};
/**
* Support function
* @param hiddenDates
* @param range
* @param time
* @returns {{duration: number, time: *, offset: number}}
*/
exports.correctTimeForHidden = function(hiddenDates, range, time) {
time = moment(time).toDate().valueOf();
time -= exports.getHiddenDurationBefore(hiddenDates,range,time);
return time;
};
exports.getHiddenDurationBefore = function(hiddenDates, range, time) {
var timeOffset = 0;
time = moment(time).toDate().valueOf();
for (var i = 0; i < hiddenDates.length; i++) {
var startDate = hiddenDates[i].start;
var endDate = hiddenDates[i].end;
// if time after the cutout, and the
if (startDate >= range.start && endDate < range.end) {
if (time >= endDate) {
timeOffset += (endDate - startDate);
}
}
}
return timeOffset;
}
/**
* sum the duration from start to finish, including the hidden duration,
* until the required amount has been reached, return the accumulated hidden duration
* @param hiddenDates
* @param range
* @param time
* @returns {{duration: number, time: *, offset: number}}
*/
exports.getAccumulatedHiddenDuration = function(hiddenDates, range, requiredDuration) {
var hiddenDuration = 0;
var duration = 0;
var previousPoint = range.start;
//exports.printDates(hiddenDates)
for (var i = 0; i < hiddenDates.length; i++) {
var startDate = hiddenDates[i].start;
var endDate = hiddenDates[i].end;
// if time after the cutout, and the
if (startDate >= range.start && endDate < range.end) {
duration += startDate - previousPoint;
previousPoint = endDate;
if (duration >= requiredDuration) {
break;
}
else {
hiddenDuration += endDate - startDate;
}
}
}
return hiddenDuration;
};
/**
* used to step over to either side of a hidden block. Correction is disabled on tablets, might be set to true
* @param hiddenDates
* @param time
* @param direction
* @param correctionEnabled
* @returns {*}
*/
exports.snapAwayFromHidden = function(hiddenDates, time, direction, correctionEnabled) {
var isHidden = exports.isHidden(time, hiddenDates);
if (isHidden.hidden == true) {
if (direction < 0) {
if (correctionEnabled == true) {
return isHidden.startDate - (isHidden.endDate - time) - 1;
}
else {
return isHidden.startDate - 1;
}
}
else {
if (correctionEnabled == true) {
return isHidden.endDate + (time - isHidden.startDate) + 1;
}
else {
return isHidden.endDate + 1;
}
}
}
else {
return time;
}
}
/**
* Check if a time is hidden
*
* @param time
* @param hiddenDates
* @returns {{hidden: boolean, startDate: Window.start, endDate: *}}
*/
exports.isHidden = function(time, hiddenDates) {
for (var i = 0; i < hiddenDates.length; i++) {
var startDate = hiddenDates[i].start;
var endDate = hiddenDates[i].end;
if (time >= startDate && time < endDate) { // if the start is entering a hidden zone
return {hidden: true, startDate: startDate, endDate: endDate};
break;
}
}
return {hidden: false, startDate: startDate, endDate: endDate};
}
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
/**
* @constructor DataStep
* The class DataStep is an iterator for data for the lineGraph. You provide a start data point and an
* end data point. The class itself determines the best scale (step size) based on the
* provided start Date, end Date, and minimumStep.
*
* If minimumStep is provided, the step size is chosen as close as possible
* to the minimumStep but larger than minimumStep. If minimumStep is not
* provided, the scale is set to 1 DAY.
* The minimumStep should correspond with the onscreen size of about 6 characters
*
* Alternatively, you can set a scale by hand.
* After creation, you can initialize the class by executing first(). Then you
* can iterate from the start date to the end date via next(). You can check if
* the end date is reached with the function hasNext(). After each step, you can
* retrieve the current date via getCurrent().
* The DataStep has scales ranging from milliseconds, seconds, minutes, hours,
* days, to years.
*
* Version: 1.2
*
* @param {Date} [start] The start date, for example new Date(2010, 9, 21)
* or new Date(2010, 9, 21, 23, 45, 00)
* @param {Date} [end] The end date
* @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
*/
function DataStep(start, end, minimumStep, containerHeight, customRange, alignZeros) {
// variables
this.current = 0;
this.autoScale = true;
this.stepIndex = 0;
this.step = 1;
this.scale = 1;
this.marginStart;
this.marginEnd;
this.deadSpace = 0;
this.majorSteps = [1, 2, 5, 10];
this.minorSteps = [0.25, 0.5, 1, 2];
this.alignZeros = alignZeros;
this.setRange(start, end, minimumStep, containerHeight, customRange);
}
/**
* Set a new range
* If minimumStep is provided, the step size is chosen as close as possible
* to the minimumStep but larger than minimumStep. If minimumStep is not
* provided, the scale is set to 1 DAY.
* The minimumStep should correspond with the onscreen size of about 6 characters
* @param {Number} [start] The start date and time.
* @param {Number} [end] The end date and time.
* @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
*/
DataStep.prototype.setRange = function(start, end, minimumStep, containerHeight, customRange) {
this._start = customRange.min === undefined ? start : customRange.min;
this._end = customRange.max === undefined ? end : customRange.max;
if (this._start == this._end) {
this._start -= 0.75;
this._end += 1;
}
if (this.autoScale == true) {
this.setMinimumStep(minimumStep, containerHeight);
}
this.setFirst(customRange);
};
/**
* Automatically determine the scale that bests fits the provided minimum step
* @param {Number} [minimumStep] The minimum step size in milliseconds
*/
DataStep.prototype.setMinimumStep = function(minimumStep, containerHeight) {
// round to floor
var size = this._end - this._start;
var safeSize = size * 1.2;
var minimumStepValue = minimumStep * (safeSize / containerHeight);
var orderOfMagnitude = Math.round(Math.log(safeSize)/Math.LN10);
var minorStepIdx = -1;
var magnitudefactor = Math.pow(10,orderOfMagnitude);
var start = 0;
if (orderOfMagnitude < 0) {
start = orderOfMagnitude;
}
var solutionFound = false;
for (var i = start; Math.abs(i) <= Math.abs(orderOfMagnitude); i++) {
magnitudefactor = Math.pow(10,i);
for (var j = 0; j < this.minorSteps.length; j++) {
var stepSize = magnitudefactor * this.minorSteps[j];
if (stepSize >= minimumStepValue) {
solutionFound = true;
minorStepIdx = j;
break;
}
}
if (solutionFound == true) {
break;
}
}
this.stepIndex = minorStepIdx;
this.scale = magnitudefactor;
this.step = magnitudefactor * this.minorSteps[minorStepIdx];
};
/**
* Round the current date to the first minor date value
* This must be executed once when the current date is set to start Date
*/
DataStep.prototype.setFirst = function(customRange) {
if (customRange === undefined) {
customRange = {};
}
var niceStart = customRange.min === undefined ? this._start - (this.scale * 2 * this.minorSteps[this.stepIndex]) : customRange.min;
var niceEnd = customRange.max === undefined ? this._end + (this.scale * this.minorSteps[this.stepIndex]) : customRange.max;
this.marginEnd = customRange.max === undefined ? this.roundToMinor(niceEnd) : customRange.max;
this.marginStart = customRange.min === undefined ? this.roundToMinor(niceStart) : customRange.min;
// if we need to align the zero's we need to make sure that there is a zero to use.
if (this.alignZeros == true && (this.marginEnd - this.marginStart) % this.step != 0) {
this.marginEnd += this.marginEnd % this.step;
}
this.deadSpace = this.roundToMinor(niceEnd) - niceEnd + this.roundToMinor(niceStart) - niceStart;
this.marginRange = this.marginEnd - this.marginStart;
this.current = this.marginEnd;
};
DataStep.prototype.roundToMinor = function(value) {
var rounded = value - (value % (this.scale * this.minorSteps[this.stepIndex]));
if (value % (this.scale * this.minorSteps[this.stepIndex]) > 0.5 * (this.scale * this.minorSteps[this.stepIndex])) {
return rounded + (this.scale * this.minorSteps[this.stepIndex]);
}
else {
return rounded;
}
}
/**
* Check if the there is a next step
* @return {boolean} true if the current date has not passed the end date
*/
DataStep.prototype.hasNext = function () {
return (this.current >= this.marginStart);
};
/**
* Do the next step
*/
DataStep.prototype.next = function() {
var prev = this.current;
this.current -= this.step;
// safety mechanism: if current time is still unchanged, move to the end
if (this.current == prev) {
this.current = this._end;
}
};
/**
* Do the next step
*/
DataStep.prototype.previous = function() {
this.current += this.step;
this.marginEnd += this.step;
this.marginRange = this.marginEnd - this.marginStart;
};
/**
* Get the current datetime
* @return {String} current The current date
*/
DataStep.prototype.getCurrent = function(decimals) {
// prevent round-off errors when close to zero
var current = (Math.abs(this.current) < this.step / 2) ? 0 : this.current;
var toPrecision = '' + Number(current).toPrecision(5);
// If decimals is specified, then limit or extend the string as required
if(decimals !== undefined && !isNaN(Number(decimals))) {
// If string includes exponent, then we need to add it to the end
var exp = "";
var index = toPrecision.indexOf("e");
if(index != -1) {
// Get the exponent
exp = toPrecision.slice(index);
// Remove the exponent in case we need to zero-extend
toPrecision = toPrecision.slice(0, index);
}
index = Math.max(toPrecision.indexOf(","), toPrecision.indexOf("."));
if(index === -1) {
// No decimal found - if we want decimals, then we need to add it
if(decimals !== 0) {
toPrecision += '.';
}
// Calculate how long the string should be
index = toPrecision.length + decimals;
}
else if(decimals !== 0) {
// Calculate how long the string should be - accounting for the decimal place
index += decimals + 1;
}
if(index > toPrecision.length) {
// We need to add zeros!
for(var cnt = index - toPrecision.length; cnt > 0; cnt--) {
toPrecision += '0';
}
}
else {
// we need to remove characters
toPrecision = toPrecision.slice(0, index);
}
// Add the exponent if there is one
toPrecision += exp;
}
else {
if (toPrecision.indexOf(",") != -1 || toPrecision.indexOf(".") != -1) {
// If no decimal is specified, and there are decimal places, remove trailing zeros
for (var i = toPrecision.length - 1; i > 0; i--) {
if (toPrecision[i] == "0") {
toPrecision = toPrecision.slice(0, i);
}
else if (toPrecision[i] == "." || toPrecision[i] == ",") {
toPrecision = toPrecision.slice(0, i);
break;
}
else {
break;
}
}
}
}
return toPrecision;
};
/**
* Check if the current value is a major value (for example when the step
* is DAY, a major value is each first day of the MONTH)
* @return {boolean} true if current date is major, else false.
*/
DataStep.prototype.isMajor = function() {
return (this.current % (this.scale * this.majorSteps[this.stepIndex]) == 0);
};
module.exports = DataStep;
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
var util = __webpack_require__(1);
var hammerUtil = __webpack_require__(47);
var moment = __webpack_require__(44);
var Component = __webpack_require__(25);
var DateUtil = __webpack_require__(15);
/**
* @constructor Range
* A Range controls a numeric range with a start and end value.
* The Range adjusts the range based on mouse events or programmatic changes,
* and triggers events when the range is changing or has been changed.
* @param {{dom: Object, domProps: Object, emitter: Emitter}} body
* @param {Object} [options] See description at Range.setOptions
*/
function Range(body, options) {
var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
this.start = now.clone().add(-3, 'days').valueOf(); // Number
this.end = now.clone().add(4, 'days').valueOf(); // Number
this.body = body;
this.deltaDifference = 0;
this.scaleOffset = 0;
this.startToFront = false;
this.endToFront = true;
// default options
this.defaultOptions = {
start: null,
end: null,
direction: 'horizontal', // 'horizontal' or 'vertical'
moveable: true,
zoomable: true,
min: null,
max: null,
zoomMin: 10, // milliseconds
zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000 // milliseconds
};
this.options = util.extend({}, this.defaultOptions);
this.props = {
touch: {}
};
this.animateTimer = null;
// drag listeners for dragging
this.body.emitter.on('dragstart', this._onDragStart.bind(this));
this.body.emitter.on('drag', this._onDrag.bind(this));
this.body.emitter.on('dragend', this._onDragEnd.bind(this));
// ignore dragging when holding
this.body.emitter.on('hold', this._onHold.bind(this));
// mouse wheel for zooming
this.body.emitter.on('mousewheel', this._onMouseWheel.bind(this));
this.body.emitter.on('DOMMouseScroll', this._onMouseWheel.bind(this)); // For FF
// pinch to zoom
this.body.emitter.on('touch', this._onTouch.bind(this));
this.body.emitter.on('pinch', this._onPinch.bind(this));
this.setOptions(options);
}
Range.prototype = new Component();
/**
* Set options for the range controller
* @param {Object} options Available options:
* {Number | Date | String} start Start date for the range
* {Number | Date | String} end End date for the range
* {Number} min Minimum value for start
* {Number} max Maximum value for end
* {Number} zoomMin Set a minimum value for
* (end - start).
* {Number} zoomMax Set a maximum value for
* (end - start).
* {Boolean} moveable Enable moving of the range
* by dragging. True by default
* {Boolean} zoomable Enable zooming of the range
* by pinching/scrolling. True by default
*/
Range.prototype.setOptions = function (options) {
if (options) {
// copy the options that we know
var fields = ['direction', 'min', 'max', 'zoomMin', 'zoomMax', 'moveable', 'zoomable', 'activate', 'hiddenDates'];
util.selectiveExtend(fields, this.options, options);
if ('start' in options || 'end' in options) {
// apply a new range. both start and end are optional
this.setRange(options.start, options.end);
}
}
};
/**
* Test whether direction has a valid value
* @param {String} direction 'horizontal' or 'vertical'
*/
function validateDirection (direction) {
if (direction != 'horizontal' && direction != 'vertical') {
throw new TypeError('Unknown direction "' + direction + '". ' +
'Choose "horizontal" or "vertical".');
}
}
/**
* Set a new start and end range
* @param {Date | Number | String} [start]
* @param {Date | Number | String} [end]
* @param {boolean | number} [animate=false] If true, the range is animated
* smoothly to the new window.
* If animate is a number, the
* number is taken as duration
* Default duration is 500 ms.
* @param {Boolean} [byUser=false]
*
*/
Range.prototype.setRange = function(start, end, animate, byUser) {
if (byUser !== true) {
byUser = false;
}
var _start = start != undefined ? util.convert(start, 'Date').valueOf() : null;
var _end = end != undefined ? util.convert(end, 'Date').valueOf() : null;
this._cancelAnimation();
if (animate) {
var me = this;
var initStart = this.start;
var initEnd = this.end;
var duration = typeof animate === 'number' ? animate : 500;
var initTime = new Date().valueOf();
var anyChanged = false;
var next = function () {
if (!me.props.touch.dragging) {
var now = new Date().valueOf();
var time = now - initTime;
var done = time > duration;
var s = (done || _start === null) ? _start : util.easeInOutQuad(time, initStart, _start, duration);
var e = (done || _end === null) ? _end : util.easeInOutQuad(time, initEnd, _end, duration);
changed = me._applyRange(s, e);
DateUtil.updateHiddenDates(me.body, me.options.hiddenDates);
anyChanged = anyChanged || changed;
if (changed) {
me.body.emitter.emit('rangechange', {start: new Date(me.start), end: new Date(me.end), byUser:byUser});
}
if (done) {
if (anyChanged) {
me.body.emitter.emit('rangechanged', {start: new Date(me.start), end: new Date(me.end), byUser:byUser});
}
}
else {
// animate with as high as possible frame rate, leave 20 ms in between
// each to prevent the browser from blocking
me.animateTimer = setTimeout(next, 20);
}
}
};
return next();
}
else {
var changed = this._applyRange(_start, _end);
DateUtil.updateHiddenDates(this.body, this.options.hiddenDates);
if (changed) {
var params = {start: new Date(this.start), end: new Date(this.end), byUser:byUser};
this.body.emitter.emit('rangechange', params);
this.body.emitter.emit('rangechanged', params);
}
}
};
/**
* Stop an animation
* @private
*/
Range.prototype._cancelAnimation = function () {
if (this.animateTimer) {
clearTimeout(this.animateTimer);
this.animateTimer = null;
}
};
/**
* Set a new start and end range. This method is the same as setRange, but
* does not trigger a range change and range changed event, and it returns
* true when the range is changed
* @param {Number} [start]
* @param {Number} [end]
* @return {Boolean} changed
* @private
*/
Range.prototype._applyRange = function(start, end) {
var newStart = (start != null) ? util.convert(start, 'Date').valueOf() : this.start,
newEnd = (end != null) ? util.convert(end, 'Date').valueOf() : this.end,
max = (this.options.max != null) ? util.convert(this.options.max, 'Date').valueOf() : null,
min = (this.options.min != null) ? util.convert(this.options.min, 'Date').valueOf() : null,
diff;
// check for valid number
if (isNaN(newStart) || newStart === null) {
throw new Error('Invalid start "' + start + '"');
}
if (isNaN(newEnd) || newEnd === null) {
throw new Error('Invalid end "' + end + '"');
}
// prevent start < end
if (newEnd < newStart) {
newEnd = newStart;
}
// prevent start < min
if (min !== null) {
if (newStart < min) {
diff = (min - newStart);
newStart += diff;
newEnd += diff;
// prevent end > max
if (max != null) {
if (newEnd > max) {
newEnd = max;
}
}
}
}
// prevent end > max
if (max !== null) {
if (newEnd > max) {
diff = (newEnd - max);
newStart -= diff;
newEnd -= diff;
// prevent start < min
if (min != null) {
if (newStart < min) {
newStart = min;
}
}
}
}
// prevent (end-start) < zoomMin
if (this.options.zoomMin !== null) {
var zoomMin = parseFloat(this.options.zoomMin);
if (zoomMin < 0) {
zoomMin = 0;
}
if ((newEnd - newStart) < zoomMin) {
if ((this.end - this.start) === zoomMin && newStart > this.start && newEnd < this.end) {
// ignore this action, we are already zoomed to the minimum
newStart = this.start;
newEnd = this.end;
}
else {
// zoom to the minimum
diff = (zoomMin - (newEnd - newStart));
newStart -= diff / 2;
newEnd += diff / 2;
}
}
}
// prevent (end-start) > zoomMax
if (this.options.zoomMax !== null) {
var zoomMax = parseFloat(this.options.zoomMax);
if (zoomMax < 0) {
zoomMax = 0;
}
if ((newEnd - newStart) > zoomMax) {
if ((this.end - this.start) === zoomMax && newStart < this.start && newEnd > this.end) {
// ignore this action, we are already zoomed to the maximum
newStart = this.start;
newEnd = this.end;
}
else {
// zoom to the maximum
diff = ((newEnd - newStart) - zoomMax);
newStart += diff / 2;
newEnd -= diff / 2;
}
}
}
var changed = (this.start != newStart || this.end != newEnd);
// if the new range does NOT overlap with the old range, emit checkRangedItems to avoid not showing ranged items (ranged meaning has end time, not necessarily of type Range)
if (!((newStart >= this.start && newStart <= this.end) || (newEnd >= this.start && newEnd <= this.end)) &&
!((this.start >= newStart && this.start <= newEnd) || (this.end >= newStart && this.end <= newEnd) )) {
this.body.emitter.emit('checkRangedItems');
}
this.start = newStart;
this.end = newEnd;
return changed;
};
/**
* Retrieve the current range.
* @return {Object} An object with start and end properties
*/
Range.prototype.getRange = function() {
return {
start: this.start,
end: this.end
};
};
/**
* Calculate the conversion offset and scale for current range, based on
* the provided width
* @param {Number} width
* @returns {{offset: number, scale: number}} conversion
*/
Range.prototype.conversion = function (width, totalHidden) {
return Range.conversion(this.start, this.end, width, totalHidden);
};
/**
* Static method to calculate the conversion offset and scale for a range,
* based on the provided start, end, and width
* @param {Number} start
* @param {Number} end
* @param {Number} width
* @returns {{offset: number, scale: number}} conversion
*/
Range.conversion = function (start, end, width, totalHidden) {
if (totalHidden === undefined) {
totalHidden = 0;
}
if (width != 0 && (end - start != 0)) {
return {
offset: start,
scale: width / (end - start - totalHidden)
}
}
else {
return {
offset: 0,
scale: 1
};
}
};
/**
* Start dragging horizontally or vertically
* @param {Event} event
* @private
*/
Range.prototype._onDragStart = function(event) {
this.deltaDifference = 0;
this.previousDelta = 0;
// only allow dragging when configured as movable
if (!this.options.moveable) return;
// refuse to drag when we where pinching to prevent the timeline make a jump
// when releasing the fingers in opposite order from the touch screen
if (!this.props.touch.allowDragging) return;
this.props.touch.start = this.start;
this.props.touch.end = this.end;
this.props.touch.dragging = true;
if (this.body.dom.root) {
this.body.dom.root.style.cursor = 'move';
}
};
/**
* Perform dragging operation
* @param {Event} event
* @private
*/
Range.prototype._onDrag = function (event) {
// only allow dragging when configured as movable
if (!this.options.moveable) return;
// refuse to drag when we where pinching to prevent the timeline make a jump
// when releasing the fingers in opposite order from the touch screen
if (!this.props.touch.allowDragging) return;
var direction = this.options.direction;
validateDirection(direction);
var delta = (direction == 'horizontal') ? event.gesture.deltaX : event.gesture.deltaY;
delta -= this.deltaDifference;
var interval = (this.props.touch.end - this.props.touch.start);
// normalize dragging speed if cutout is in between.
var duration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
interval -= duration;
var width = (direction == 'horizontal') ? this.body.domProps.center.width : this.body.domProps.center.height;
var diffRange = -delta / width * interval;
var newStart = this.props.touch.start + diffRange;
var newEnd = this.props.touch.end + diffRange;
// snapping times away from hidden zones
var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, this.previousDelta-delta, true);
var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, this.previousDelta-delta, true);
if (safeStart != newStart || safeEnd != newEnd) {
this.deltaDifference += delta;
this.props.touch.start = safeStart;
this.props.touch.end = safeEnd;
this._onDrag(event);
return;
}
this.previousDelta = delta;
this._applyRange(newStart, newEnd);
// fire a rangechange event
this.body.emitter.emit('rangechange', {
start: new Date(this.start),
end: new Date(this.end),
byUser: true
});
};
/**
* Stop dragging operation
* @param {event} event
* @private
*/
Range.prototype._onDragEnd = function (event) {
// only allow dragging when configured as movable
if (!this.options.moveable) return;
// refuse to drag when we where pinching to prevent the timeline make a jump
// when releasing the fingers in opposite order from the touch screen
if (!this.props.touch.allowDragging) return;
this.props.touch.dragging = false;
if (this.body.dom.root) {
this.body.dom.root.style.cursor = 'auto';
}
// fire a rangechanged event
this.body.emitter.emit('rangechanged', {
start: new Date(this.start),
end: new Date(this.end),
byUser: true
});
};
/**
* Event handler for mouse wheel event, used to zoom
* Code from http://adomas.org/javascript-mouse-wheel/
* @param {Event} event
* @private
*/
Range.prototype._onMouseWheel = function(event) {
// only allow zooming when configured as zoomable and moveable
if (!(this.options.zoomable && this.options.moveable)) return;
// retrieve delta
var delta = 0;
if (event.wheelDelta) { /* IE/Opera. */
delta = event.wheelDelta / 120;
} else if (event.detail) { /* Mozilla case. */
// In Mozilla, sign of delta is different than in IE.
// Also, delta is multiple of 3.
delta = -event.detail / 3;
}
// If delta is nonzero, handle it.
// Basically, delta is now positive if wheel was scrolled up,
// and negative, if wheel was scrolled down.
if (delta) {
// perform the zoom action. Delta is normally 1 or -1
// adjust a negative delta such that zooming in with delta 0.1
// equals zooming out with a delta -0.1
var scale;
if (delta < 0) {
scale = 1 - (delta / 5);
}
else {
scale = 1 / (1 + (delta / 5)) ;
}
// calculate center, the date to zoom around
var gesture = hammerUtil.fakeGesture(this, event),
pointer = getPointer(gesture.center, this.body.dom.center),
pointerDate = this._pointerToDate(pointer);
this.zoom(scale, pointerDate, delta);
}
// Prevent default actions caused by mouse wheel
// (else the page and timeline both zoom and scroll)
event.preventDefault();
};
/**
* Start of a touch gesture
* @private
*/
Range.prototype._onTouch = function (event) {
this.props.touch.start = this.start;
this.props.touch.end = this.end;
this.props.touch.allowDragging = true;
this.props.touch.center = null;
this.scaleOffset = 0;
this.deltaDifference = 0;
};
/**
* On start of a hold gesture
* @private
*/
Range.prototype._onHold = function () {
this.props.touch.allowDragging = false;
};
/**
* Handle pinch event
* @param {Event} event
* @private
*/
Range.prototype._onPinch = function (event) {
// only allow zooming when configured as zoomable and moveable
if (!(this.options.zoomable && this.options.moveable)) return;
this.props.touch.allowDragging = false;
if (event.gesture.touches.length > 1) {
if (!this.props.touch.center) {
this.props.touch.center = getPointer(event.gesture.center, this.body.dom.center);
}
var scale = 1 / (event.gesture.scale + this.scaleOffset);
var centerDate = this._pointerToDate(this.props.touch.center);
var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.body.hiddenDates, this, centerDate);
var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore;
// calculate new start and end
var newStart = (centerDate - hiddenDurationBefore) + (this.props.touch.start - (centerDate - hiddenDurationBefore)) * scale;
var newEnd = (centerDate + hiddenDurationAfter) + (this.props.touch.end - (centerDate + hiddenDurationAfter)) * scale;
// snapping times away from hidden zones
this.startToFront = 1 - scale > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
this.endToFront = scale - 1 > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, 1 - scale, true);
var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, scale - 1, true);
if (safeStart != newStart || safeEnd != newEnd) {
this.props.touch.start = safeStart;
this.props.touch.end = safeEnd;
this.scaleOffset = 1 - event.gesture.scale;
newStart = safeStart;
newEnd = safeEnd;
}
this.setRange(newStart, newEnd, false, true);
this.startToFront = false; // revert to default
this.endToFront = true; // revert to default
}
};
/**
* Helper function to calculate the center date for zooming
* @param {{x: Number, y: Number}} pointer
* @return {number} date
* @private
*/
Range.prototype._pointerToDate = function (pointer) {
var conversion;
var direction = this.options.direction;
validateDirection(direction);
if (direction == 'horizontal') {
return this.body.util.toTime(pointer.x).valueOf();
}
else {
var height = this.body.domProps.center.height;
conversion = this.conversion(height);
return pointer.y / conversion.scale + conversion.offset;
}
};
/**
* Get the pointer location relative to the location of the dom element
* @param {{pageX: Number, pageY: Number}} touch
* @param {Element} element HTML DOM element
* @return {{x: Number, y: Number}} pointer
* @private
*/
function getPointer (touch, element) {
return {
x: touch.pageX - util.getAbsoluteLeft(element),
y: touch.pageY - util.getAbsoluteTop(element)
};
}
/**
* Zoom the range the given scale in or out. Start and end date will
* be adjusted, and the timeline will be redrawn. You can optionally give a
* date around which to zoom.
* For example, try scale = 0.9 or 1.1
* @param {Number} scale Scaling factor. Values above 1 will zoom out,
* values below 1 will zoom in.
* @param {Number} [center] Value representing a date around which will
* be zoomed.
*/
Range.prototype.zoom = function(scale, center, delta) {
// if centerDate is not provided, take it half between start Date and end Date
if (center == null) {
center = (this.start + this.end) / 2;
}
var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.body.hiddenDates, this, center);
var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore;
// calculate new start and end
var newStart = (center-hiddenDurationBefore) + (this.start - (center-hiddenDurationBefore)) * scale;
var newEnd = (center+hiddenDurationAfter) + (this.end - (center+hiddenDurationAfter)) * scale;
// snapping times away from hidden zones
this.startToFront = delta > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
this.endToFront = -delta > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, delta, true);
var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, -delta, true);
if (safeStart != newStart || safeEnd != newEnd) {
newStart = safeStart;
newEnd = safeEnd;
}
this.setRange(newStart, newEnd, false, true);
this.startToFront = false; // revert to default
this.endToFront = true; // revert to default
};
/**
* Move the range with a given delta to the left or right. Start and end
* value will be adjusted. For example, try delta = 0.1 or -0.1
* @param {Number} delta Moving amount. Positive value will move right,
* negative value will move left
*/
Range.prototype.move = function(delta) {
// zoom start Date and end Date relative to the centerDate
var diff = (this.end - this.start);
// apply new values
var newStart = this.start + diff * delta;
var newEnd = this.end + diff * delta;
// TODO: reckon with min and max range
this.start = newStart;
this.end = newEnd;
};
/**
* Move the range to a new center point
* @param {Number} moveTo New center point of the range
*/
Range.prototype.moveTo = function(moveTo) {
var center = (this.start + this.end) / 2;
var diff = center - moveTo;
// calculate new start and end
var newStart = this.start - diff;
var newEnd = this.end - diff;
this.setRange(newStart, newEnd);
};
module.exports = Range;
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
// Utility functions for ordering and stacking of items
var EPSILON = 0.001; // used when checking collisions, to prevent round-off errors
/**
* Order items by their start data
* @param {Item[]} items
*/
exports.orderByStart = function(items) {
items.sort(function (a, b) {
return a.data.start - b.data.start;
});
};
/**
* Order items by their end date. If they have no end date, their start date
* is used.
* @param {Item[]} items
*/
exports.orderByEnd = function(items) {
items.sort(function (a, b) {
var aTime = ('end' in a.data) ? a.data.end : a.data.start,
bTime = ('end' in b.data) ? b.data.end : b.data.start;
return aTime - bTime;
});
};
/**
* Adjust vertical positions of the items such that they don't overlap each
* other.
* @param {Item[]} items
* All visible items
* @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
* Margins between items and between items and the axis.
* @param {boolean} [force=false]
* If true, all items will be repositioned. If false (default), only
* items having a top===null will be re-stacked
*/
exports.stack = function(items, margin, force) {
var i, iMax;
if (force) {
// reset top position of all items
for (i = 0, iMax = items.length; i < iMax; i++) {
items[i].top = null;
}
}
// calculate new, non-overlapping positions
for (i = 0, iMax = items.length; i < iMax; i++) {
var item = items[i];
if (item.stack && item.top === null) {
// initialize top position
item.top = margin.axis;
do {
// TODO: optimize checking for overlap. when there is a gap without items,
// you only need to check for items from the next item on, not from zero
var collidingItem = null;
for (var j = 0, jj = items.length; j < jj; j++) {
var other = items[j];
if (other.top !== null && other !== item && other.stack && exports.collision(item, other, margin.item)) {
collidingItem = other;
break;
}
}
if (collidingItem != null) {
// There is a collision. Reposition the items above the colliding element
item.top = collidingItem.top + collidingItem.height + margin.item.vertical;
}
} while (collidingItem);
}
}
};
/**
* Adjust vertical positions of the items without stacking them
* @param {Item[]} items
* All visible items
* @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
* Margins between items and between items and the axis.
*/
exports.nostack = function(items, margin, subgroups) {
var i, iMax, newTop;
// reset top position of all items
for (i = 0, iMax = items.length; i < iMax; i++) {
if (items[i].data.subgroup !== undefined) {
newTop = margin.axis;
for (var subgroup in subgroups) {
if (subgroups.hasOwnProperty(subgroup)) {
if (subgroups[subgroup].visible == true && subgroups[subgroup].index < subgroups[items[i].data.subgroup].index) {
newTop += subgroups[subgroup].height + margin.item.vertical;
}
}
}
items[i].top = newTop;
}
else {
items[i].top = margin.axis;
}
}
};
/**
* Test if the two provided items collide
* The items must have parameters left, width, top, and height.
* @param {Item} a The first item
* @param {Item} b The second item
* @param {{horizontal: number, vertical: number}} margin
* An object containing a horizontal and vertical
* minimum required margin.
* @return {boolean} true if a and b collide, else false
*/
exports.collision = function(a, b, margin) {
return ((a.left - margin.horizontal + EPSILON) < (b.left + b.width) &&
(a.left + a.width + margin.horizontal - EPSILON) > b.left &&
(a.top - margin.vertical + EPSILON) < (b.top + b.height) &&
(a.top + a.height + margin.vertical - EPSILON) > b.top);
};
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
var moment = __webpack_require__(44);
var DateUtil = __webpack_require__(15);
var util = __webpack_require__(1);
/**
* @constructor TimeStep
* The class TimeStep is an iterator for dates. You provide a start date and an
* end date. The class itself determines the best scale (step size) based on the
* provided start Date, end Date, and minimumStep.
*
* If minimumStep is provided, the step size is chosen as close as possible
* to the minimumStep but larger than minimumStep. If minimumStep is not
* provided, the scale is set to 1 DAY.
* The minimumStep should correspond with the onscreen size of about 6 characters
*
* Alternatively, you can set a scale by hand.
* After creation, you can initialize the class by executing first(). Then you
* can iterate from the start date to the end date via next(). You can check if
* the end date is reached with the function hasNext(). After each step, you can
* retrieve the current date via getCurrent().
* The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
* days, to years.
*
* Version: 1.2
*
* @param {Date} [start] The start date, for example new Date(2010, 9, 21)
* or new Date(2010, 9, 21, 23, 45, 00)
* @param {Date} [end] The end date
* @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
*/
function TimeStep(start, end, minimumStep, hiddenDates) {
// variables
this.current = new Date();
this._start = new Date();
this._end = new Date();
this.autoScale = true;
this.scale = 'day';
this.step = 1;
// initialize the range
this.setRange(start, end, minimumStep);
// hidden Dates options
this.switchedDay = false;
this.switchedMonth = false;
this.switchedYear = false;
this.hiddenDates = hiddenDates;
if (hiddenDates === undefined) {
this.hiddenDates = [];
}
this.format = TimeStep.FORMAT; // default formatting
}
// Time formatting
TimeStep.FORMAT = {
minorLabels: {
millisecond:'SSS',
second: 's',
minute: 'HH:mm',
hour: 'HH:mm',
weekday: 'ddd D',
day: 'D',
month: 'MMM',
year: 'YYYY'
},
majorLabels: {
millisecond:'HH:mm:ss',
second: 'D MMMM HH:mm',
minute: 'ddd D MMMM',
hour: 'ddd D MMMM',
weekday: 'MMMM YYYY',
day: 'MMMM YYYY',
month: 'YYYY',
year: ''
}
};
/**
* Set custom formatting for the minor an major labels of the TimeStep.
* Both `minorLabels` and `majorLabels` are an Object with properties:
* 'millisecond, 'second, 'minute', 'hour', 'weekday, 'day, 'month, 'year'.
* @param {{minorLabels: Object, majorLabels: Object}} format
*/
TimeStep.prototype.setFormat = function (format) {
var defaultFormat = util.deepExtend({}, TimeStep.FORMAT);
this.format = util.deepExtend(defaultFormat, format);
};
/**
* Set a new range
* If minimumStep is provided, the step size is chosen as close as possible
* to the minimumStep but larger than minimumStep. If minimumStep is not
* provided, the scale is set to 1 DAY.
* The minimumStep should correspond with the onscreen size of about 6 characters
* @param {Date} [start] The start date and time.
* @param {Date} [end] The end date and time.
* @param {int} [minimumStep] Optional. Minimum step size in milliseconds
*/
TimeStep.prototype.setRange = function(start, end, minimumStep) {
if (!(start instanceof Date) || !(end instanceof Date)) {
throw "No legal start or end date in method setRange";
}
this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
if (this.autoScale) {
this.setMinimumStep(minimumStep);
}
};
/**
* Set the range iterator to the start date.
*/
TimeStep.prototype.first = function() {
this.current = new Date(this._start.valueOf());
this.roundToMinor();
};
/**
* Round the current date to the first minor date value
* This must be executed once when the current date is set to start Date
*/
TimeStep.prototype.roundToMinor = function() {
// round to floor
// IMPORTANT: we have no breaks in this switch! (this is no bug)
// noinspection FallThroughInSwitchStatementJS
switch (this.scale) {
case 'year':
this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
this.current.setMonth(0);
case 'month': this.current.setDate(1);
case 'day': // intentional fall through
case 'weekday': this.current.setHours(0);
case 'hour': this.current.setMinutes(0);
case 'minute': this.current.setSeconds(0);
case 'second': this.current.setMilliseconds(0);
//case 'millisecond': // nothing to do for milliseconds
}
if (this.step != 1) {
// round down to the first minor value that is a multiple of the current step size
switch (this.scale) {
case 'millisecond': this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
case 'second': this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
case 'minute': this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
case 'hour': this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
case 'weekday': // intentional fall through
case 'day': this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
case 'month': this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
case 'year': this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
default: break;
}
}
};
/**
* Check if the there is a next step
* @return {boolean} true if the current date has not passed the end date
*/
TimeStep.prototype.hasNext = function () {
return (this.current.valueOf() <= this._end.valueOf());
};
/**
* Do the next step
*/
TimeStep.prototype.next = function() {
var prev = this.current.valueOf();
// Two cases, needed to prevent issues with switching daylight savings
// (end of March and end of October)
if (this.current.getMonth() < 6) {
switch (this.scale) {
case 'millisecond':
this.current = new Date(this.current.valueOf() + this.step); break;
case 'second': this.current = new Date(this.current.valueOf() + this.step * 1000); break;
case 'minute': this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
case 'hour':
this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
// in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
var h = this.current.getHours();
this.current.setHours(h - (h % this.step));
break;
case 'weekday': // intentional fall through
case 'day': this.current.setDate(this.current.getDate() + this.step); break;
case 'month': this.current.setMonth(this.current.getMonth() + this.step); break;
case 'year': this.current.setFullYear(this.current.getFullYear() + this.step); break;
default: break;
}
}
else {
switch (this.scale) {
case 'millisecond': this.current = new Date(this.current.valueOf() + this.step); break;
case 'second': this.current.setSeconds(this.current.getSeconds() + this.step); break;
case 'minute': this.current.setMinutes(this.current.getMinutes() + this.step); break;
case 'hour': this.current.setHours(this.current.getHours() + this.step); break;
case 'weekday': // intentional fall through
case 'day': this.current.setDate(this.current.getDate() + this.step); break;
case 'month': this.current.setMonth(this.current.getMonth() + this.step); break;
case 'year': this.current.setFullYear(this.current.getFullYear() + this.step); break;
default: break;
}
}
if (this.step != 1) {
// round down to the correct major value
switch (this.scale) {
case 'millisecond': if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
case 'second': if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
case 'minute': if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
case 'hour': if(this.current.getHours() < this.step) this.current.setHours(0); break;
case 'weekday': // intentional fall through
case 'day': if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
case 'month': if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
case 'year': break; // nothing to do for year
default: break;
}
}
// safety mechanism: if current time is still unchanged, move to the end
if (this.current.valueOf() == prev) {
this.current = new Date(this._end.valueOf());
}
DateUtil.stepOverHiddenDates(this, prev);
};
/**
* Get the current datetime
* @return {Date} current The current date
*/
TimeStep.prototype.getCurrent = function() {
return this.current;
};
/**
* Set a custom scale. Autoscaling will be disabled.
* For example setScale('minute', 5) will result
* in minor steps of 5 minutes, and major steps of an hour.
*
* @param {{scale: string, step: number}} params
* An object containing two properties:
* - A string 'scale'. Choose from 'millisecond', 'second',
* 'minute', 'hour', 'weekday, 'day, 'month, 'year'.
* - A number 'step'. A step size, by default 1.
* Choose for example 1, 2, 5, or 10.
*/
TimeStep.prototype.setScale = function(params) {
if (params && typeof params.scale == 'string') {
this.scale = params.scale;
this.step = params.step > 0 ? params.step : 1;
this.autoScale = false;
}
};
/**
* Enable or disable autoscaling
* @param {boolean} enable If true, autoascaling is set true
*/
TimeStep.prototype.setAutoScale = function (enable) {
this.autoScale = enable;
};
/**
* Automatically determine the scale that bests fits the provided minimum step
* @param {Number} [minimumStep] The minimum step size in milliseconds
*/
TimeStep.prototype.setMinimumStep = function(minimumStep) {
if (minimumStep == undefined) {
return;
}
//var b = asc + ds;
var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
var stepMonth = (1000 * 60 * 60 * 24 * 30);
var stepDay = (1000 * 60 * 60 * 24);
var stepHour = (1000 * 60 * 60);
var stepMinute = (1000 * 60);
var stepSecond = (1000);
var stepMillisecond= (1);
// find the smallest step that is larger than the provided minimumStep
if (stepYear*1000 > minimumStep) {this.scale = 'year'; this.step = 1000;}
if (stepYear*500 > minimumStep) {this.scale = 'year'; this.step = 500;}
if (stepYear*100 > minimumStep) {this.scale = 'year'; this.step = 100;}
if (stepYear*50 > minimumStep) {this.scale = 'year'; this.step = 50;}
if (stepYear*10 > minimumStep) {this.scale = 'year'; this.step = 10;}
if (stepYear*5 > minimumStep) {this.scale = 'year'; this.step = 5;}
if (stepYear > minimumStep) {this.scale = 'year'; this.step = 1;}
if (stepMonth*3 > minimumStep) {this.scale = 'month'; this.step = 3;}
if (stepMonth > minimumStep) {this.scale = 'month'; this.step = 1;}
if (stepDay*5 > minimumStep) {this.scale = 'day'; this.step = 5;}
if (stepDay*2 > minimumStep) {this.scale = 'day'; this.step = 2;}
if (stepDay > minimumStep) {this.scale = 'day'; this.step = 1;}
if (stepDay/2 > minimumStep) {this.scale = 'weekday'; this.step = 1;}
if (stepHour*4 > minimumStep) {this.scale = 'hour'; this.step = 4;}
if (stepHour > minimumStep) {this.scale = 'hour'; this.step = 1;}
if (stepMinute*15 > minimumStep) {this.scale = 'minute'; this.step = 15;}
if (stepMinute*10 > minimumStep) {this.scale = 'minute'; this.step = 10;}
if (stepMinute*5 > minimumStep) {this.scale = 'minute'; this.step = 5;}
if (stepMinute > minimumStep) {this.scale = 'minute'; this.step = 1;}
if (stepSecond*15 > minimumStep) {this.scale = 'second'; this.step = 15;}
if (stepSecond*10 > minimumStep) {this.scale = 'second'; this.step = 10;}
if (stepSecond*5 > minimumStep) {this.scale = 'second'; this.step = 5;}
if (stepSecond > minimumStep) {this.scale = 'second'; this.step = 1;}
if (stepMillisecond*200 > minimumStep) {this.scale = 'millisecond'; this.step = 200;}
if (stepMillisecond*100 > minimumStep) {this.scale = 'millisecond'; this.step = 100;}
if (stepMillisecond*50 > minimumStep) {this.scale = 'millisecond'; this.step = 50;}
if (stepMillisecond*10 > minimumStep) {this.scale = 'millisecond'; this.step = 10;}
if (stepMillisecond*5 > minimumStep) {this.scale = 'millisecond'; this.step = 5;}
if (stepMillisecond > minimumStep) {this.scale = 'millisecond'; this.step = 1;}
};
/**
* Snap a date to a rounded value.
* The snap intervals are dependent on the current scale and step.
* Static function
* @param {Date} date the date to be snapped.
* @param {string} scale Current scale, can be 'millisecond', 'second',
* 'minute', 'hour', 'weekday, 'day, 'month, 'year'.
* @param {number} step Current step (1, 2, 4, 5, ...
* @return {Date} snappedDate
*/
TimeStep.snap = function(date, scale, step) {
var clone = new Date(date.valueOf());
if (scale == 'year') {
var year = clone.getFullYear() + Math.round(clone.getMonth() / 12);
clone.setFullYear(Math.round(year / step) * step);
clone.setMonth(0);
clone.setDate(0);
clone.setHours(0);
clone.setMinutes(0);
clone.setSeconds(0);
clone.setMilliseconds(0);
}
else if (scale == 'month') {
if (clone.getDate() > 15) {
clone.setDate(1);
clone.setMonth(clone.getMonth() + 1);
// important: first set Date to 1, after that change the month.
}
else {
clone.setDate(1);
}
clone.setHours(0);
clone.setMinutes(0);
clone.setSeconds(0);
clone.setMilliseconds(0);
}
else if (scale == 'day') {
//noinspection FallthroughInSwitchStatementJS
switch (step) {
case 5:
case 2:
clone.setHours(Math.round(clone.getHours() / 24) * 24); break;
default:
clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
}
clone.setMinutes(0);
clone.setSeconds(0);
clone.setMilliseconds(0);
}
else if (scale == 'weekday') {
//noinspection FallthroughInSwitchStatementJS
switch (step) {
case 5:
case 2:
clone.setHours(Math.round(clone.getHours() / 12) * 12); break;
default:
clone.setHours(Math.round(clone.getHours() / 6) * 6); break;
}
clone.setMinutes(0);
clone.setSeconds(0);
clone.setMilliseconds(0);
}
else if (scale == 'hour') {
switch (step) {
case 4:
clone.setMinutes(Math.round(clone.getMinutes() / 60) * 60); break;
default:
clone.setMinutes(Math.round(clone.getMinutes() / 30) * 30); break;
}
clone.setSeconds(0);
clone.setMilliseconds(0);
} else if (scale == 'minute') {
//noinspection FallthroughInSwitchStatementJS
switch (step) {
case 15:
case 10:
clone.setMinutes(Math.round(clone.getMinutes() / 5) * 5);
clone.setSeconds(0);
break;
case 5:
clone.setSeconds(Math.round(clone.getSeconds() / 60) * 60); break;
default:
clone.setSeconds(Math.round(clone.getSeconds() / 30) * 30); break;
}
clone.setMilliseconds(0);
}
else if (scale == 'second') {
//noinspection FallthroughInSwitchStatementJS
switch (step) {
case 15:
case 10:
clone.setSeconds(Math.round(clone.getSeconds() / 5) * 5);
clone.setMilliseconds(0);
break;
case 5:
clone.setMilliseconds(Math.round(clone.getMilliseconds() / 1000) * 1000); break;
default:
clone.setMilliseconds(Math.round(clone.getMilliseconds() / 500) * 500); break;
}
}
else if (scale == 'millisecond') {
var _step = step > 5 ? step / 2 : 1;
clone.setMilliseconds(Math.round(clone.getMilliseconds() / _step) * _step);
}
return clone;
};
/**
* Check if the current value is a major value (for example when the step
* is DAY, a major value is each first day of the MONTH)
* @return {boolean} true if current date is major, else false.
*/
TimeStep.prototype.isMajor = function() {
if (this.switchedYear == true) {
this.switchedYear = false;
switch (this.scale) {
case 'year':
case 'month':
case 'weekday':
case 'day':
case 'hour':
case 'minute':
case 'second':
case 'millisecond':
return true;
default:
return false;
}
}
else if (this.switchedMonth == true) {
this.switchedMonth = false;
switch (this.scale) {
case 'weekday':
case 'day':
case 'hour':
case 'minute':
case 'second':
case 'millisecond':
return true;
default:
return false;
}
}
else if (this.switchedDay == true) {
this.switchedDay = false;
switch (this.scale) {
case 'millisecond':
case 'second':
case 'minute':
case 'hour':
return true;
default:
return false;
}
}
switch (this.scale) {
case 'millisecond':
return (this.current.getMilliseconds() == 0);
case 'second':
return (this.current.getSeconds() == 0);
case 'minute':
return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
case 'hour':
return (this.current.getHours() == 0);
case 'weekday': // intentional fall through
case 'day':
return (this.current.getDate() == 1);
case 'month':
return (this.current.getMonth() == 0);
case 'year':
return false;
default:
return false;
}
};
/**
* Returns formatted text for the minor axislabel, depending on the current
* date and the scale. For example when scale is MINUTE, the current time is
* formatted as "hh:mm".
* @param {Date} [date] custom date. if not provided, current date is taken
*/
TimeStep.prototype.getLabelMinor = function(date) {
if (date == undefined) {
date = this.current;
}
var format = this.format.minorLabels[this.scale];
return (format && format.length > 0) ? moment(date).format(format) : '';
};
/**
* Returns formatted text for the major axis label, depending on the current
* date and the scale. For example when scale is MINUTE, the major scale is
* hours, and the hour will be formatted as "hh".
* @param {Date} [date] custom date. if not provided, current date is taken
*/
TimeStep.prototype.getLabelMajor = function(date) {
if (date == undefined) {
date = this.current;
}
var format = this.format.majorLabels[this.scale];
return (format && format.length > 0) ? moment(date).format(format) : '';
};
TimeStep.prototype.getClassName = function() {
var m = moment(this.current);
var date = m.locale ? m.locale('en') : m.lang('en'); // old versions of moment have .lang() function
var step = this.step;
function even(value) {
return (value / step % 2 == 0) ? ' even' : ' odd';
}
function today(date) {
if (date.isSame(new Date(), 'day')) {
return ' today';
}
if (date.isSame(moment().add(1, 'day'), 'day')) {
return ' tomorrow';
}
if (date.isSame(moment().add(-1, 'day'), 'day')) {
return ' yesterday';
}
return '';
}
function currentWeek(date) {
return date.isSame(new Date(), 'week') ? ' current-week' : '';
}
function currentMonth(date) {
return date.isSame(new Date(), 'month') ? ' current-month' : '';
}
function currentYear(date) {
return date.isSame(new Date(), 'year') ? ' current-year' : '';
}
switch (this.scale) {
case 'millisecond':
return even(date.milliseconds()).trim();
case 'second':
return even(date.seconds()).trim();
case 'minute':
return even(date.minutes()).trim();
case 'hour':
var hours = date.hours();
if (this.step == 4) {
hours = hours + '-' + (hours + 4);
}
return hours + 'h' + today(date) + even(date.hours());
case 'weekday':
return date.format('dddd').toLowerCase() +
today(date) + currentWeek(date) + even(date.date());
case 'day':
var day = date.date();
var month = date.format('MMMM').toLowerCase();
return 'day' + day + ' ' + month + currentMonth(date) + even(day - 1);
case 'month':
return date.format('MMMM').toLowerCase() +
currentMonth(date) + even(date.month());
case 'year':
var year = date.year();
return 'year' + year + currentYear(date)+ even(year);
default:
return '';
}
};
module.exports = TimeStep;
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
var Hammer = __webpack_require__(45);
var util = __webpack_require__(1);
/**
* @constructor Item
* @param {Object} data Object containing (optional) parameters type,
* start, end, content, group, className.
* @param {{toScreen: function, toTime: function}} conversion
* Conversion functions from time to screen and vice versa
* @param {Object} options Configuration options
* // TODO: describe available options
*/
function Item (data, conversion, options) {
this.id = null;
this.parent = null;
this.data = data;
this.dom = null;
this.conversion = conversion || {};
this.options = options || {};
this.selected = false;
this.displayed = false;
this.dirty = true;
this.top = null;
this.left = null;
this.width = null;
this.height = null;
}
Item.prototype.stack = true;
/**
* Select current item
*/
Item.prototype.select = function() {
this.selected = true;
this.dirty = true;
if (this.displayed) this.redraw();
};
/**
* Unselect current item
*/
Item.prototype.unselect = function() {
this.selected = false;
this.dirty = true;
if (this.displayed) this.redraw();
};
/**
* Set data for the item. Existing data will be updated. The id should not
* be changed. When the item is displayed, it will be redrawn immediately.
* @param {Object} data
*/
Item.prototype.setData = function(data) {
var groupChanged = data.group != undefined && this.data.group != data.group;
if (groupChanged) {
this.parent.itemSet._moveToGroup(this, data.group);
}
this.data = data;
this.dirty = true;
if (this.displayed) this.redraw();
};
/**
* Set a parent for the item
* @param {ItemSet | Group} parent
*/
Item.prototype.setParent = function(parent) {
if (this.displayed) {
this.hide();
this.parent = parent;
if (this.parent) {
this.show();
}
}
else {
this.parent = parent;
}
};
/**
* Check whether this item is visible inside given range
* @returns {{start: Number, end: Number}} range with a timestamp for start and end
* @returns {boolean} True if visible
*/
Item.prototype.isVisible = function(range) {
// Should be implemented by Item implementations
return false;
};
/**
* Show the Item in the DOM (when not already visible)
* @return {Boolean} changed
*/
Item.prototype.show = function() {
return false;
};
/**
* Hide the Item from the DOM (when visible)
* @return {Boolean} changed
*/
Item.prototype.hide = function() {
return false;
};
/**
* Repaint the item
*/
Item.prototype.redraw = function() {
// should be implemented by the item
};
/**
* Reposition the Item horizontally
*/
Item.prototype.repositionX = function() {
// should be implemented by the item
};
/**
* Reposition the Item vertically
*/
Item.prototype.repositionY = function() {
// should be implemented by the item
};
/**
* Repaint a delete button on the top right of the item when the item is selected
* @param {HTMLElement} anchor
* @protected
*/
Item.prototype._repaintDeleteButton = function (anchor) {
if (this.selected && this.options.editable.remove && !this.dom.deleteButton) {
// create and show button
var me = this;
var deleteButton = document.createElement('div');
deleteButton.className = 'delete';
deleteButton.title = 'Delete this item';
Hammer(deleteButton, {
preventDefault: true
}).on('tap', function (event) {
event.preventDefault();
event.stopPropagation();
me.parent.removeFromDataSet(me);
});
anchor.appendChild(deleteButton);
this.dom.deleteButton = deleteButton;
}
else if (!this.selected && this.dom.deleteButton) {
// remove button
if (this.dom.deleteButton.parentNode) {
this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);
}
this.dom.deleteButton = null;
}
};
/**
* Set HTML contents for the item
* @param {Element} element HTML element to fill with the contents
* @private
*/
Item.prototype._updateContents = function (element) {
var content;
if (this.options.template) {
var itemData = this.parent.itemSet.itemsData.get(this.id); // get a clone of the data from the dataset
content = this.options.template(itemData);
}
else {
content = this.data.content;
}
if(content !== this.content) {
// only replace the content when changed
if (content instanceof Element) {
element.innerHTML = '';
element.appendChild(content);
}
else if (content != undefined) {
element.innerHTML = content;
}
else {
if (!(this.data.type == 'background' && this.data.content === undefined)) {
throw new Error('Property "content" missing in item ' + this.id);
}
}
this.content = content;
}
};
/**
* Set HTML contents for the item
* @param {Element} element HTML element to fill with the contents
* @private
*/
Item.prototype._updateTitle = function (element) {
if (this.data.title != null) {
element.title = this.data.title || '';
}
else {
element.removeAttribute('title');
}
};
/**
* Process dataAttributes timeline option and set as data- attributes on dom.content
* @param {Element} element HTML element to which the attributes will be attached
* @private
*/
Item.prototype._updateDataAttributes = function(element) {
if (this.options.dataAttributes && this.options.dataAttributes.length > 0) {
var attributes = [];
if (Array.isArray(this.options.dataAttributes)) {
attributes = this.options.dataAttributes;
}
else if (this.options.dataAttributes == 'all') {
attributes = Object.keys(this.data);
}
else {
return;
}
for (var i = 0; i < attributes.length; i++) {
var name = attributes[i];
var value = this.data[name];
if (value != null) {
element.setAttribute('data-' + name, value);
}
else {
element.removeAttribute('data-' + name);
}
}
}
};
/**
* Update custom styles of the element
* @param element
* @private
*/
Item.prototype._updateStyle = function(element) {
// remove old styles
if (this.style) {
util.removeCssText(element, this.style);
this.style = null;
}
// append new styles
if (this.data.style) {
util.addCssText(element, this.data.style);
this.style = this.data.style;
}
};
module.exports = Item;
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
var Hammer = __webpack_require__(45);
var Item = __webpack_require__(20);
var BackgroundGroup = __webpack_require__(31);
var RangeItem = __webpack_require__(24);
/**
* @constructor BackgroundItem
* @extends Item
* @param {Object} data Object containing parameters start, end
* content, className.
* @param {{toScreen: function, toTime: function}} conversion
* Conversion functions from time to screen and vice versa
* @param {Object} [options] Configuration options
* // TODO: describe options
*/
// TODO: implement support for the BackgroundItem just having a start, then being displayed as a sort of an annotation
function BackgroundItem (data, conversion, options) {
this.props = {
content: {
width: 0
}
};
this.overflow = false; // if contents can overflow (css styling), this flag is set to true
// validate data
if (data) {
if (data.start == undefined) {
throw new Error('Property "start" missing in item ' + data.id);
}
if (data.end == undefined) {
throw new Error('Property "end" missing in item ' + data.id);
}
}
Item.call(this, data, conversion, options);
this.emptyContent = false;
}
BackgroundItem.prototype = new Item (null, null, null);
BackgroundItem.prototype.baseClassName = 'item background';
BackgroundItem.prototype.stack = false;
/**
* Check whether this item is visible inside given range
* @returns {{start: Number, end: Number}} range with a timestamp for start and end
* @returns {boolean} True if visible
*/
BackgroundItem.prototype.isVisible = function(range) {
// determine visibility
return (this.data.start < range.end) && (this.data.end > range.start);
};
/**
* Repaint the item
*/
BackgroundItem.prototype.redraw = function() {
var dom = this.dom;
if (!dom) {
// create DOM
this.dom = {};
dom = this.dom;
// background box
dom.box = document.createElement('div');
// className is updated in redraw()
// contents box
dom.content = document.createElement('div');
dom.content.className = 'content';
dom.box.appendChild(dom.content);
// Note: we do NOT attach this item as attribute to the DOM,
// such that background items cannot be selected
//dom.box['timeline-item'] = this;
this.dirty = true;
}
// append DOM to parent DOM
if (!this.parent) {
throw new Error('Cannot redraw item: no parent attached');
}
if (!dom.box.parentNode) {
var background = this.parent.dom.background;
if (!background) {
throw new Error('Cannot redraw item: parent has no background container element');
}
background.appendChild(dom.box);
}
this.displayed = true;
// Update DOM when item is marked dirty. An item is marked dirty when:
// - the item is not yet rendered
// - the item's data is changed
// - the item is selected/deselected
if (this.dirty) {
this._updateContents(this.dom.content);
this._updateTitle(this.dom.content);
this._updateDataAttributes(this.dom.content);
this._updateStyle(this.dom.box);
// update class
var className = (this.data.className ? (' ' + this.data.className) : '') +
(this.selected ? ' selected' : '');
dom.box.className = this.baseClassName + className;
// determine from css whether this box has overflow
this.overflow = window.getComputedStyle(dom.content).overflow !== 'hidden';
// recalculate size
this.props.content.width = this.dom.content.offsetWidth;
this.height = 0; // set height zero, so this item will be ignored when stacking items
this.dirty = false;
}
};
/**
* Show the item in the DOM (when not already visible). The items DOM will
* be created when needed.
*/
BackgroundItem.prototype.show = RangeItem.prototype.show;
/**
* Hide the item from the DOM (when visible)
* @return {Boolean} changed
*/
BackgroundItem.prototype.hide = RangeItem.prototype.hide;
/**
* Reposition the item horizontally
* @Override
*/
BackgroundItem.prototype.repositionX = RangeItem.prototype.repositionX;
/**
* Reposition the item vertically
* @Override
*/
BackgroundItem.prototype.repositionY = function(margin) {
var onTop = this.options.orientation === 'top';
this.dom.content.style.top = onTop ? '' : '0';
this.dom.content.style.bottom = onTop ? '0' : '';
var height;
// special positioning for subgroups
if (this.data.subgroup !== undefined) {
// TODO: instead of calculating the top position of the subgroups here for every BackgroundItem, calculate the top of the subgroup once in Itemset
var itemSubgroup = this.data.subgroup;
var subgroups = this.parent.subgroups;
var subgroupIndex = subgroups[itemSubgroup].index;
// if the orientation is top, we need to take the difference in height into account.
if (onTop == true) {
// the first subgroup will have to account for the distance from the top to the first item.
height = this.parent.subgroups[itemSubgroup].height + margin.item.vertical;
height += subgroupIndex == 0 ? margin.axis - 0.5*margin.item.vertical : 0;
var newTop = this.parent.top;
for (var subgroup in subgroups) {
if (subgroups.hasOwnProperty(subgroup)) {
if (subgroups[subgroup].visible == true && subgroups[subgroup].index < subgroupIndex) {
newTop += subgroups[subgroup].height + margin.item.vertical;
}
}
}
// the others will have to be offset downwards with this same distance.
newTop += subgroupIndex != 0 ? margin.axis - 0.5 * margin.item.vertical : 0;
this.dom.box.style.top = newTop + 'px';
this.dom.box.style.bottom = '';
}
// and when the orientation is bottom:
else {
var newTop = this.parent.top;
var totalHeight = 0;
for (var subgroup in subgroups) {
if (subgroups.hasOwnProperty(subgroup)) {
if (subgroups[subgroup].visible == true) {
var newHeight = subgroups[subgroup].height + margin.item.vertical;
totalHeight += newHeight;
if (subgroups[subgroup].index > subgroupIndex) {
newTop += newHeight;
}
}
}
}
height = this.parent.subgroups[itemSubgroup].height + margin.item.vertical;
this.dom.box.style.top = (this.parent.height - totalHeight + newTop) + 'px';
this.dom.box.style.bottom = '';
}
}
// and in the case of no subgroups:
else {
// we want backgrounds with groups to only show in groups.
if (this.parent instanceof BackgroundGroup) {
// if the item is not in a group:
height = Math.max(this.parent.height,
this.parent.itemSet.body.domProps.center.height,
this.parent.itemSet.body.domProps.centerContainer.height);
this.dom.box.style.top = onTop ? '0' : '';
this.dom.box.style.bottom = onTop ? '' : '0';
}
else {
height = this.parent.height;
// same alignment for items when orientation is top or bottom
this.dom.box.style.top = this.parent.top + 'px';
this.dom.box.style.bottom = '';
}
}
this.dom.box.style.height = height + 'px';
};
module.exports = BackgroundItem;
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
var Item = __webpack_require__(20);
var util = __webpack_require__(1);
/**
* @constructor BoxItem
* @extends Item
* @param {Object} data Object containing parameters start
* content, className.
* @param {{toScreen: function, toTime: function}} conversion
* Conversion functions from time to screen and vice versa
* @param {Object} [options] Configuration options
* // TODO: describe available options
*/
function BoxItem (data, conversion, options) {
this.props = {
dot: {
width: 0,
height: 0
},
line: {
width: 0,
height: 0
}
};
// validate data
if (data) {
if (data.start == undefined) {
throw new Error('Property "start" missing in item ' + data);
}
}
Item.call(this, data, conversion, options);
}
BoxItem.prototype = new Item (null, null, null);
/**
* Check whether this item is visible inside given range
* @returns {{start: Number, end: Number}} range with a timestamp for start and end
* @returns {boolean} True if visible
*/
BoxItem.prototype.isVisible = function(range) {
// determine visibility
// TODO: account for the real width of the item. Right now we just add 1/4 to the window
var interval = (range.end - range.start) / 4;
return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
};
/**
* Repaint the item
*/
BoxItem.prototype.redraw = function() {
var dom = this.dom;
if (!dom) {
// create DOM
this.dom = {};
dom = this.dom;
// create main box
dom.box = document.createElement('DIV');
// contents box (inside the background box). used for making margins
dom.content = document.createElement('DIV');
dom.content.className = 'content';
dom.box.appendChild(dom.content);
// line to axis
dom.line = document.createElement('DIV');
dom.line.className = 'line';
// dot on axis
dom.dot = document.createElement('DIV');
dom.dot.className = 'dot';
// attach this item as attribute
dom.box['timeline-item'] = this;
this.dirty = true;
}
// append DOM to parent DOM
if (!this.parent) {
throw new Error('Cannot redraw item: no parent attached');
}
if (!dom.box.parentNode) {
var foreground = this.parent.dom.foreground;
if (!foreground) throw new Error('Cannot redraw item: parent has no foreground container element');
foreground.appendChild(dom.box);
}
if (!dom.line.parentNode) {
var background = this.parent.dom.background;
if (!background) throw new Error('Cannot redraw item: parent has no background container element');
background.appendChild(dom.line);
}
if (!dom.dot.parentNode) {
var axis = this.parent.dom.axis;
if (!background) throw new Error('Cannot redraw item: parent has no axis container element');
axis.appendChild(dom.dot);
}
this.displayed = true;
// Update DOM when item is marked dirty. An item is marked dirty when:
// - the item is not yet rendered
// - the item's data is changed
// - the item is selected/deselected
if (this.dirty) {
this._updateContents(this.dom.content);
this._updateTitle(this.dom.box);
this._updateDataAttributes(this.dom.box);
this._updateStyle(this.dom.box);
// update class
var className = (this.data.className? ' ' + this.data.className : '') +
(this.selected ? ' selected' : '');
dom.box.className = 'item box' + className;
dom.line.className = 'item line' + className;
dom.dot.className = 'item dot' + className;
// recalculate size
this.props.dot.height = dom.dot.offsetHeight;
this.props.dot.width = dom.dot.offsetWidth;
this.props.line.width = dom.line.offsetWidth;
this.width = dom.box.offsetWidth;
this.height = dom.box.offsetHeight;
this.dirty = false;
}
this._repaintDeleteButton(dom.box);
};
/**
* Show the item in the DOM (when not already displayed). The items DOM will
* be created when needed.
*/
BoxItem.prototype.show = function() {
if (!this.displayed) {
this.redraw();
}
};
/**
* Hide the item from the DOM (when visible)
*/
BoxItem.prototype.hide = function() {
if (this.displayed) {
var dom = this.dom;
if (dom.box.parentNode) dom.box.parentNode.removeChild(dom.box);
if (dom.line.parentNode) dom.line.parentNode.removeChild(dom.line);
if (dom.dot.parentNode) dom.dot.parentNode.removeChild(dom.dot);
this.displayed = false;
}
};
/**
* Reposition the item horizontally
* @Override
*/
BoxItem.prototype.repositionX = function() {
var start = this.conversion.toScreen(this.data.start);
var align = this.options.align;
var left;
// calculate left position of the box
if (align == 'right') {
this.left = start - this.width;
}
else if (align == 'left') {
this.left = start;
}
else {
// default or 'center'
this.left = start - this.width / 2;
}
// reposition box
this.dom.box.style.left = this.left + 'px';
// reposition line
this.dom.line.style.left = (start - this.props.line.width / 2) + 'px';
// reposition dot
this.dom.dot.style.left = (start - this.props.dot.width / 2) + 'px';
};
/**
* Reposition the item vertically
* @Override
*/
BoxItem.prototype.repositionY = function() {
var orientation = this.options.orientation;
var box = this.dom.box;
var line = this.dom.line;
var dot = this.dom.dot;
if (orientation == 'top') {
box.style.top = (this.top || 0) + 'px';
line.style.top = '0';
line.style.height = (this.parent.top + this.top + 1) + 'px';
line.style.bottom = '';
}
else { // orientation 'bottom'
var itemSetHeight = this.parent.itemSet.props.height; // TODO: this is nasty
var lineHeight = itemSetHeight - this.parent.top - this.parent.height + this.top;
box.style.top = (this.parent.height - this.top - this.height || 0) + 'px';
line.style.top = (itemSetHeight - lineHeight) + 'px';
line.style.bottom = '0';
}
dot.style.top = (-this.props.dot.height / 2) + 'px';
};
module.exports = BoxItem;
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
var Item = __webpack_require__(20);
/**
* @constructor PointItem
* @extends Item
* @param {Object} data Object containing parameters start
* content, className.
* @param {{toScreen: function, toTime: function}} conversion
* Conversion functions from time to screen and vice versa
* @param {Object} [options] Configuration options
* // TODO: describe available options
*/
function PointItem (data, conversion, options) {
this.props = {
dot: {
top: 0,
width: 0,
height: 0
},
content: {
height: 0,
marginLeft: 0
}
};
// validate data
if (data) {
if (data.start == undefined) {
throw new Error('Property "start" missing in item ' + data);
}
}
Item.call(this, data, conversion, options);
}
PointItem.prototype = new Item (null, null, null);
/**
* Check whether this item is visible inside given range
* @returns {{start: Number, end: Number}} range with a timestamp for start and end
* @returns {boolean} True if visible
*/
PointItem.prototype.isVisible = function(range) {
// determine visibility
// TODO: account for the real width of the item. Right now we just add 1/4 to the window
var interval = (range.end - range.start) / 4;
return (this.data.start > range.start - interval) && (this.data.start < range.end + interval);
};
/**
* Repaint the item
*/
PointItem.prototype.redraw = function() {
var dom = this.dom;
if (!dom) {
// create DOM
this.dom = {};
dom = this.dom;
// background box
dom.point = document.createElement('div');
// className is updated in redraw()
// contents box, right from the dot
dom.content = document.createElement('div');
dom.content.className = 'content';
dom.point.appendChild(dom.content);
// dot at start
dom.dot = document.createElement('div');
dom.point.appendChild(dom.dot);
// attach this item as attribute
dom.point['timeline-item'] = this;
this.dirty = true;
}
// append DOM to parent DOM
if (!this.parent) {
throw new Error('Cannot redraw item: no parent attached');
}
if (!dom.point.parentNode) {
var foreground = this.parent.dom.foreground;
if (!foreground) {
throw new Error('Cannot redraw item: parent has no foreground container element');
}
foreground.appendChild(dom.point);
}
this.displayed = true;
// Update DOM when item is marked dirty. An item is marked dirty when:
// - the item is not yet rendered
// - the item's data is changed
// - the item is selected/deselected
if (this.dirty) {
this._updateContents(this.dom.content);
this._updateTitle(this.dom.point);
this._updateDataAttributes(this.dom.point);
this._updateStyle(this.dom.point);
// update class
var className = (this.data.className? ' ' + this.data.className : '') +
(this.selected ? ' selected' : '');
dom.point.className = 'item point' + className;
dom.dot.className = 'item dot' + className;
// recalculate size
this.width = dom.point.offsetWidth;
this.height = dom.point.offsetHeight;
this.props.dot.width = dom.dot.offsetWidth;
this.props.dot.height = dom.dot.offsetHeight;
this.props.content.height = dom.content.offsetHeight;
// resize contents
dom.content.style.marginLeft = 2 * this.props.dot.width + 'px';
//dom.content.style.marginRight = ... + 'px'; // TODO: margin right
dom.dot.style.top = ((this.height - this.props.dot.height) / 2) + 'px';
dom.dot.style.left = (this.props.dot.width / 2) + 'px';
this.dirty = false;
}
this._repaintDeleteButton(dom.point);
};
/**
* Show the item in the DOM (when not already visible). The items DOM will
* be created when needed.
*/
PointItem.prototype.show = function() {
if (!this.displayed) {
this.redraw();
}
};
/**
* Hide the item from the DOM (when visible)
*/
PointItem.prototype.hide = function() {
if (this.displayed) {
if (this.dom.point.parentNode) {
this.dom.point.parentNode.removeChild(this.dom.point);
}
this.displayed = false;
}
};
/**
* Reposition the item horizontally
* @Override
*/
PointItem.prototype.repositionX = function() {
var start = this.conversion.toScreen(this.data.start);
this.left = start - this.props.dot.width;
// reposition point
this.dom.point.style.left = this.left + 'px';
};
/**
* Reposition the item vertically
* @Override
*/
PointItem.prototype.repositionY = function() {
var orientation = this.options.orientation,
point = this.dom.point;
if (orientation == 'top') {
point.style.top = this.top + 'px';
}
else {
point.style.top = (this.parent.height - this.top - this.height) + 'px';
}
};
module.exports = PointItem;
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
var Hammer = __webpack_require__(45);
var Item = __webpack_require__(20);
/**
* @constructor RangeItem
* @extends Item
* @param {Object} data Object containing parameters start, end
* content, className.
* @param {{toScreen: function, toTime: function}} conversion
* Conversion functions from time to screen and vice versa
* @param {Object} [options] Configuration options
* // TODO: describe options
*/
function RangeItem (data, conversion, options) {
this.props = {
content: {
width: 0
}
};
this.overflow = false; // if contents can overflow (css styling), this flag is set to true
// validate data
if (data) {
if (data.start == undefined) {
throw new Error('Property "start" missing in item ' + data.id);
}
if (data.end == undefined) {
throw new Error('Property "end" missing in item ' + data.id);
}
}
Item.call(this, data, conversion, options);
}
RangeItem.prototype = new Item (null, null, null);
RangeItem.prototype.baseClassName = 'item range';
/**
* Check whether this item is visible inside given range
* @returns {{start: Number, end: Number}} range with a timestamp for start and end
* @returns {boolean} True if visible
*/
RangeItem.prototype.isVisible = function(range) {
// determine visibility
return (this.data.start < range.end) && (this.data.end > range.start);
};
/**
* Repaint the item
*/
RangeItem.prototype.redraw = function() {
var dom = this.dom;
if (!dom) {
// create DOM
this.dom = {};
dom = this.dom;
// background box
dom.box = document.createElement('div');
// className is updated in redraw()
// contents box
dom.content = document.createElement('div');
dom.content.className = 'content';
dom.box.appendChild(dom.content);
// attach this item as attribute
dom.box['timeline-item'] = this;
this.dirty = true;
}
// append DOM to parent DOM
if (!this.parent) {
throw new Error('Cannot redraw item: no parent attached');
}
if (!dom.box.parentNode) {
var foreground = this.parent.dom.foreground;
if (!foreground) {
throw new Error('Cannot redraw item: parent has no foreground container element');
}
foreground.appendChild(dom.box);
}
this.displayed = true;
// Update DOM when item is marked dirty. An item is marked dirty when:
// - the item is not yet rendered
// - the item's data is changed
// - the item is selected/deselected
if (this.dirty) {
this._updateContents(this.dom.content);
this._updateTitle(this.dom.box);
this._updateDataAttributes(this.dom.box);
this._updateStyle(this.dom.box);
// update class
var className = (this.data.className ? (' ' + this.data.className) : '') +
(this.selected ? ' selected' : '');
dom.box.className = this.baseClassName + className;
// determine from css whether this box has overflow
this.overflow = window.getComputedStyle(dom.content).overflow !== 'hidden';
// recalculate size
// turn off max-width to be able to calculate the real width
// this causes an extra browser repaint/reflow, but so be it
this.dom.content.style.maxWidth = 'none';
this.props.content.width = this.dom.content.offsetWidth;
this.height = this.dom.box.offsetHeight;
this.dom.content.style.maxWidth = '';
this.dirty = false;
}
this._repaintDeleteButton(dom.box);
this._repaintDragLeft();
this._repaintDragRight();
};
/**
* Show the item in the DOM (when not already visible). The items DOM will
* be created when needed.
*/
RangeItem.prototype.show = function() {
if (!this.displayed) {
this.redraw();
}
};
/**
* Hide the item from the DOM (when visible)
* @return {Boolean} changed
*/
RangeItem.prototype.hide = function() {
if (this.displayed) {
var box = this.dom.box;
if (box.parentNode) {
box.parentNode.removeChild(box);
}
this.displayed = false;
}
};
/**
* Reposition the item horizontally
* @param {boolean} [limitSize=true] If true (default), the width of the range
* item will be limited, as the browser cannot
* display very wide divs. This means though
* that the applied left and width may
* not correspond to the ranges start and end
* @Override
*/
RangeItem.prototype.repositionX = function(limitSize) {
var parentWidth = this.parent.width;
var start = this.conversion.toScreen(this.data.start);
var end = this.conversion.toScreen(this.data.end);
var contentLeft;
var contentWidth;
// limit the width of the range, as browsers cannot draw very wide divs
if (limitSize === undefined || limitSize === true) {
if (start < -parentWidth) {
start = -parentWidth;
}
if (end > 2 * parentWidth) {
end = 2 * parentWidth;
}
}
var boxWidth = Math.max(end - start, 1);
if (this.overflow) {
this.left = start;
this.width = boxWidth + this.props.content.width;
contentWidth = this.props.content.width;
// Note: The calculation of width is an optimistic calculation, giving
// a width which will not change when moving the Timeline
// So no re-stacking needed, which is nicer for the eye;
}
else {
this.left = start;
this.width = boxWidth;
contentWidth = Math.min(end - start - 2 * this.options.padding, this.props.content.width);
}
this.dom.box.style.left = this.left + 'px';
this.dom.box.style.width = boxWidth + 'px';
switch (this.options.align) {
case 'left':
this.dom.content.style.left = '0';
break;
case 'right':
this.dom.content.style.left = Math.max((boxWidth - contentWidth - 2 * this.options.padding), 0) + 'px';
break;
case 'center':
this.dom.content.style.left = Math.max((boxWidth - contentWidth - 2 * this.options.padding) / 2, 0) + 'px';
break;
default: // 'auto'
// when range exceeds left of the window, position the contents at the left of the visible area
if (this.overflow) {
if (end > 0) {
contentLeft = Math.max(-start, 0);
}
else {
contentLeft = -contentWidth; // ensure it's not visible anymore
}
}
else {
if (start < 0) {
contentLeft = Math.min(-start,
(end - start - contentWidth - 2 * this.options.padding));
// TODO: remove the need for options.padding. it's terrible.
}
else {
contentLeft = 0;
}
}
this.dom.content.style.left = contentLeft + 'px';
}
};
/**
* Reposition the item vertically
* @Override
*/
RangeItem.prototype.repositionY = function() {
var orientation = this.options.orientation,
box = this.dom.box;
if (orientation == 'top') {
box.style.top = this.top + 'px';
}
else {
box.style.top = (this.parent.height - this.top - this.height) + 'px';
}
};
/**
* Repaint a drag area on the left side of the range when the range is selected
* @protected
*/
RangeItem.prototype._repaintDragLeft = function () {
if (this.selected && this.options.editable.updateTime && !this.dom.dragLeft) {
// create and show drag area
var dragLeft = document.createElement('div');
dragLeft.className = 'drag-left';
dragLeft.dragLeftItem = this;
// TODO: this should be redundant?
Hammer(dragLeft, {
preventDefault: true
}).on('drag', function () {
//console.log('drag left')
});
this.dom.box.appendChild(dragLeft);
this.dom.dragLeft = dragLeft;
}
else if (!this.selected && this.dom.dragLeft) {
// delete drag area
if (this.dom.dragLeft.parentNode) {
this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);
}
this.dom.dragLeft = null;
}
};
/**
* Repaint a drag area on the right side of the range when the range is selected
* @protected
*/
RangeItem.prototype._repaintDragRight = function () {
if (this.selected && this.options.editable.updateTime && !this.dom.dragRight) {
// create and show drag area
var dragRight = document.createElement('div');
dragRight.className = 'drag-right';
dragRight.dragRightItem = this;
// TODO: this should be redundant?
Hammer(dragRight, {
preventDefault: true
}).on('drag', function () {
//console.log('drag right')
});
this.dom.box.appendChild(dragRight);
this.dom.dragRight = dragRight;
}
else if (!this.selected && this.dom.dragRight) {
// delete drag area
if (this.dom.dragRight.parentNode) {
this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);
}
this.dom.dragRight = null;
}
};
module.exports = RangeItem;
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
/**
* Prototype for visual components
* @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} [body]
* @param {Object} [options]
*/
function Component (body, options) {
this.options = null;
this.props = null;
}
/**
* Set options for the component. The new options will be merged into the
* current options.
* @param {Object} options
*/
Component.prototype.setOptions = function(options) {
if (options) {
util.extend(this.options, options);
}
};
/**
* Repaint the component
* @return {boolean} Returns true if the component is resized
*/
Component.prototype.redraw = function() {
// should be implemented by the component
return false;
};
/**
* Destroy the component. Cleanup DOM and event listeners
*/
Component.prototype.destroy = function() {
// should be implemented by the component
};
/**
* Test whether the component is resized since the last time _isResized() was
* called.
* @return {Boolean} Returns true if the component is resized
* @protected
*/
Component.prototype._isResized = function() {
var resized = (this.props._previousWidth !== this.props.width ||
this.props._previousHeight !== this.props.height);
this.props._previousWidth = this.props.width;
this.props._previousHeight = this.props.height;
return resized;
};
module.exports = Component;
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
var util = __webpack_require__(1);
var Component = __webpack_require__(25);
var moment = __webpack_require__(44);
var locales = __webpack_require__(48);
/**
* A current time bar
* @param {{range: Range, dom: Object, domProps: Object}} body
* @param {Object} [options] Available parameters:
* {Boolean} [showCurrentTime]
* @constructor CurrentTime
* @extends Component
*/
function CurrentTime (body, options) {
this.body = body;
// default options
this.defaultOptions = {
showCurrentTime: true,
locales: locales,
locale: 'en'
};
this.options = util.extend({}, this.defaultOptions);
this.offset = 0;
this._create();
this.setOptions(options);
}
CurrentTime.prototype = new Component();
/**
* Create the HTML DOM for the current time bar
* @private
*/
CurrentTime.prototype._create = function() {
var bar = document.createElement('div');
bar.className = 'currenttime';
bar.style.position = 'absolute';
bar.style.top = '0px';
bar.style.height = '100%';
this.bar = bar;
};
/**
* Destroy the CurrentTime bar
*/
CurrentTime.prototype.destroy = function () {
this.options.showCurrentTime = false;
this.redraw(); // will remove the bar from the DOM and stop refreshing
this.body = null;
};
/**
* Set options for the component. Options will be merged in current options.
* @param {Object} options Available parameters:
* {boolean} [showCurrentTime]
*/
CurrentTime.prototype.setOptions = function(options) {
if (options) {
// copy all options that we know
util.selectiveExtend(['showCurrentTime', 'locale', 'locales'], this.options, options);
}
};
/**
* Repaint the component
* @return {boolean} Returns true if the component is resized
*/
CurrentTime.prototype.redraw = function() {
if (this.options.showCurrentTime) {
var parent = this.body.dom.backgroundVertical;
if (this.bar.parentNode != parent) {
// attach to the dom
if (this.bar.parentNode) {
this.bar.parentNode.removeChild(this.bar);
}
parent.appendChild(this.bar);
this.start();
}
var now = new Date(new Date().valueOf() + this.offset);
var x = this.body.util.toScreen(now);
var locale = this.options.locales[this.options.locale];
var title = locale.current + ' ' + locale.time + ': ' + moment(now).format('dddd, MMMM Do YYYY, H:mm:ss');
title = title.charAt(0).toUpperCase() + title.substring(1);
this.bar.style.left = x + 'px';
this.bar.title = title;
}
else {
// remove the line from the DOM
if (this.bar.parentNode) {
this.bar.parentNode.removeChild(this.bar);
}
this.stop();
}
return false;
};
/**
* Start auto refreshing the current time bar
*/
CurrentTime.prototype.start = function() {
var me = this;
function update () {
me.stop();
// determine interval to refresh
var scale = me.body.range.conversion(me.body.domProps.center.width).scale;
var interval = 1 / scale / 10;
if (interval < 30) interval = 30;
if (interval > 1000) interval = 1000;
me.redraw();
// start a timer to adjust for the new time
me.currentTimeTimer = setTimeout(update, interval);
}
update();
};
/**
* Stop auto refreshing the current time bar
*/
CurrentTime.prototype.stop = function() {
if (this.currentTimeTimer !== undefined) {
clearTimeout(this.currentTimeTimer);
delete this.currentTimeTimer;
}
};
/**
* Set a current time. This can be used for example to ensure that a client's
* time is synchronized with a shared server time.
* @param {Date | String | Number} time A Date, unix timestamp, or
* ISO date string.
*/
CurrentTime.prototype.setCurrentTime = function(time) {
var t = util.convert(time, 'Date').valueOf();
var now = new Date().valueOf();
this.offset = t - now;
this.redraw();
};
/**
* Get the current time.
* @return {Date} Returns the current time.
*/
CurrentTime.prototype.getCurrentTime = function() {
return new Date(new Date().valueOf() + this.offset);
};
module.exports = CurrentTime;
/***/ },
/* 27 */
/***/ function(module, exports, __webpack_require__) {
var Hammer = __webpack_require__(45);
var util = __webpack_require__(1);
var Component = __webpack_require__(25);
var moment = __webpack_require__(44);
var locales = __webpack_require__(48);
/**
* A custom time bar
* @param {{range: Range, dom: Object}} body
* @param {Object} [options] Available parameters:
* {Boolean} [showCustomTime]
* @constructor CustomTime
* @extends Component
*/
function CustomTime (body, options) {
this.body = body;
// default options
this.defaultOptions = {
showCustomTime: false,
locales: locales,
locale: 'en',
id: 0
};
this.options = util.extend({}, this.defaultOptions);
if (options && options.time) {
this.customTime = options.time;
} else {
this.customTime = new Date();
}
this.eventParams = {}; // stores state parameters while dragging the bar
// create the DOM
this._create();
this.setOptions(options);
}
CustomTime.prototype = new Component();
/**
* Set options for the component. Options will be merged in current options.
* @param {Object} options Available parameters:
* {boolean} [showCustomTime]
*/
CustomTime.prototype.setOptions = function(options) {
if (options) {
// copy all options that we know
util.selectiveExtend(['showCustomTime', 'locale', 'locales', 'id'], this.options, options);
// Triggered by addCustomTimeBar, redraw to add new bar
if (this.options.id) {
this.redraw();
}
}
};
/**
* Create the DOM for the custom time
* @private
*/
CustomTime.prototype._create = function() {
var bar = document.createElement('div');
bar.className = 'customtime';
bar.style.position = 'absolute';
bar.style.top = '0px';
bar.style.height = '100%';
this.bar = bar;
var drag = document.createElement('div');
drag.style.position = 'relative';
drag.style.top = '0px';
drag.style.left = '-10px';
drag.style.height = '100%';
drag.style.width = '20px';
bar.appendChild(drag);
// attach event listeners
this.hammer = Hammer(bar, {
prevent_default: true
});
this.hammer.on('dragstart', this._onDragStart.bind(this));
this.hammer.on('drag', this._onDrag.bind(this));
this.hammer.on('dragend', this._onDragEnd.bind(this));
};
/**
* Destroy the CustomTime bar
*/
CustomTime.prototype.destroy = function () {
this.options.showCustomTime = false;
this.redraw(); // will remove the bar from the DOM
this.hammer.enable(false);
this.hammer = null;
this.body = null;
};
/**
* Repaint the component
* @return {boolean} Returns true if the component is resized
*/
CustomTime.prototype.redraw = function () {
if (this.options.showCustomTime) {
var parent = this.body.dom.backgroundVertical;
if (this.bar.parentNode != parent) {
// attach to the dom
if (this.bar.parentNode) {
this.bar.parentNode.removeChild(this.bar);
}
parent.appendChild(this.bar);
}
var x = this.body.util.toScreen(this.customTime);
var locale = this.options.locales[this.options.locale];
var title = locale.time + ': ' + moment(this.customTime).format('dddd, MMMM Do YYYY, H:mm:ss');
title = title.charAt(0).toUpperCase() + title.substring(1);
this.bar.style.left = x + 'px';
this.bar.title = title;
}
else {
// remove the line from the DOM
if (this.bar.parentNode) {
this.bar.parentNode.removeChild(this.bar);
}
}
return false;
};
/**
* Set custom time.
* @param {Date | number | string} time
*/
CustomTime.prototype.setCustomTime = function(time) {
this.customTime = util.convert(time, 'Date');
this.redraw();
};
/**
* Retrieve the current custom time.
* @return {Date} customTime
*/
CustomTime.prototype.getCustomTime = function() {
return new Date(this.customTime.valueOf());
};
/**
* Start moving horizontally
* @param {Event} event
* @private
*/
CustomTime.prototype._onDragStart = function(event) {
this.eventParams.dragging = true;
this.eventParams.customTime = this.customTime;
event.stopPropagation();
event.preventDefault();
};
/**
* Perform moving operating.
* @param {Event} event
* @private
*/
CustomTime.prototype._onDrag = function (event) {
if (!this.eventParams.dragging) return;
var deltaX = event.gesture.deltaX,
x = this.body.util.toScreen(this.eventParams.customTime) + deltaX,
time = this.body.util.toTime(x);
this.setCustomTime(time);
// fire a timechange event
this.body.emitter.emit('timechange', {
id: this.options.id,
time: new Date(this.customTime.valueOf())
});
event.stopPropagation();
event.preventDefault();
};
/**
* Stop moving operating.
* @param {event} event
* @private
*/
CustomTime.prototype._onDragEnd = function (event) {
if (!this.eventParams.dragging) return;
// fire a timechanged event
this.body.emitter.emit('timechanged', {
id: this.options.id,
time: new Date(this.customTime.valueOf())
});
event.stopPropagation();
event.preventDefault();
};
module.exports = CustomTime;
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
var util = __webpack_require__(1);
var DOMutil = __webpack_require__(2);
var Component = __webpack_require__(25);
var DataStep = __webpack_require__(16);
/**
* A horizontal time axis
* @param {Object} [options] See DataAxis.setOptions for the available
* options.
* @constructor DataAxis
* @extends Component
* @param body
*/
function DataAxis (body, options, svg, linegraphOptions) {
this.id = util.randomUUID();
this.body = body;
this.defaultOptions = {
orientation: 'left', // supported: 'left', 'right'
showMinorLabels: true,
showMajorLabels: true,
icons: true,
majorLinesOffset: 7,
minorLinesOffset: 4,
labelOffsetX: 10,
labelOffsetY: 2,
iconWidth: 20,
width: '40px',
visible: true,
alignZeros: true,
customRange: {
left: {min:undefined, max:undefined},
right: {min:undefined, max:undefined}
},
title: {
left: {text:undefined},
right: {text:undefined}
},
format: {
left: {decimals: undefined},
right: {decimals: undefined}
}
};
this.linegraphOptions = linegraphOptions;
this.linegraphSVG = svg;
this.props = {};
this.DOMelements = { // dynamic elements
lines: {},
labels: {},
title: {}
};
this.dom = {};
this.range = {start:0, end:0};
this.options = util.extend({}, this.defaultOptions);
this.conversionFactor = 1;
this.setOptions(options);
this.width = Number(('' + this.options.width).replace("px",""));
this.minWidth = this.width;
this.height = this.linegraphSVG.offsetHeight;
this.hidden = false;
this.stepPixels = 25;
this.stepPixelsForced = 25;
this.zeroCrossing = -1;
this.lineOffset = 0;
this.master = true;
this.svgElements = {};
this.iconsRemoved = false;
this.groups = {};
this.amountOfGroups = 0;
// create the HTML DOM
this._create();
var me = this;
this.body.emitter.on("verticalDrag", function() {
me.dom.lineContainer.style.top = me.body.domProps.scrollTop + 'px';
});
}
DataAxis.prototype = new Component();
DataAxis.prototype.addGroup = function(label, graphOptions) {
if (!this.groups.hasOwnProperty(label)) {
this.groups[label] = graphOptions;
}
this.amountOfGroups += 1;
};
DataAxis.prototype.updateGroup = function(label, graphOptions) {
this.groups[label] = graphOptions;
};
DataAxis.prototype.removeGroup = function(label) {
if (this.groups.hasOwnProperty(label)) {
delete this.groups[label];
this.amountOfGroups -= 1;
}
};
DataAxis.prototype.setOptions = function (options) {
if (options) {
var redraw = false;
if (this.options.orientation != options.orientation && options.orientation !== undefined) {
redraw = true;
}
var fields = [
'orientation',
'showMinorLabels',
'showMajorLabels',
'icons',
'majorLinesOffset',
'minorLinesOffset',
'labelOffsetX',
'labelOffsetY',
'iconWidth',
'width',
'visible',
'customRange',
'title',
'format',
'alignZeros'
];
util.selectiveExtend(fields, this.options, options);
this.minWidth = Number(('' + this.options.width).replace("px",""));
if (redraw == true && this.dom.frame) {
this.hide();
this.show();
}
}
};
/**
* Create the HTML DOM for the DataAxis
*/
DataAxis.prototype._create = function() {
this.dom.frame = document.createElement('div');
this.dom.frame.style.width = this.options.width;
this.dom.frame.style.height = this.height;
this.dom.lineContainer = document.createElement('div');
this.dom.lineContainer.style.width = '100%';
this.dom.lineContainer.style.height = this.height;
this.dom.lineContainer.style.position = 'relative';
// create svg element for graph drawing.
this.svg = document.createElementNS('http://www.w3.org/2000/svg',"svg");
this.svg.style.position = "absolute";
this.svg.style.top = '0px';
this.svg.style.height = '100%';
this.svg.style.width = '100%';
this.svg.style.display = "block";
this.dom.frame.appendChild(this.svg);
};
DataAxis.prototype._redrawGroupIcons = function () {
DOMutil.prepareElements(this.svgElements);
var x;
var iconWidth = this.options.iconWidth;
var iconHeight = 15;
var iconOffset = 4;
var y = iconOffset + 0.5 * iconHeight;
if (this.options.orientation == 'left') {
x = iconOffset;
}
else {
x = this.width - iconWidth - iconOffset;
}
for (var groupId in this.groups) {
if (this.groups.hasOwnProperty(groupId)) {
if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
this.groups[groupId].drawIcon(x, y, this.svgElements, this.svg, iconWidth, iconHeight);
y += iconHeight + iconOffset;
}
}
}
DOMutil.cleanupElements(this.svgElements);
this.iconsRemoved = false;
};
DataAxis.prototype._cleanupIcons = function() {
if (this.iconsRemoved == false) {
DOMutil.prepareElements(this.svgElements);
DOMutil.cleanupElements(this.svgElements);
this.iconsRemoved = true;
}
}
/**
* Create the HTML DOM for the DataAxis
*/
DataAxis.prototype.show = function() {
this.hidden = false;
if (!this.dom.frame.parentNode) {
if (this.options.orientation == 'left') {
this.body.dom.left.appendChild(this.dom.frame);
}
else {
this.body.dom.right.appendChild(this.dom.frame);
}
}
if (!this.dom.lineContainer.parentNode) {
this.body.dom.backgroundHorizontal.appendChild(this.dom.lineContainer);
}
};
/**
* Create the HTML DOM for the DataAxis
*/
DataAxis.prototype.hide = function() {
this.hidden = true;
if (this.dom.frame.parentNode) {
this.dom.frame.parentNode.removeChild(this.dom.frame);
}
if (this.dom.lineContainer.parentNode) {
this.dom.lineContainer.parentNode.removeChild(this.dom.lineContainer);
}
};
/**
* Set a range (start and end)
* @param end
* @param start
* @param end
*/
DataAxis.prototype.setRange = function (start, end) {
if (this.master == false && this.options.alignZeros == true && this.zeroCrossing != -1) {
if (start > 0) {
start = 0;
}
}
this.range.start = start;
this.range.end = end;
};
/**
* Repaint the component
* @return {boolean} Returns true if the component is resized
*/
DataAxis.prototype.redraw = function () {
var resized = false;
var activeGroups = 0;
// Make sure the line container adheres to the vertical scrolling.
this.dom.lineContainer.style.top = this.body.domProps.scrollTop + 'px';
for (var groupId in this.groups) {
if (this.groups.hasOwnProperty(groupId)) {
if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
activeGroups++;
}
}
}
if (this.amountOfGroups == 0 || activeGroups == 0) {
this.hide();
}
else {
this.show();
this.height = Number(this.linegraphSVG.style.height.replace("px",""));
// svg offsetheight did not work in firefox and explorer...
this.dom.lineContainer.style.height = this.height + 'px';
this.width = this.options.visible == true ? Number(('' + this.options.width).replace("px","")) : 0;
var props = this.props;
var frame = this.dom.frame;
// update classname
frame.className = 'dataaxis';
// calculate character width and height
this._calculateCharSize();
var orientation = this.options.orientation;
var showMinorLabels = this.options.showMinorLabels;
var showMajorLabels = this.options.showMajorLabels;
// determine the width and height of the elements for the axis
props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
props.minorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.minorLinesOffset;
props.minorLineHeight = 1;
props.majorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.majorLinesOffset;
props.majorLineHeight = 1;
// take frame offline while updating (is almost twice as fast)
if (orientation == 'left') {
frame.style.top = '0';
frame.style.left = '0';
frame.style.bottom = '';
frame.style.width = this.width + 'px';
frame.style.height = this.height + "px";
this.props.width = this.body.domProps.left.width;
this.props.height = this.body.domProps.left.height;
}
else { // right
frame.style.top = '';
frame.style.bottom = '0';
frame.style.left = '0';
frame.style.width = this.width + 'px';
frame.style.height = this.height + "px";
this.props.width = this.body.domProps.right.width;
this.props.height = this.body.domProps.right.height;
}
resized = this._redrawLabels();
resized = this._isResized() || resized;
if (this.options.icons == true) {
this._redrawGroupIcons();
}
else {
this._cleanupIcons();
}
this._redrawTitle(orientation);
}
return resized;
};
/**
* Repaint major and minor text labels and vertical grid lines
* @private
*/
DataAxis.prototype._redrawLabels = function () {
var resized = false;
DOMutil.prepareElements(this.DOMelements.lines);
DOMutil.prepareElements(this.DOMelements.labels);
var orientation = this.options['orientation'];
// calculate range and step (step such that we have space for 7 characters per label)
var minimumStep = this.master ? this.props.majorCharHeight || 10 : this.stepPixelsForced;
var step = new DataStep(
this.range.start,
this.range.end,
minimumStep,
this.dom.frame.offsetHeight,
this.options.customRange[this.options.orientation],
this.master == false && this.options.alignZeros // doess the step have to align zeros? only if not master and the options is on
);
this.step = step;
// get the distance in pixels for a step
// dead space is space that is "left over" after a step
var stepPixels = (this.dom.frame.offsetHeight - (step.deadSpace * (this.dom.frame.offsetHeight / step.marginRange))) / (((step.marginRange - step.deadSpace) / step.step));
this.stepPixels = stepPixels;
var amountOfSteps = this.height / stepPixels;
var stepDifference = 0;
// the slave axis needs to use the same horizontal lines as the master axis.
if (this.master == false) {
stepPixels = this.stepPixelsForced;
stepDifference = Math.round((this.dom.frame.offsetHeight / stepPixels) - amountOfSteps);
for (var i = 0; i < 0.5 * stepDifference; i++) {
step.previous();
}
amountOfSteps = this.height / stepPixels;
if (this.zeroCrossing != -1 && this.options.alignZeros == true) {
var zeroStepDifference = (step.marginEnd / step.step) - this.zeroCrossing;
if (zeroStepDifference > 0) {
for (var i = 0; i < zeroStepDifference; i++) {step.next();}
}
else if (zeroStepDifference < 0) {
for (var i = 0; i < -zeroStepDifference; i++) {step.previous();}
}
}
}
else {
amountOfSteps += 0.25;
}
this.valueAtZero = step.marginEnd;
var marginStartPos = 0;
// do not draw the first label
var max = 1;
// Get the number of decimal places
var decimals;
if(this.options.format[orientation] !== undefined) {
decimals = this.options.format[orientation].decimals;
}
this.maxLabelSize = 0;
var y = 0;
while (max < Math.round(amountOfSteps)) {
step.next();
y = Math.round(max * stepPixels);
marginStartPos = max * stepPixels;
var isMajor = step.isMajor();
if (this.options['showMinorLabels'] && isMajor == false || this.master == false && this.options['showMinorLabels'] == true) {
this._redrawLabel(y - 2, step.getCurrent(decimals), orientation, 'yAxis minor', this.props.minorCharHeight);
}
if (isMajor && this.options['showMajorLabels'] && this.master == true ||
this.options['showMinorLabels'] == false && this.master == false && isMajor == true) {
if (y >= 0) {
this._redrawLabel(y - 2, step.getCurrent(decimals), orientation, 'yAxis major', this.props.majorCharHeight);
}
this._redrawLine(y, orientation, 'grid horizontal major', this.options.majorLinesOffset, this.props.majorLineWidth);
}
else {
this._redrawLine(y, orientation, 'grid horizontal minor', this.options.minorLinesOffset, this.props.minorLineWidth);
}
if (this.master == true && step.current == 0) {
this.zeroCrossing = max;
}
max++;
}
if (this.master == false) {
this.conversionFactor = y / (this.valueAtZero - step.current);
}
else {
this.conversionFactor = this.dom.frame.offsetHeight / step.marginRange;
}
// Note that title is rotated, so we're using the height, not width!
var titleWidth = 0;
if (this.options.title[orientation] !== undefined && this.options.title[orientation].text !== undefined) {
titleWidth = this.props.titleCharHeight;
}
var offset = this.options.icons == true ? Math.max(this.options.iconWidth, titleWidth) + this.options.labelOffsetX + 15 : titleWidth + this.options.labelOffsetX + 15;
// this will resize the yAxis to accommodate the labels.
if (this.maxLabelSize > (this.width - offset) && this.options.visible == true) {
this.width = this.maxLabelSize + offset;
this.options.width = this.width + "px";
DOMutil.cleanupElements(this.DOMelements.lines);
DOMutil.cleanupElements(this.DOMelements.labels);
this.redraw();
resized = true;
}
// this will resize the yAxis if it is too big for the labels.
else if (this.maxLabelSize < (this.width - offset) && this.options.visible == true && this.width > this.minWidth) {
this.width = Math.max(this.minWidth,this.maxLabelSize + offset);
this.options.width = this.width + "px";
DOMutil.cleanupElements(this.DOMelements.lines);
DOMutil.cleanupElements(this.DOMelements.labels);
this.redraw();
resized = true;
}
else {
DOMutil.cleanupElements(this.DOMelements.lines);
DOMutil.cleanupElements(this.DOMelements.labels);
resized = false;
}
return resized;
};
DataAxis.prototype.convertValue = function (value) {
var invertedValue = this.valueAtZero - value;
var convertedValue = invertedValue * this.conversionFactor;
return convertedValue;
};
DataAxis.prototype.screenToValue = function (x) {
return this.valueAtZero - (x / this.conversionFactor);
};
/**
* Create a label for the axis at position x
* @private
* @param y
* @param text
* @param orientation
* @param className
* @param characterHeight
*/
DataAxis.prototype._redrawLabel = function (y, text, orientation, className, characterHeight) {
// reuse redundant label
var label = DOMutil.getDOMElement('div',this.DOMelements.labels, this.dom.frame); //this.dom.redundant.labels.shift();
label.className = className;
label.innerHTML = text;
if (orientation == 'left') {
label.style.left = '-' + this.options.labelOffsetX + 'px';
label.style.textAlign = "right";
}
else {
label.style.right = '-' + this.options.labelOffsetX + 'px';
label.style.textAlign = "left";
}
label.style.top = y - 0.5 * characterHeight + this.options.labelOffsetY + 'px';
text += '';
var largestWidth = Math.max(this.props.majorCharWidth,this.props.minorCharWidth);
if (this.maxLabelSize < text.length * largestWidth) {
this.maxLabelSize = text.length * largestWidth;
}
};
/**
* Create a minor line for the axis at position y
* @param y
* @param orientation
* @param className
* @param offset
* @param width
*/
DataAxis.prototype._redrawLine = function (y, orientation, className, offset, width) {
if (this.master == true) {
var line = DOMutil.getDOMElement('div',this.DOMelements.lines, this.dom.lineContainer);//this.dom.redundant.lines.shift();
line.className = className;
line.innerHTML = '';
if (orientation == 'left') {
line.style.left = (this.width - offset) + 'px';
}
else {
line.style.right = (this.width - offset) + 'px';
}
line.style.width = width + 'px';
line.style.top = y + 'px';
}
};
/**
* Create a title for the axis
* @private
* @param orientation
*/
DataAxis.prototype._redrawTitle = function (orientation) {
DOMutil.prepareElements(this.DOMelements.title);
// Check if the title is defined for this axes
if (this.options.title[orientation] !== undefined && this.options.title[orientation].text !== undefined) {
var title = DOMutil.getDOMElement('div', this.DOMelements.title, this.dom.frame);
title.className = 'yAxis title ' + orientation;
title.innerHTML = this.options.title[orientation].text;
// Add style - if provided
if (this.options.title[orientation].style !== undefined) {
util.addCssText(title, this.options.title[orientation].style);
}
if (orientation == 'left') {
title.style.left = this.props.titleCharHeight + 'px';
}
else {
title.style.right = this.props.titleCharHeight + 'px';
}
title.style.width = this.height + 'px';
}
// we need to clean up in case we did not use all elements.
DOMutil.cleanupElements(this.DOMelements.title);
};
/**
* Determine the size of text on the axis (both major and minor axis).
* The size is calculated only once and then cached in this.props.
* @private
*/
DataAxis.prototype._calculateCharSize = function () {
// determine the char width and height on the minor axis
if (!('minorCharHeight' in this.props)) {
var textMinor = document.createTextNode('0');
var measureCharMinor = document.createElement('div');
measureCharMinor.className = 'yAxis minor measure';
measureCharMinor.appendChild(textMinor);
this.dom.frame.appendChild(measureCharMinor);
this.props.minorCharHeight = measureCharMinor.clientHeight;
this.props.minorCharWidth = measureCharMinor.clientWidth;
this.dom.frame.removeChild(measureCharMinor);
}
if (!('majorCharHeight' in this.props)) {
var textMajor = document.createTextNode('0');
var measureCharMajor = document.createElement('div');
measureCharMajor.className = 'yAxis major measure';
measureCharMajor.appendChild(textMajor);
this.dom.frame.appendChild(measureCharMajor);
this.props.majorCharHeight = measureCharMajor.clientHeight;
this.props.majorCharWidth = measureCharMajor.clientWidth;
this.dom.frame.removeChild(measureCharMajor);
}
if (!('titleCharHeight' in this.props)) {
var textTitle = document.createTextNode('0');
var measureCharTitle = document.createElement('div');
measureCharTitle.className = 'yAxis title measure';
measureCharTitle.appendChild(textTitle);
this.dom.frame.appendChild(measureCharTitle);
this.props.titleCharHeight = measureCharTitle.clientHeight;
this.props.titleCharWidth = measureCharTitle.clientWidth;
this.dom.frame.removeChild(measureCharTitle);
}
};
module.exports = DataAxis;
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
var util = __webpack_require__(1);
var DOMutil = __webpack_require__(2);
var Line = __webpack_require__(49);
var Bar = __webpack_require__(50);
var Points = __webpack_require__(51);
/**
* /**
* @param {object} group | the object of the group from the dataset
* @param {string} groupId | ID of the group
* @param {object} options | the default options
* @param {array} groupsUsingDefaultStyles | this array has one entree.
* It is passed as an array so it is passed by reference.
* It enumerates through the default styles
* @constructor
*/
function GraphGroup (group, groupId, options, groupsUsingDefaultStyles) {
this.id = groupId;
var fields = ['sampling','style','sort','yAxisOrientation','barChart','drawPoints','shaded','catmullRom']
this.options = util.selectiveBridgeObject(fields,options);
this.usingDefaultStyle = group.className === undefined;
this.groupsUsingDefaultStyles = groupsUsingDefaultStyles;
this.zeroPosition = 0;
this.update(group);
if (this.usingDefaultStyle == true) {
this.groupsUsingDefaultStyles[0] += 1;
}
this.itemsData = [];
this.visible = group.visible === undefined ? true : group.visible;
}
/**
* this loads a reference to all items in this group into this group.
* @param {array} items
*/
GraphGroup.prototype.setItems = function(items) {
if (items != null) {
this.itemsData = items;
if (this.options.sort == true) {
this.itemsData.sort(function (a,b) {return a.x - b.x;})
}
}
else {
this.itemsData = [];
}
};
/**
* this is used for plotting barcharts, this way, we only have to calculate it once.
* @param pos
*/
GraphGroup.prototype.setZeroPosition = function(pos) {
this.zeroPosition = pos;
};
/**
* set the options of the graph group over the default options.
* @param options
*/
GraphGroup.prototype.setOptions = function(options) {
if (options !== undefined) {
var fields = ['sampling','style','sort','yAxisOrientation','barChart'];
util.selectiveDeepExtend(fields, this.options, options);
util.mergeOptions(this.options, options,'catmullRom');
util.mergeOptions(this.options, options,'drawPoints');
util.mergeOptions(this.options, options,'shaded');
if (options.catmullRom) {
if (typeof options.catmullRom == 'object') {
if (options.catmullRom.parametrization) {
if (options.catmullRom.parametrization == 'uniform') {
this.options.catmullRom.alpha = 0;
}
else if (options.catmullRom.parametrization == 'chordal') {
this.options.catmullRom.alpha = 1.0;
}
else {
this.options.catmullRom.parametrization = 'centripetal';
this.options.catmullRom.alpha = 0.5;
}
}
}
}
}
if (this.options.style == 'line') {
this.type = new Line(this.id, this.options);
}
else if (this.options.style == 'bar') {
this.type = new Bar(this.id, this.options);
}
else if (this.options.style == 'points') {
this.type = new Points(this.id, this.options);
}
};
/**
* this updates the current group class with the latest group dataset entree, used in _updateGroup in linegraph
* @param group
*/
GraphGroup.prototype.update = function(group) {
this.group = group;
this.content = group.content || 'graph';
this.className = group.className || this.className || "graphGroup" + this.groupsUsingDefaultStyles[0] % 10;
this.visible = group.visible === undefined ? true : group.visible;
this.style = group.style;
this.setOptions(group.options);
};
/**
* draw the icon for the legend.
*
* @param x
* @param y
* @param JSONcontainer
* @param SVGcontainer
* @param iconWidth
* @param iconHeight
*/
GraphGroup.prototype.drawIcon = function(x, y, JSONcontainer, SVGcontainer, iconWidth, iconHeight) {
var fillHeight = iconHeight * 0.5;
var path, fillPath;
var outline = DOMutil.getSVGElement("rect", JSONcontainer, SVGcontainer);
outline.setAttributeNS(null, "x", x);
outline.setAttributeNS(null, "y", y - fillHeight);
outline.setAttributeNS(null, "width", iconWidth);
outline.setAttributeNS(null, "height", 2*fillHeight);
outline.setAttributeNS(null, "class", "outline");
if (this.options.style == 'line') {
path = DOMutil.getSVGElement("path", JSONcontainer, SVGcontainer);
path.setAttributeNS(null, "class", this.className);
if(this.style !== undefined) {
path.setAttributeNS(null, "style", this.style);
}
path.setAttributeNS(null, "d", "M" + x + ","+y+" L" + (x + iconWidth) + ","+y+"");
if (this.options.shaded.enabled == true) {
fillPath = DOMutil.getSVGElement("path", JSONcontainer, SVGcontainer);
if (this.options.shaded.orientation == 'top') {
fillPath.setAttributeNS(null, "d", "M"+x+", " + (y - fillHeight) +
"L"+x+","+y+" L"+ (x + iconWidth) + ","+y+" L"+ (x + iconWidth) + "," + (y - fillHeight));
}
else {
fillPath.setAttributeNS(null, "d", "M"+x+","+y+" " +
"L"+x+"," + (y + fillHeight) + " " +
"L"+ (x + iconWidth) + "," + (y + fillHeight) +
"L"+ (x + iconWidth) + ","+y);
}
fillPath.setAttributeNS(null, "class", this.className + " iconFill");
}
if (this.options.drawPoints.enabled == true) {
DOMutil.drawPoint(x + 0.5 * iconWidth,y, this, JSONcontainer, SVGcontainer);
}
}
else {
var barWidth = Math.round(0.3 * iconWidth);
var bar1Height = Math.round(0.4 * iconHeight);
var bar2Height = Math.round(0.75 * iconHeight);
var offset = Math.round((iconWidth - (2 * barWidth))/3);
DOMutil.drawBar(x + 0.5*barWidth + offset , y + fillHeight - bar1Height - 1, barWidth, bar1Height, this.className + ' bar', JSONcontainer, SVGcontainer);
DOMutil.drawBar(x + 1.5*barWidth + offset + 2, y + fillHeight - bar2Height - 1, barWidth, bar2Height, this.className + ' bar', JSONcontainer, SVGcontainer);
}
};
/**
* return the legend entree for this group.
*
* @param iconWidth
* @param iconHeight
* @returns {{icon: HTMLElement, label: (group.content|*|string), orientation: (.options.yAxisOrientation|*)}}
*/
GraphGroup.prototype.getLegend = function(iconWidth, iconHeight) {
var svg = document.createElementNS('http://www.w3.org/2000/svg',"svg");
this.drawIcon(0,0.5*iconHeight,[],svg,iconWidth,iconHeight);
return {icon: svg, label: this.content, orientation:this.options.yAxisOrientation};
}
GraphGroup.prototype.getYRange = function(groupData) {
return this.type.getYRange(groupData);
}
GraphGroup.prototype.draw = function(dataset, group, framework) {
this.type.draw(dataset, group, framework);
}
module.exports = GraphGroup;
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
var util = __webpack_require__(1);
var stack = __webpack_require__(18);
var RangeItem = __webpack_require__(24);
/**
* @constructor Group
* @param {Number | String} groupId
* @param {Object} data
* @param {ItemSet} itemSet
*/
function Group (groupId, data, itemSet) {
this.groupId = groupId;
this.subgroups = {};
this.subgroupIndex = 0;
this.subgroupOrderer = data && data.subgroupOrder;
this.itemSet = itemSet;
this.dom = {};
this.props = {
label: {
width: 0,
height: 0
}
};
this.className = null;
this.items = {}; // items filtered by groupId of this group
this.visibleItems = []; // items currently visible in window
this.orderedItems = {
byStart: [],
byEnd: []
};
this.checkRangedItems = false; // needed to refresh the ranged items if the window is programatically changed with NO overlap.
var me = this;
this.itemSet.body.emitter.on("checkRangedItems", function () {
me.checkRangedItems = true;
})
this._create();
this.setData(data);
}
/**
* Create DOM elements for the group
* @private
*/
Group.prototype._create = function() {
var label = document.createElement('div');
label.className = 'vlabel';
this.dom.label = label;
var inner = document.createElement('div');
inner.className = 'inner';
label.appendChild(inner);
this.dom.inner = inner;
var foreground = document.createElement('div');
foreground.className = 'group';
foreground['timeline-group'] = this;
this.dom.foreground = foreground;
this.dom.background = document.createElement('div');
this.dom.background.className = 'group';
this.dom.axis = document.createElement('div');
this.dom.axis.className = 'group';
// create a hidden marker to detect when the Timelines container is attached
// to the DOM, or the style of a parent of the Timeline is changed from
// display:none is changed to visible.
this.dom.marker = document.createElement('div');
this.dom.marker.style.visibility = 'hidden'; // TODO: ask jos why this is not none?
this.dom.marker.innerHTML = '?';
this.dom.background.appendChild(this.dom.marker);
};
/**
* Set the group data for this group
* @param {Object} data Group data, can contain properties content and className
*/
Group.prototype.setData = function(data) {
// update contents
var content = data && data.content;
if (content instanceof Element) {
this.dom.inner.appendChild(content);
}
else if (content !== undefined && content !== null) {
this.dom.inner.innerHTML = content;
}
else {
this.dom.inner.innerHTML = this.groupId || ''; // groupId can be null
}
// update title
this.dom.label.title = data && data.title || '';
if (!this.dom.inner.firstChild) {
util.addClassName(this.dom.inner, 'hidden');
}
else {
util.removeClassName(this.dom.inner, 'hidden');
}
// update className
var className = data && data.className || null;
if (className != this.className) {
if (this.className) {
util.removeClassName(this.dom.label, this.className);
util.removeClassName(this.dom.foreground, this.className);
util.removeClassName(this.dom.background, this.className);
util.removeClassName(this.dom.axis, this.className);
}
util.addClassName(this.dom.label, className);
util.addClassName(this.dom.foreground, className);
util.addClassName(this.dom.background, className);
util.addClassName(this.dom.axis, className);
this.className = className;
}
// update style
if (this.style) {
util.removeCssText(this.dom.label, this.style);
this.style = null;
}
if (data && data.style) {
util.addCssText(this.dom.label, data.style);
this.style = data.style;
}
};
/**
* Get the width of the group label
* @return {number} width
*/
Group.prototype.getLabelWidth = function() {
return this.props.label.width;
};
/**
* Repaint this group
* @param {{start: number, end: number}} range
* @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
* @param {boolean} [restack=false] Force restacking of all items
* @return {boolean} Returns true if the group is resized
*/
Group.prototype.redraw = function(range, margin, restack) {
var resized = false;
// force recalculation of the height of the items when the marker height changed
// (due to the Timeline being attached to the DOM or changed from display:none to visible)
var markerHeight = this.dom.marker.clientHeight;
if (markerHeight != this.lastMarkerHeight) {
this.lastMarkerHeight = markerHeight;
util.forEach(this.items, function (item) {
item.dirty = true;
if (item.displayed) item.redraw();
});
restack = true;
}
// reposition visible items vertically
if (typeof this.itemSet.options.order === 'function') {
// a custom order function
if (restack) {
// brute force restack of all items
// show all items
var me = this;
var limitSize = false;
util.forEach(this.items, function (item) {
if (!item.displayed) {
item.redraw();
me.visibleItems.push(item);
}
item.repositionX(limitSize);
});
// order all items and force a restacking
var customOrderedItems = this.orderedItems.byStart.slice().sort(function (a, b) {
return me.itemSet.options.order(a.data, b.data);
});
stack.stack(customOrderedItems, margin, true /* restack=true */);
}
this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range);
}
else {
// no custom order function, lazy stacking
this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range);
if (this.itemSet.options.stack) { // TODO: ugly way to access options...
stack.stack(this.visibleItems, margin, restack);
}
else { // no stacking
stack.nostack(this.visibleItems, margin, this.subgroups);
}
}
// recalculate the height of the group
var height = this._calculateHeight(margin);
// calculate actual size and position
var foreground = this.dom.foreground;
this.top = foreground.offsetTop;
this.left = foreground.offsetLeft;
this.width = foreground.offsetWidth;
resized = util.updateProperty(this, 'height', height) || resized;
// recalculate size of label
resized = util.updateProperty(this.props.label, 'width', this.dom.inner.clientWidth) || resized;
resized = util.updateProperty(this.props.label, 'height', this.dom.inner.clientHeight) || resized;
// apply new height
this.dom.background.style.height = height + 'px';
this.dom.foreground.style.height = height + 'px';
this.dom.label.style.height = height + 'px';
// update vertical position of items after they are re-stacked and the height of the group is calculated
for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
var item = this.visibleItems[i];
item.repositionY(margin);
}
return resized;
};
/**
* recalculate the height of the group
* @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
* @returns {number} Returns the height
* @private
*/
Group.prototype._calculateHeight = function (margin) {
// recalculate the height of the group
var height;
var visibleItems = this.visibleItems;
//var visibleSubgroups = [];
//this.visibleSubgroups = 0;
this.resetSubgroups();
var me = this;
if (visibleItems.length) {
var min = visibleItems[0].top;
var max = visibleItems[0].top + visibleItems[0].height;
util.forEach(visibleItems, function (item) {
min = Math.min(min, item.top);
max = Math.max(max, (item.top + item.height));
if (item.data.subgroup !== undefined) {
me.subgroups[item.data.subgroup].height = Math.max(me.subgroups[item.data.subgroup].height,item.height);
me.subgroups[item.data.subgroup].visible = true;
//if (visibleSubgroups.indexOf(item.data.subgroup) == -1){
// visibleSubgroups.push(item.data.subgroup);
// me.visibleSubgroups += 1;
//}
}
});
if (min > margin.axis) {
// there is an empty gap between the lowest item and the axis
var offset = min - margin.axis;
max -= offset;
util.forEach(visibleItems, function (item) {
item.top -= offset;
});
}
height = max + margin.item.vertical / 2;
}
else {
height = 0;
}
height = Math.max(height, this.props.label.height);
return height;
};
/**
* Show this group: attach to the DOM
*/
Group.prototype.show = function() {
if (!this.dom.label.parentNode) {
this.itemSet.dom.labelSet.appendChild(this.dom.label);
}
if (!this.dom.foreground.parentNode) {
this.itemSet.dom.foreground.appendChild(this.dom.foreground);
}
if (!this.dom.background.parentNode) {
this.itemSet.dom.background.appendChild(this.dom.background);
}
if (!this.dom.axis.parentNode) {
this.itemSet.dom.axis.appendChild(this.dom.axis);
}
};
/**
* Hide this group: remove from the DOM
*/
Group.prototype.hide = function() {
var label = this.dom.label;
if (label.parentNode) {
label.parentNode.removeChild(label);
}
var foreground = this.dom.foreground;
if (foreground.parentNode) {
foreground.parentNode.removeChild(foreground);
}
var background = this.dom.background;
if (background.parentNode) {
background.parentNode.removeChild(background);
}
var axis = this.dom.axis;
if (axis.parentNode) {
axis.parentNode.removeChild(axis);
}
};
/**
* Add an item to the group
* @param {Item} item
*/
Group.prototype.add = function(item) {
this.items[item.id] = item;
item.setParent(this);
// add to
if (item.data.subgroup !== undefined) {
if (this.subgroups[item.data.subgroup] === undefined) {
this.subgroups[item.data.subgroup] = {height:0, visible: false, index:this.subgroupIndex, items: []};
this.subgroupIndex++;
}
this.subgroups[item.data.subgroup].items.push(item);
}
this.orderSubgroups();
if (this.visibleItems.indexOf(item) == -1) {
var range = this.itemSet.body.range; // TODO: not nice accessing the range like this
this._checkIfVisible(item, this.visibleItems, range);
}
};
Group.prototype.orderSubgroups = function() {
if (this.subgroupOrderer !== undefined) {
var sortArray = [];
if (typeof this.subgroupOrderer == 'string') {
for (var subgroup in this.subgroups) {
sortArray.push({subgroup: subgroup, sortField: this.subgroups[subgroup].items[0].data[this.subgroupOrderer]})
}
sortArray.sort(function (a, b) {
return a.sortField - b.sortField;
})
}
else if (typeof this.subgroupOrderer == 'function') {
for (var subgroup in this.subgroups) {
sortArray.push(this.subgroups[subgroup].items[0].data);
}
sortArray.sort(this.subgroupOrderer);
}
if (sortArray.length > 0) {
for (var i = 0; i < sortArray.length; i++) {
this.subgroups[sortArray[i].subgroup].index = i;
}
}
}
};
Group.prototype.resetSubgroups = function() {
for (var subgroup in this.subgroups) {
if (this.subgroups.hasOwnProperty(subgroup)) {
this.subgroups[subgroup].visible = false;
}
}
};
/**
* Remove an item from the group
* @param {Item} item
*/
Group.prototype.remove = function(item) {
delete this.items[item.id];
item.setParent(null);
// remove from visible items
var index = this.visibleItems.indexOf(item);
if (index != -1) this.visibleItems.splice(index, 1);
// TODO: also remove from ordered items?
};
/**
* Remove an item from the corresponding DataSet
* @param {Item} item
*/
Group.prototype.removeFromDataSet = function(item) {
this.itemSet.removeItem(item.id);
};
/**
* Reorder the items
*/
Group.prototype.order = function() {
var array = util.toArray(this.items);
var startArray = [];
var endArray = [];
for (var i = 0; i < array.length; i++) {
if (array[i].data.end !== undefined) {
endArray.push(array[i]);
}
startArray.push(array[i]);
}
this.orderedItems = {
byStart: startArray,
byEnd: endArray
};
stack.orderByStart(this.orderedItems.byStart);
stack.orderByEnd(this.orderedItems.byEnd);
};
/**
* Update the visible items
* @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date
* @param {Item[]} visibleItems The previously visible items.
* @param {{start: number, end: number}} range Visible range
* @return {Item[]} visibleItems The new visible items.
* @private
*/
Group.prototype._updateVisibleItems = function(orderedItems, oldVisibleItems, range) {
var visibleItems = [];
var visibleItemsLookup = {}; // we keep this to quickly look up if an item already exists in the list without using indexOf on visibleItems
var interval = (range.end - range.start) / 4;
var lowerBound = range.start - interval;
var upperBound = range.end + interval;
var item, i;
// this function is used to do the binary search.
var searchFunction = function (value) {
if (value < lowerBound) {return -1;}
else if (value <= upperBound) {return 0;}
else {return 1;}
}
// first check if the items that were in view previously are still in view.
// IMPORTANT: this handles the case for the items with startdate before the window and enddate after the window!
// also cleans up invisible items.
if (oldVisibleItems.length > 0) {
for (i = 0; i < oldVisibleItems.length; i++) {
this._checkIfVisibleWithReference(oldVisibleItems[i], visibleItems, visibleItemsLookup, range);
}
}
// we do a binary search for the items that have only start values.
var initialPosByStart = util.binarySearchCustom(orderedItems.byStart, searchFunction, 'data','start');
// trace the visible items from the inital start pos both ways until an invisible item is found, we only look at the start values.
this._traceVisible(initialPosByStart, orderedItems.byStart, visibleItems, visibleItemsLookup, function (item) {
return (item.data.start < lowerBound || item.data.start > upperBound);
});
// if the window has changed programmatically without overlapping the old window, the ranged items with start < lowerBound and end > upperbound are not shown.
// We therefore have to brute force check all items in the byEnd list
if (this.checkRangedItems == true) {
this.checkRangedItems = false;
for (i = 0; i < orderedItems.byEnd.length; i++) {
this._checkIfVisibleWithReference(orderedItems.byEnd[i], visibleItems, visibleItemsLookup, range);
}
}
else {
// we do a binary search for the items that have defined end times.
var initialPosByEnd = util.binarySearchCustom(orderedItems.byEnd, searchFunction, 'data','end');
// trace the visible items from the inital start pos both ways until an invisible item is found, we only look at the end values.
this._traceVisible(initialPosByEnd, orderedItems.byEnd, visibleItems, visibleItemsLookup, function (item) {
return (item.data.end < lowerBound || item.data.end > upperBound);
});
}
// finally, we reposition all the visible items.
for (i = 0; i < visibleItems.length; i++) {
item = visibleItems[i];
if (!item.displayed) item.show();
// reposition item horizontally
item.repositionX();
}
// debug
//console.log("new line")
//if (this.groupId == null) {
// for (i = 0; i < orderedItems.byStart.length; i++) {
// item = orderedItems.byStart[i].data;
// console.log('start',i,initialPosByStart, item.start.valueOf(), item.content, item.start >= lowerBound && item.start <= upperBound,i == initialPosByStart ? "<------------------- HEREEEE" : "")
// }
// for (i = 0; i < orderedItems.byEnd.length; i++) {
// item = orderedItems.byEnd[i].data;
// console.log('rangeEnd',i,initialPosByEnd, item.end.valueOf(), item.content, item.end >= range.start && item.end <= range.end,i == initialPosByEnd ? "<------------------- HEREEEE" : "")
// }
//}
return visibleItems;
};
Group.prototype._traceVisible = function (initialPos, items, visibleItems, visibleItemsLookup, breakCondition) {
var item;
var i;
if (initialPos != -1) {
for (i = initialPos; i >= 0; i--) {
item = items[i];
if (breakCondition(item)) {
break;
}
else {
if (visibleItemsLookup[item.id] === undefined) {
visibleItemsLookup[item.id] = true;
visibleItems.push(item);
}
}
}
for (i = initialPos + 1; i < items.length; i++) {
item = items[i];
if (breakCondition(item)) {
break;
}
else {
if (visibleItemsLookup[item.id] === undefined) {
visibleItemsLookup[item.id] = true;
visibleItems.push(item);
}
}
}
}
}
/**
* this function is very similar to the _checkIfInvisible() but it does not
* return booleans, hides the item if it should not be seen and always adds to
* the visibleItems.
* this one is for brute forcing and hiding.
*
* @param {Item} item
* @param {Array} visibleItems
* @param {{start:number, end:number}} range
* @private
*/
Group.prototype._checkIfVisible = function(item, visibleItems, range) {
if (item.isVisible(range)) {
if (!item.displayed) item.show();
// reposition item horizontally
item.repositionX();
visibleItems.push(item);
}
else {
if (item.displayed) item.hide();
}
};
/**
* this function is very similar to the _checkIfInvisible() but it does not
* return booleans, hides the item if it should not be seen and always adds to
* the visibleItems.
* this one is for brute forcing and hiding.
*
* @param {Item} item
* @param {Array} visibleItems
* @param {{start:number, end:number}} range
* @private
*/
Group.prototype._checkIfVisibleWithReference = function(item, visibleItems, visibleItemsLookup, range) {
if (item.isVisible(range)) {
if (visibleItemsLookup[item.id] === undefined) {
visibleItemsLookup[item.id] = true;
visibleItems.push(item);
}
}
else {
if (item.displayed) item.hide();
}
};
module.exports = Group;
/***/ },
/* 31 */
/***/ function(module, exports, __webpack_require__) {
var util = __webpack_require__(1);
var Group = __webpack_require__(30);
/**
* @constructor BackgroundGroup
* @param {Number | String} groupId
* @param {Object} data
* @param {ItemSet} itemSet
*/
function BackgroundGroup (groupId, data, itemSet) {
Group.call(this, groupId, data, itemSet);
this.width = 0;
this.height = 0;
this.top = 0;
this.left = 0;
}
BackgroundGroup.prototype = Object.create(Group.prototype);
/**
* Repaint this group
* @param {{start: number, end: number}} range
* @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
* @param {boolean} [restack=false] Force restacking of all items
* @return {boolean} Returns true if the group is resized
*/
BackgroundGroup.prototype.redraw = function(range, margin, restack) {
var resized = false;
this.visibleItems = this._updateVisibleItems(this.orderedItems, this.visibleItems, range);
// calculate actual size
this.width = this.dom.background.offsetWidth;
// apply new height (just always zero for BackgroundGroup
this.dom.background.style.height = '0';
// update vertical position of items after they are re-stacked and the height of the group is calculated
for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
var item = this.visibleItems[i];
item.repositionY(margin);
}
return resized;
};
/**
* Show this group: attach to the DOM
*/
BackgroundGroup.prototype.show = function() {
if (!this.dom.background.parentNode) {
this.itemSet.dom.background.appendChild(this.dom.background);
}
};
module.exports = BackgroundGroup;
/***/ },
/* 32 */
/***/ function(module, exports, __webpack_require__) {
var Hammer = __webpack_require__(45);
var util = __webpack_require__(1);
var DataSet = __webpack_require__(3);
var DataView = __webpack_require__(4);
var TimeStep = __webpack_require__(19);
var Component = __webpack_require__(25);
var Group = __webpack_require__(30);
var BackgroundGroup = __webpack_require__(31);
var BoxItem = __webpack_require__(22);
var PointItem = __webpack_require__(23);
var RangeItem = __webpack_require__(24);
var BackgroundItem = __webpack_require__(21);
var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
var BACKGROUND = '__background__'; // reserved group id for background items without group
/**
* An ItemSet holds a set of items and ranges which can be displayed in a
* range. The width is determined by the parent of the ItemSet, and the height
* is determined by the size of the items.
* @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body
* @param {Object} [options] See ItemSet.setOptions for the available options.
* @constructor ItemSet
* @extends Component
*/
function ItemSet(body, options) {
this.body = body;
this.defaultOptions = {
type: null, // 'box', 'point', 'range', 'background'
orientation: 'bottom', // item orientation: 'top' or 'bottom'
align: 'auto', // alignment of box items
stack: true,
groupOrder: null,
selectable: true,
editable: {
updateTime: false,
updateGroup: false,
add: false,
remove: false
},
snap: TimeStep.snap,
onAdd: function (item, callback) {
callback(item);
},
onUpdate: function (item, callback) {
callback(item);
},
onMove: function (item, callback) {
callback(item);
},
onRemove: function (item, callback) {
callback(item);
},
onMoving: function (item, callback) {
callback(item);
},
margin: {
item: {
horizontal: 10,
vertical: 10
},
axis: 20
},
padding: 5
};
// options is shared by this ItemSet and all its items
this.options = util.extend({}, this.defaultOptions);
// options for getting items from the DataSet with the correct type
this.itemOptions = {
type: {start: 'Date', end: 'Date'}
};
this.conversion = {
toScreen: body.util.toScreen,
toTime: body.util.toTime
};
this.dom = {};
this.props = {};
this.hammer = null;
var me = this;
this.itemsData = null; // DataSet
this.groupsData = null; // DataSet
// listeners for the DataSet of the items
this.itemListeners = {
'add': function (event, params, senderId) {
me._onAdd(params.items);
},
'update': function (event, params, senderId) {
me._onUpdate(params.items);
},
'remove': function (event, params, senderId) {
me._onRemove(params.items);
}
};
// listeners for the DataSet of the groups
this.groupListeners = {
'add': function (event, params, senderId) {
me._onAddGroups(params.items);
},
'update': function (event, params, senderId) {
me._onUpdateGroups(params.items);
},
'remove': function (event, params, senderId) {
me._onRemoveGroups(params.items);
}
};
this.items = {}; // object with an Item for every data item
this.groups = {}; // Group object for every group
this.groupIds = [];
this.selection = []; // list with the ids of all selected nodes
this.stackDirty = true; // if true, all items will be restacked on next redraw
this.touchParams = {}; // stores properties while dragging
// create the HTML DOM
this._create();
this.setOptions(options);
}
ItemSet.prototype = new Component();
// available item types will be registered here
ItemSet.types = {
background: BackgroundItem,
box: BoxItem,
range: RangeItem,
point: PointItem
};
/**
* Create the HTML DOM for the ItemSet
*/
ItemSet.prototype._create = function(){
var frame = document.createElement('div');
frame.className = 'itemset';
frame['timeline-itemset'] = this;
this.dom.frame = frame;
// create background panel
var background = document.createElement('div');
background.className = 'background';
frame.appendChild(background);
this.dom.background = background;
// create foreground panel
var foreground = document.createElement('div');
foreground.className = 'foreground';
frame.appendChild(foreground);
this.dom.foreground = foreground;
// create axis panel
var axis = document.createElement('div');
axis.className = 'axis';
this.dom.axis = axis;
// create labelset
var labelSet = document.createElement('div');
labelSet.className = 'labelset';
this.dom.labelSet = labelSet;
// create ungrouped Group
this._updateUngrouped();
// create background Group
var backgroundGroup = new BackgroundGroup(BACKGROUND, null, this);
backgroundGroup.show();
this.groups[BACKGROUND] = backgroundGroup;
// attach event listeners
// Note: we bind to the centerContainer for the case where the height
// of the center container is larger than of the ItemSet, so we
// can click in the empty area to create a new item or deselect an item.
this.hammer = Hammer(this.body.dom.centerContainer, {
preventDefault: true
});
// drag items when selected
this.hammer.on('touch', this._onTouch.bind(this));
this.hammer.on('dragstart', this._onDragStart.bind(this));
this.hammer.on('drag', this._onDrag.bind(this));
this.hammer.on('dragend', this._onDragEnd.bind(this));
// single select (or unselect) when tapping an item
this.hammer.on('tap', this._onSelectItem.bind(this));
// multi select when holding mouse/touch, or on ctrl+click
this.hammer.on('hold', this._onMultiSelectItem.bind(this));
// add item on doubletap
this.hammer.on('doubletap', this._onAddItem.bind(this));
// attach to the DOM
this.show();
};
/**
* Set options for the ItemSet. Existing options will be extended/overwritten.
* @param {Object} [options] The following options are available:
* {String} type
* Default type for the items. Choose from 'box'
* (default), 'point', 'range', or 'background'.
* The default style can be overwritten by
* individual items.
* {String} align
* Alignment for the items, only applicable for
* BoxItem. Choose 'center' (default), 'left', or
* 'right'.
* {String} orientation
* Orientation of the item set. Choose 'top' or
* 'bottom' (default).
* {Function} groupOrder
* A sorting function for ordering groups
* {Boolean} stack
* If true (deafult), items will be stacked on
* top of each other.
* {Number} margin.axis
* Margin between the axis and the items in pixels.
* Default is 20.
* {Number} margin.item.horizontal
* Horizontal margin between items in pixels.
* Default is 10.
* {Number} margin.item.vertical
* Vertical Margin between items in pixels.
* Default is 10.
* {Number} margin.item
* Margin between items in pixels in both horizontal
* and vertical direction. Default is 10.
* {Number} margin
* Set margin for both axis and items in pixels.
* {Number} padding
* Padding of the contents of an item in pixels.
* Must correspond with the items css. Default is 5.
* {Boolean} selectable
* If true (default), items can be selected.
* {Boolean} editable
* Set all editable options to true or false
* {Boolean} editable.updateTime
* Allow dragging an item to an other moment in time
* {Boolean} editable.updateGroup
* Allow dragging an item to an other group
* {Boolean} editable.add
* Allow creating new items on double tap
* {Boolean} editable.remove
* Allow removing items by clicking the delete button
* top right of a selected item.
* {Function(item: Item, callback: Function)} onAdd
* Callback function triggered when an item is about to be added:
* when the user double taps an empty space in the Timeline.
* {Function(item: Item, callback: Function)} onUpdate
* Callback function fired when an item is about to be updated.
* This function typically has to show a dialog where the user
* change the item. If not implemented, nothing happens.
* {Function(item: Item, callback: Function)} onMove
* Fired when an item has been moved. If not implemented,
* the move action will be accepted.
* {Function(item: Item, callback: Function)} onRemove
* Fired when an item is about to be deleted.
* If not implemented, the item will be always removed.
*/
ItemSet.prototype.setOptions = function(options) {
if (options) {
// copy all options that we know
var fields = ['type', 'align', 'order', 'padding', 'stack', 'selectable', 'groupOrder', 'dataAttributes', 'template','hide', 'snap'];
util.selectiveExtend(fields, this.options, options);
if ('orientation' in options) {
if (typeof options.orientation === 'string') {
this.options.orientation = options.orientation;
}
else if (typeof options.orientation === 'object' && 'item' in options.orientation) {
this.options.orientation = options.orientation.item;
}
}
if ('margin' in options) {
if (typeof options.margin === 'number') {
this.options.margin.axis = options.margin;
this.options.margin.item.horizontal = options.margin;
this.options.margin.item.vertical = options.margin;
}
else if (typeof options.margin === 'object') {
util.selectiveExtend(['axis'], this.options.margin, options.margin);
if ('item' in options.margin) {
if (typeof options.margin.item === 'number') {
this.options.margin.item.horizontal = options.margin.item;
this.options.margin.item.vertical = options.margin.item;
}
else if (typeof options.margin.item === 'object') {
util.selectiveExtend(['horizontal', 'vertical'], this.options.margin.item, options.margin.item);
}
}
}
}
if ('editable' in options) {
if (typeof options.editable === 'boolean') {
this.options.editable.updateTime = options.editable;
this.options.editable.updateGroup = options.editable;
this.options.editable.add = options.editable;
this.options.editable.remove = options.editable;
}
else if (typeof options.editable === 'object') {
util.selectiveExtend(['updateTime', 'updateGroup', 'add', 'remove'], this.options.editable, options.editable);
}
}
// callback functions
var addCallback = (function (name) {
var fn = options[name];
if (fn) {
if (!(fn instanceof Function)) {
throw new Error('option ' + name + ' must be a function ' + name + '(item, callback)');
}
this.options[name] = fn;
}
}).bind(this);
['onAdd', 'onUpdate', 'onRemove', 'onMove', 'onMoving'].forEach(addCallback);
// force the itemSet to refresh: options like orientation and margins may be changed
this.markDirty();
}
};
/**
* Mark the ItemSet dirty so it will refresh everything with next redraw.
* Optionally, all items can be marked as dirty and be refreshed.
* @param {{refreshItems: boolean}} [options]
*/
ItemSet.prototype.markDirty = function(options) {
this.groupIds = [];
this.stackDirty = true;
if (options && options.refreshItems) {
util.forEach(this.items, function (item) {
item.dirty = true;
if (item.displayed) item.redraw();
});
}
};
/**
* Destroy the ItemSet
*/
ItemSet.prototype.destroy = function() {
this.hide();
this.setItems(null);
this.setGroups(null);
this.hammer = null;
this.body = null;
this.conversion = null;
};
/**
* Hide the component from the DOM
*/
ItemSet.prototype.hide = function() {
// remove the frame containing the items
if (this.dom.frame.parentNode) {
this.dom.frame.parentNode.removeChild(this.dom.frame);
}
// remove the axis with dots
if (this.dom.axis.parentNode) {
this.dom.axis.parentNode.removeChild(this.dom.axis);
}
// remove the labelset containing all group labels
if (this.dom.labelSet.parentNode) {
this.dom.labelSet.parentNode.removeChild(this.dom.labelSet);
}
};
/**
* Show the component in the DOM (when not already visible).
* @return {Boolean} changed
*/
ItemSet.prototype.show = function() {
// show frame containing the items
if (!this.dom.frame.parentNode) {
this.body.dom.center.appendChild(this.dom.frame);
}
// show axis with dots
if (!this.dom.axis.parentNode) {
this.body.dom.backgroundVertical.appendChild(this.dom.axis);
}
// show labelset containing labels
if (!this.dom.labelSet.parentNode) {
this.body.dom.left.appendChild(this.dom.labelSet);
}
};
/**
* Set selected items by their id. Replaces the current selection
* Unknown id's are silently ignored.
* @param {string[] | string} [ids] An array with zero or more id's of the items to be
* selected, or a single item id. If ids is undefined
* or an empty array, all items will be unselected.
*/
ItemSet.prototype.setSelection = function(ids) {
var i, ii, id, item;
if (ids == undefined) ids = [];
if (!Array.isArray(ids)) ids = [ids];
// unselect currently selected items
for (i = 0, ii = this.selection.length; i < ii; i++) {
id = this.selection[i];
item = this.items[id];
if (item) item.unselect();
}
// select items
this.selection = [];
for (i = 0, ii = ids.length; i < ii; i++) {
id = ids[i];
item = this.items[id];
if (item) {
this.selection.push(id);
item.select();
}
}
};
/**
* Get the selected items by their id
* @return {Array} ids The ids of the selected items
*/
ItemSet.prototype.getSelection = function() {
return this.selection.concat([]);
};
/**
* Get the id's of the currently visible items.
* @returns {Array} The ids of the visible items
*/
ItemSet.prototype.getVisibleItems = function() {
var range = this.body.range.getRange();
var left = this.body.util.toScreen(range.start);
var right = this.body.util.toScreen(range.end);
var ids = [];
for (var groupId in this.groups) {
if (this.groups.hasOwnProperty(groupId)) {
var group = this.groups[groupId];
var rawVisibleItems = group.visibleItems;
// filter the "raw" set with visibleItems into a set which is really
// visible by pixels
for (var i = 0; i < rawVisibleItems.length; i++) {
var item = rawVisibleItems[i];
// TODO: also check whether visible vertically
if ((item.left < right) && (item.left + item.width > left)) {
ids.push(item.id);
}
}
}
}
return ids;
};
/**
* Deselect a selected item
* @param {String | Number} id
* @private
*/
ItemSet.prototype._deselect = function(id) {
var selection = this.selection;
for (var i = 0, ii = selection.length; i < ii; i++) {
if (selection[i] == id) { // non-strict comparison!
selection.splice(i, 1);
break;
}
}
};
/**
* Repaint the component
* @return {boolean} Returns true if the component is resized
*/
ItemSet.prototype.redraw = function() {
var margin = this.options.margin,
range = this.body.range,
asSize = util.option.asSize,
options = this.options,
orientation = options.orientation,
resized = false,
frame = this.dom.frame,
editable = options.editable.updateTime || options.editable.updateGroup;
// recalculate absolute position (before redrawing groups)
this.props.top = this.body.domProps.top.height + this.body.domProps.border.top;
this.props.left = this.body.domProps.left.width + this.body.domProps.border.left;
// update class name
frame.className = 'itemset' + (editable ? ' editable' : '');
// reorder the groups (if needed)
resized = this._orderGroups() || resized;
// check whether zoomed (in that case we need to re-stack everything)
// TODO: would be nicer to get this as a trigger from Range
var visibleInterval = range.end - range.start;
var zoomed = (visibleInterval != this.lastVisibleInterval) || (this.props.width != this.props.lastWidth);
if (zoomed) this.stackDirty = true;
this.lastVisibleInterval = visibleInterval;
this.props.lastWidth = this.props.width;
var restack = this.stackDirty;
var firstGroup = this._firstGroup();
var firstMargin = {
item: margin.item,
axis: margin.axis
};
var nonFirstMargin = {
item: margin.item,
axis: margin.item.vertical / 2
};
var height = 0;
var minHeight = margin.axis + margin.item.vertical;
// redraw the background group
this.groups[BACKGROUND].redraw(range, nonFirstMargin, restack);
// redraw all regular groups
util.forEach(this.groups, function (group) {
var groupMargin = (group == firstGroup) ? firstMargin : nonFirstMargin;
var groupResized = group.redraw(range, groupMargin, restack);
resized = groupResized || resized;
height += group.height;
});
height = Math.max(height, minHeight);
this.stackDirty = false;
// update frame height
frame.style.height = asSize(height);
// calculate actual size
this.props.width = frame.offsetWidth;
this.props.height = height;
// reposition axis
this.dom.axis.style.top = asSize((orientation == 'top') ?
(this.body.domProps.top.height + this.body.domProps.border.top) :
(this.body.domProps.top.height + this.body.domProps.centerContainer.height));
this.dom.axis.style.left = '0';
// check if this component is resized
resized = this._isResized() || resized;
return resized;
};
/**
* Get the first group, aligned with the axis
* @return {Group | null} firstGroup
* @private
*/
ItemSet.prototype._firstGroup = function() {
var firstGroupIndex = (this.options.orientation == 'top') ? 0 : (this.groupIds.length - 1);
var firstGroupId = this.groupIds[firstGroupIndex];
var firstGroup = this.groups[firstGroupId] || this.groups[UNGROUPED];
return firstGroup || null;
};
/**
* Create or delete the group holding all ungrouped items. This group is used when
* there are no groups specified.
* @protected
*/
ItemSet.prototype._updateUngrouped = function() {
var ungrouped = this.groups[UNGROUPED];
var background = this.groups[BACKGROUND];
var item, itemId;
if (this.groupsData) {
// remove the group holding all ungrouped items
if (ungrouped) {
ungrouped.hide();
delete this.groups[UNGROUPED];
for (itemId in this.items) {
if (this.items.hasOwnProperty(itemId)) {
item = this.items[itemId];
item.parent && item.parent.remove(item);
var groupId = this._getGroupId(item.data);
var group = this.groups[groupId];
group && group.add(item) || item.hide();
}
}
}
}
else {
// create a group holding all (unfiltered) items
if (!ungrouped) {
var id = null;
var data = null;
ungrouped = new Group(id, data, this);
this.groups[UNGROUPED] = ungrouped;
for (itemId in this.items) {
if (this.items.hasOwnProperty(itemId)) {
item = this.items[itemId];
ungrouped.add(item);
}
}
ungrouped.show();
}
}
};
/**
* Get the element for the labelset
* @return {HTMLElement} labelSet
*/
ItemSet.prototype.getLabelSet = function() {
return this.dom.labelSet;
};
/**
* Set items
* @param {vis.DataSet | null} items
*/
ItemSet.prototype.setItems = function(items) {
var me = this,
ids,
oldItemsData = this.itemsData;
// replace the dataset
if (!items) {
this.itemsData = null;
}
else if (items instanceof DataSet || items instanceof DataView) {
this.itemsData = items;
}
else {
throw new TypeError('Data must be an instance of DataSet or DataView');
}
if (oldItemsData) {
// unsubscribe from old dataset
util.forEach(this.itemListeners, function (callback, event) {
oldItemsData.off(event, callback);
});
// remove all drawn items
ids = oldItemsData.getIds();
this._onRemove(ids);
}
if (this.itemsData) {
// subscribe to new dataset
var id = this.id;
util.forEach(this.itemListeners, function (callback, event) {
me.itemsData.on(event, callback, id);
});
// add all new items
ids = this.itemsData.getIds();
this._onAdd(ids);
// update the group holding all ungrouped items
this._updateUngrouped();
}
};
/**
* Get the current items
* @returns {vis.DataSet | null}
*/
ItemSet.prototype.getItems = function() {
return this.itemsData;
};
/**
* Set groups
* @param {vis.DataSet} groups
*/
ItemSet.prototype.setGroups = function(groups) {
var me = this,
ids;
// unsubscribe from current dataset
if (this.groupsData) {
util.forEach(this.groupListeners, function (callback, event) {
me.groupsData.unsubscribe(event, callback);
});
// remove all drawn groups
ids = this.groupsData.getIds();
this.groupsData = null;
this._onRemoveGroups(ids); // note: this will cause a redraw
}
// replace the dataset
if (!groups) {
this.groupsData = null;
}
else if (groups instanceof DataSet || groups instanceof DataView) {
this.groupsData = groups;
}
else {
throw new TypeError('Data must be an instance of DataSet or DataView');
}
if (this.groupsData) {
// subscribe to new dataset
var id = this.id;
util.forEach(this.groupListeners, function (callback, event) {
me.groupsData.on(event, callback, id);
});
// draw all ms
ids = this.groupsData.getIds();
this._onAddGroups(ids);
}
// update the group holding all ungrouped items
this._updateUngrouped();
// update the order of all items in each group
this._order();
this.body.emitter.emit('change', {queue: true});
};
/**
* Get the current groups
* @returns {vis.DataSet | null} groups
*/
ItemSet.prototype.getGroups = function() {
return this.groupsData;
};
/**
* Remove an item by its id
* @param {String | Number} id
*/
ItemSet.prototype.removeItem = function(id) {
var item = this.itemsData.get(id),
dataset = this.itemsData.getDataSet();
if (item) {
// confirm deletion
this.options.onRemove(item, function (item) {
if (item) {
// remove by id here, it is possible that an item has no id defined
// itself, so better not delete by the item itself
dataset.remove(id);
}
});
}
};
/**
* Get the time of an item based on it's data and options.type
* @param {Object} itemData
* @returns {string} Returns the type
* @private
*/
ItemSet.prototype._getType = function (itemData) {
return itemData.type || this.options.type || (itemData.end ? 'range' : 'box');
};
/**
* Get the group id for an item
* @param {Object} itemData
* @returns {string} Returns the groupId
* @private
*/
ItemSet.prototype._getGroupId = function (itemData) {
var type = this._getType(itemData);
if (type == 'background' && itemData.group == undefined) {
return BACKGROUND;
}
else {
return this.groupsData ? itemData.group : UNGROUPED;
}
};
/**
* Handle updated items
* @param {Number[]} ids
* @protected
*/
ItemSet.prototype._onUpdate = function(ids) {
var me = this;
ids.forEach(function (id) {
var itemData = me.itemsData.get(id, me.itemOptions);
var item = me.items[id];
var type = me._getType(itemData);
var constructor = ItemSet.types[type];
if (item) {
// update item
if (!constructor || !(item instanceof constructor)) {
// item type has changed, delete the item and recreate it
me._removeItem(item);
item = null;
}
else {
me._updateItem(item, itemData);
}
}
if (!item) {
// create item
if (constructor) {
item = new constructor(itemData, me.conversion, me.options);
item.id = id; // TODO: not so nice setting id afterwards
me._addItem(item);
}
else if (type == 'rangeoverflow') {
// TODO: deprecated since version 2.1.0 (or 3.0.0?). cleanup some day
throw new TypeError('Item type "rangeoverflow" is deprecated. Use css styling instead: ' +
'.vis.timeline .item.range .content {overflow: visible;}');
}
else {
throw new TypeError('Unknown item type "' + type + '"');
}
}
});
this._order();
this.stackDirty = true; // force re-stacking of all items next redraw
this.body.emitter.emit('change', {queue: true});
};
/**
* Handle added items
* @param {Number[]} ids
* @protected
*/
ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
/**
* Handle removed items
* @param {Number[]} ids
* @protected
*/
ItemSet.prototype._onRemove = function(ids) {
var count = 0;
var me = this;
ids.forEach(function (id) {
var item = me.items[id];
if (item) {
count++;
me._removeItem(item);
}
});
if (count) {
// update order
this._order();
this.stackDirty = true; // force re-stacking of all items next redraw
this.body.emitter.emit('change', {queue: true});
}
};
/**
* Update the order of item in all groups
* @private
*/
ItemSet.prototype._order = function() {
// reorder the items in all groups
// TODO: optimization: only reorder groups affected by the changed items
util.forEach(this.groups, function (group) {
group.order();
});
};
/**
* Handle updated groups
* @param {Number[]} ids
* @private
*/
ItemSet.prototype._onUpdateGroups = function(ids) {
this._onAddGroups(ids);
};
/**
* Handle changed groups (added or updated)
* @param {Number[]} ids
* @private
*/
ItemSet.prototype._onAddGroups = function(ids) {
var me = this;
ids.forEach(function (id) {
var groupData = me.groupsData.get(id);
var group = me.groups[id];
if (!group) {
// check for reserved ids
if (id == UNGROUPED || id == BACKGROUND) {
throw new Error('Illegal group id. ' + id + ' is a reserved id.');
}
var groupOptions = Object.create(me.options);
util.extend(groupOptions, {
height: null
});
group = new Group(id, groupData, me);
me.groups[id] = group;
// add items with this groupId to the new group
for (var itemId in me.items) {
if (me.items.hasOwnProperty(itemId)) {
var item = me.items[itemId];
if (item.data.group == id) {
group.add(item);
}
}
}
group.order();
group.show();
}
else {
// update group
group.setData(groupData);
}
});
this.body.emitter.emit('change', {queue: true});
};
/**
* Handle removed groups
* @param {Number[]} ids
* @private
*/
ItemSet.prototype._onRemoveGroups = function(ids) {
var groups = this.groups;
ids.forEach(function (id) {
var group = groups[id];
if (group) {
group.hide();
delete groups[id];
}
});
this.markDirty();
this.body.emitter.emit('change', {queue: true});
};
/**
* Reorder the groups if needed
* @return {boolean} changed
* @private
*/
ItemSet.prototype._orderGroups = function () {
if (this.groupsData) {
// reorder the groups
var groupIds = this.groupsData.getIds({
order: this.options.groupOrder
});
var changed = !util.equalArray(groupIds, this.groupIds);
if (changed) {
// hide all groups, removes them from the DOM
var groups = this.groups;
groupIds.forEach(function (groupId) {
groups[groupId].hide();
});
// show the groups again, attach them to the DOM in correct order
groupIds.forEach(function (groupId) {
groups[groupId].show();
});
this.groupIds = groupIds;
}
return changed;
}
else {
return false;
}
};
/**
* Add a new item
* @param {Item} item
* @private
*/
ItemSet.prototype._addItem = function(item) {
this.items[item.id] = item;
// add to group
var groupId = this._getGroupId(item.data);
var group = this.groups[groupId];
if (group) group.add(item);
};
/**
* Update an existing item
* @param {Item} item
* @param {Object} itemData
* @private
*/
ItemSet.prototype._updateItem = function(item, itemData) {
var oldGroupId = item.data.group;
// update the items data (will redraw the item when displayed)
item.setData(itemData);
// update group
if (oldGroupId != item.data.group) {
var oldGroup = this.groups[oldGroupId];
if (oldGroup) oldGroup.remove(item);
var groupId = this._getGroupId(item.data);
var group = this.groups[groupId];
if (group) group.add(item);
}
};
/**
* Delete an item from the ItemSet: remove it from the DOM, from the map
* with items, and from the map with visible items, and from the selection
* @param {Item} item
* @private
*/
ItemSet.prototype._removeItem = function(item) {
// remove from DOM
item.hide();
// remove from items
delete this.items[item.id];
// remove from selection
var index = this.selection.indexOf(item.id);
if (index != -1) this.selection.splice(index, 1);
// remove from group
item.parent && item.parent.remove(item);
};
/**
* Create an array containing all items being a range (having an end date)
* @param array
* @returns {Array}
* @private
*/
ItemSet.prototype._constructByEndArray = function(array) {
var endArray = [];
for (var i = 0; i < array.length; i++) {
if (array[i] instanceof RangeItem) {
endArray.push(array[i]);
}
}
return endArray;
};
/**
* Register the clicked item on touch, before dragStart is initiated.
*
* dragStart is initiated from a mousemove event, which can have left the item
* already resulting in an item == null
*
* @param {Event} event
* @private
*/
ItemSet.prototype._onTouch = function (event) {
// store the touched item, used in _onDragStart
this.touchParams.item = this.itemFromTarget(event);
};
/**
* Start dragging the selected events
* @param {Event} event
* @private
*/
ItemSet.prototype._onDragStart = function (event) {
if (!this.options.editable.updateTime && !this.options.editable.updateGroup) {
return;
}
var item = this.touchParams.item || null;
var me = this;
var props;
if (item && item.selected) {
var dragLeftItem = event.target.dragLeftItem;
var dragRightItem = event.target.dragRightItem;
if (dragLeftItem) {
props = {
item: dragLeftItem,
initialX: event.gesture.center.pageX,
dragLeft: true,
data: util.extend({}, item.data) // clone the items data
};
this.touchParams.itemProps = [props];
}
else if (dragRightItem) {
props = {
item: dragRightItem,
initialX: event.gesture.center.pageX,
dragRight: true,
data: util.extend({}, item.data) // clone the items data
};
this.touchParams.itemProps = [props];
}
else {
this.touchParams.itemProps = this.getSelection().map(function (id) {
var item = me.items[id];
var props = {
item: item,
initialX: event.gesture.center.pageX,
data: util.extend({}, item.data) // clone the items data
};
return props;
});
}
event.stopPropagation();
}
else if (this.options.editable.add && event.gesture.srcEvent.ctrlKey) {
// create a new range item when dragging with ctrl key down
this._onDragStartAddItem(event);
}
};
/**
* Start creating a new range item by dragging.
* @param {Event} event
* @private
*/
ItemSet.prototype._onDragStartAddItem = function (event) {
var snap = this.options.snap || null;
var xAbs = util.getAbsoluteLeft(this.dom.frame);
var x = event.gesture.center.pageX - xAbs - 10; // minus 10 to compensate for the drag starting as soon as you've moved 10px
var time = this.body.util.toTime(x);
var scale = this.body.util.getScale();
var step = this.body.util.getStep();
var start = snap ? snap(time, scale, step) : start;
var end = start;
var itemData = {
type: 'range',
start: start,
end: end,
content: 'new item'
};
var id = util.randomUUID();
itemData[this.itemsData._fieldId] = id;
var group = this.groupFromTarget(event);
if (group) {
itemData.group = group.groupId;
}
var newItem = new RangeItem(itemData, this.conversion, this.options);
newItem.id = id; // TODO: not so nice setting id afterwards
newItem.data = itemData;
this._addItem(newItem);
var props = {
item: newItem,
dragRight: true,
initialX: event.gesture.center.pageX,
data: util.extend({}, itemData)
};
this.touchParams.itemProps = [props];
event.stopPropagation();
};
/**
* Drag selected items
* @param {Event} event
* @private
*/
ItemSet.prototype._onDrag = function (event) {
event.preventDefault();
if (this.touchParams.itemProps) {
event.stopPropagation();
var me = this;
var snap = this.options.snap || null;
var xOffset = this.body.dom.root.offsetLeft + this.body.domProps.left.width;
var scale = this.body.util.getScale();
var step = this.body.util.getStep();
// move
this.touchParams.itemProps.forEach(function (props) {
var current = me.body.util.toTime(event.gesture.center.pageX - xOffset);
var initial = me.body.util.toTime(props.initialX - xOffset);
var offset = current - initial;
var itemData = util.extend({}, props.item.data); // clone the data
if (me.options.editable.updateTime) {
if (props.dragLeft) {
// drag left side of a range item
if (itemData.start != undefined) {
var initialStart = util.convert(props.data.start, 'Date');
var start = new Date(initialStart.valueOf() + offset);
itemData.start = snap ? snap(start, scale, step) : start;
}
}
else if (props.dragRight) {
// drag right side of a range item
if (itemData.end != undefined) {
var initialEnd = util.convert(props.data.end, 'Date');
var end = new Date(initialEnd.valueOf() + offset);
itemData.end = snap ? snap(end, scale, step) : end;
}
}
else {
// drag both start and end
if (itemData.start != undefined) {
var initialStart = util.convert(props.data.start, 'Date').valueOf();
var start = new Date(initialStart + offset);
if (itemData.end != undefined) {
var initialEnd = util.convert(props.data.end, 'Date');
var duration = initialEnd.valueOf() - initialStart.valueOf();
itemData.start = snap ? snap(start, scale, step) : start;
itemData.end = new Date(itemData.start.valueOf() + duration);
}
else {
itemData.start = snap ? snap(start, scale, step) : start;
}
}
}
}
if (me.options.editable.updateGroup && (!props.dragLeft && !props.dragRight)) {
if (itemData.group != undefined) {
// drag from one group to another
var group = me.groupFromTarget(event);
if (group) {
itemData.group = group.groupId;
}
}
}
// confirm moving the item
me.options.onMoving(itemData, function (itemData) {
if (itemData) {
props.item.setData(itemData);
}
});
});
this.stackDirty = true; // force re-stacking of all items next redraw
this.body.emitter.emit('change');
}
};
/**
* Move an item to another group
* @param {Item} item
* @param {String | Number} groupId
* @private
*/
ItemSet.prototype._moveToGroup = function(item, groupId) {
var group = this.groups[groupId];
if (group && group.groupId != item.data.group) {
var oldGroup = item.parent;
oldGroup.remove(item);
oldGroup.order();
group.add(item);
group.order();
item.data.group = group.groupId;
}
};
/**
* End of dragging selected items
* @param {Event} event
* @private
*/
ItemSet.prototype._onDragEnd = function (event) {
event.preventDefault();
if (this.touchParams.itemProps) {
event.stopPropagation();
// prepare a change set for the changed items
var changes = [];
var me = this;
var dataset = this.itemsData.getDataSet();
var itemProps = this.touchParams.itemProps ;
this.touchParams.itemProps = null;
itemProps.forEach(function (props) {
var id = props.item.id;
var exists = me.itemsData.get(id, me.itemOptions) != null;
if (!exists) {
// add a new item
me.options.onAdd(props.item.data, function (itemData) {
me._removeItem(props.item); // remove temporary item
if (itemData) {
me.itemsData.getDataSet().add(itemData);
}
// force re-stacking of all items next redraw
me.stackDirty = true;
me.body.emitter.emit('change');
});
}
else {
// update existing item
var itemData = util.extend({}, props.item.data); // clone the data
me.options.onMove(itemData, function (itemData) {
if (itemData) {
// apply changes
itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined)
changes.push(itemData);
}
else {
// restore original values
props.item.setData(props.data);
me.stackDirty = true; // force re-stacking of all items next redraw
me.body.emitter.emit('change');
}
});
}
});
// apply the changes to the data (if there are changes)
if (changes.length) {
dataset.update(changes);
}
}
};
/**
* Handle selecting/deselecting an item when tapping it
* @param {Event} event
* @private
*/
ItemSet.prototype._onSelectItem = function (event) {
if (!this.options.selectable) return;
var ctrlKey = event.gesture.srcEvent && event.gesture.srcEvent.ctrlKey;
var shiftKey = event.gesture.srcEvent && event.gesture.srcEvent.shiftKey;
if (ctrlKey || shiftKey) {
this._onMultiSelectItem(event);
return;
}
var oldSelection = this.getSelection();
var item = this.itemFromTarget(event);
var selection = item ? [item.id] : [];
this.setSelection(selection);
var newSelection = this.getSelection();
// emit a select event,
// except when old selection is empty and new selection is still empty
if (newSelection.length > 0 || oldSelection.length > 0) {
this.body.emitter.emit('select', {
items: newSelection
});
}
};
/**
* Handle creation and updates of an item on double tap
* @param event
* @private
*/
ItemSet.prototype._onAddItem = function (event) {
if (!this.options.selectable) return;
if (!this.options.editable.add) return;
var me = this,
snap = this.options.snap || null,
item = this.itemFromTarget(event);
if (item) {
// update item
// execute async handler to update the item (or cancel it)
var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
this.options.onUpdate(itemData, function (itemData) {
if (itemData) {
me.itemsData.getDataSet().update(itemData);
}
});
}
else {
// add item
var xAbs = util.getAbsoluteLeft(this.dom.frame);
var x = event.gesture.center.pageX - xAbs;
var start = this.body.util.toTime(x);
var scale = this.body.util.getScale();
var step = this.body.util.getStep();
var newItem = {
start: snap ? snap(start, scale, step) : start,
content: 'new item'
};
// when default type is a range, add a default end date to the new item
if (this.options.type === 'range') {
var end = this.body.util.toTime(x + this.props.width / 5);
newItem.end = snap ? snap(end, scale, step) : end;
}
newItem[this.itemsData._fieldId] = util.randomUUID();
var group = this.groupFromTarget(event);
if (group) {
newItem.group = group.groupId;
}
// execute async handler to customize (or cancel) adding an item
this.options.onAdd(newItem, function (item) {
if (item) {
me.itemsData.getDataSet().add(item);
// TODO: need to trigger a redraw?
}
});
}
};
/**
* Handle selecting/deselecting multiple items when holding an item
* @param {Event} event
* @private
*/
ItemSet.prototype._onMultiSelectItem = function (event) {
if (!this.options.selectable) return;
var selection,
item = this.itemFromTarget(event);
if (item) {
// multi select items
selection = this.getSelection(); // current selection
var shiftKey = event.gesture.touches[0] && event.gesture.touches[0].shiftKey || false;
if (shiftKey) {
// select all items between the old selection and the tapped item
// determine the selection range
selection.push(item.id);
var range = ItemSet._getItemRange(this.itemsData.get(selection, this.itemOptions));
// select all items within the selection range
selection = [];
for (var id in this.items) {
if (this.items.hasOwnProperty(id)) {
var _item = this.items[id];
var start = _item.data.start;
var end = (_item.data.end !== undefined) ? _item.data.end : start;
if (start >= range.min &&
end <= range.max &&
!(_item instanceof BackgroundItem)) {
selection.push(_item.id); // do not use id but item.id, id itself is stringified
}
}
}
}
else {
// add/remove this item from the current selection
var index = selection.indexOf(item.id);
if (index == -1) {
// item is not yet selected -> select it
selection.push(item.id);
}
else {
// item is already selected -> deselect it
selection.splice(index, 1);
}
}
this.setSelection(selection);
this.body.emitter.emit('select', {
items: this.getSelection()
});
}
};
/**
* Calculate the time range of a list of items
* @param {Array.