vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

6567 lines
201 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version 0.0.7
  8. * @date 2013-04-26
  9. *
  10. * @license
  11. * Copyright (C) 2011-2013 Almende B.V, http://almende.com
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  14. * use this file except in compliance with the License. You may obtain a copy
  15. * of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  21. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  22. * License for the specific language governing permissions and limitations under
  23. * the License.
  24. */
  25. (function(e){if("function"==typeof bootstrap)bootstrap("vis",e);else if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else if("undefined"!=typeof ses){if(!ses.ok())return;ses.makeVis=e}else"undefined"!=typeof window?window.vis=e():global.vis=e()})(function(){var define,ses,bootstrap,module,exports;
  26. return (function(e,t,n){function i(n,s){if(!t[n]){if(!e[n]){var o=typeof require=="function"&&require;if(!s&&o)return o(n,!0);if(r)return r(n,!0);throw new Error("Cannot find module '"+n+"'")}var u=t[n]={exports:{}};e[n][0].call(u.exports,function(t){var r=e[n][1][t];return i(r?r:t)},u,u.exports)}return t[n].exports}var r=typeof require=="function"&&require;for(var s=0;s<n.length;s++)i(n[s]);return i})({1:[function(require,module,exports){
  27. /**
  28. * vis.js imports
  29. */
  30. var moment = require('moment');
  31. /**
  32. * utility functions
  33. */
  34. var util = {};
  35. /**
  36. * Test whether given object is a number
  37. * @param {*} object
  38. * @return {Boolean} isNumber
  39. */
  40. util.isNumber = function isNumber(object) {
  41. return (object instanceof Number || typeof object == 'number');
  42. };
  43. /**
  44. * Test whether given object is a string
  45. * @param {*} object
  46. * @return {Boolean} isString
  47. */
  48. util.isString = function isString(object) {
  49. return (object instanceof String || typeof object == 'string');
  50. };
  51. /**
  52. * Test whether given object is a Date, or a String containing a Date
  53. * @param {Date | String} object
  54. * @return {Boolean} isDate
  55. */
  56. util.isDate = function isDate(object) {
  57. if (object instanceof Date) {
  58. return true;
  59. }
  60. else if (util.isString(object)) {
  61. // test whether this string contains a date
  62. var match = ASPDateRegex.exec(object);
  63. if (match) {
  64. return true;
  65. }
  66. else if (!isNaN(Date.parse(object))) {
  67. return true;
  68. }
  69. }
  70. return false;
  71. };
  72. /**
  73. * Test whether given object is an instance of google.visualization.DataTable
  74. * @param {*} object
  75. * @return {Boolean} isDataTable
  76. */
  77. util.isDataTable = function isDataTable(object) {
  78. return (typeof (google) !== 'undefined') &&
  79. (google.visualization) &&
  80. (google.visualization.DataTable) &&
  81. (object instanceof google.visualization.DataTable);
  82. };
  83. /**
  84. * Create a semi UUID
  85. * source: http://stackoverflow.com/a/105074/1262753
  86. * @return {String} uuid
  87. */
  88. util.randomUUID = function randomUUID () {
  89. var S4 = function () {
  90. return Math.floor(
  91. Math.random() * 0x10000 /* 65536 */
  92. ).toString(16);
  93. };
  94. return (
  95. S4() + S4() + '-' +
  96. S4() + '-' +
  97. S4() + '-' +
  98. S4() + '-' +
  99. S4() + S4() + S4()
  100. );
  101. };
  102. /**
  103. * Extend object a with the properties of object b
  104. * @param {Object} a
  105. * @param {Object} b
  106. * @return {Object} a
  107. */
  108. util.extend = function (a, b) {
  109. for (var prop in b) {
  110. if (b.hasOwnProperty(prop)) {
  111. a[prop] = b[prop];
  112. }
  113. }
  114. return a;
  115. };
  116. /**
  117. * Cast an object to another type
  118. * @param {Boolean | Number | String | Date | Null | undefined} object
  119. * @param {String | function | undefined} type Name of the type or a cast
  120. * function. Available types:
  121. * 'Boolean', 'Number', 'String',
  122. * 'Date', ISODate', 'ASPDate'.
  123. * @return {*} object
  124. * @throws Error
  125. */
  126. util.cast = function cast(object, type) {
  127. if (object === undefined) {
  128. return undefined;
  129. }
  130. if (object === null) {
  131. return null;
  132. }
  133. if (!type) {
  134. return object;
  135. }
  136. if (typeof type == 'function') {
  137. return type(object);
  138. }
  139. //noinspection FallthroughInSwitchStatementJS
  140. switch (type) {
  141. case 'boolean':
  142. case 'Boolean':
  143. return Boolean(object);
  144. case 'number':
  145. case 'Number':
  146. return Number(object);
  147. case 'string':
  148. case 'String':
  149. return String(object);
  150. case 'Date':
  151. if (util.isNumber(object)) {
  152. return new Date(object);
  153. }
  154. if (object instanceof Date) {
  155. return new Date(object.valueOf());
  156. }
  157. if (util.isString(object)) {
  158. // parse ASP.Net Date pattern,
  159. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  160. // code from http://momentjs.com/
  161. var match = ASPDateRegex.exec(object);
  162. if (match) {
  163. return new Date(Number(match[1]));
  164. }
  165. else {
  166. return moment(object).toDate(); // parse string
  167. }
  168. }
  169. else {
  170. throw new Error(
  171. 'Cannot cast object of type ' + util.getType(object) +
  172. ' to type Date');
  173. }
  174. case 'ISODate':
  175. if (object instanceof Date) {
  176. return object.toISOString();
  177. }
  178. else if (util.isNumber(object) || util.isString(object)) {
  179. return moment(object).toDate().toISOString();
  180. }
  181. else {
  182. throw new Error(
  183. 'Cannot cast object of type ' + util.getType(object) +
  184. ' to type ISODate');
  185. }
  186. case 'ASPDate':
  187. if (object instanceof Date) {
  188. return '/Date(' + object.valueOf() + ')/';
  189. }
  190. else if (util.isNumber(object) || util.isString(object)) {
  191. return '/Date(' + moment(object).valueOf() + ')/';
  192. }
  193. else {
  194. throw new Error(
  195. 'Cannot cast object of type ' + util.getType(object) +
  196. ' to type ASPDate');
  197. }
  198. default:
  199. throw new Error('Cannot cast object of type ' + util.getType(object) +
  200. ' to type "' + type + '"');
  201. }
  202. };
  203. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  204. /**
  205. * Get the type of an object, for example util.getType([]) returns 'Array'
  206. * @param {*} object
  207. * @return {String} type
  208. */
  209. util.getType = function getType(object) {
  210. var type = typeof object;
  211. if (type == 'object') {
  212. if (object == null) {
  213. return 'null';
  214. }
  215. if (object instanceof Boolean) {
  216. return 'Boolean';
  217. }
  218. if (object instanceof Number) {
  219. return 'Number';
  220. }
  221. if (object instanceof String) {
  222. return 'String';
  223. }
  224. if (object instanceof Array) {
  225. return 'Array';
  226. }
  227. if (object instanceof Date) {
  228. return 'Date';
  229. }
  230. return 'Object';
  231. }
  232. else if (type == 'number') {
  233. return 'Number';
  234. }
  235. else if (type == 'boolean') {
  236. return 'Boolean';
  237. }
  238. else if (type == 'string') {
  239. return 'String';
  240. }
  241. return type;
  242. };
  243. /**
  244. * Retrieve the absolute left value of a DOM element
  245. * @param {Element} elem A dom element, for example a div
  246. * @return {number} left The absolute left position of this element
  247. * in the browser page.
  248. */
  249. util.getAbsoluteLeft = function getAbsoluteLeft (elem) {
  250. var doc = document.documentElement;
  251. var body = document.body;
  252. var left = elem.offsetLeft;
  253. var e = elem.offsetParent;
  254. while (e != null && e != body && e != doc) {
  255. left += e.offsetLeft;
  256. left -= e.scrollLeft;
  257. e = e.offsetParent;
  258. }
  259. return left;
  260. };
  261. /**
  262. * Retrieve the absolute top value of a DOM element
  263. * @param {Element} elem A dom element, for example a div
  264. * @return {number} top The absolute top position of this element
  265. * in the browser page.
  266. */
  267. util.getAbsoluteTop = function getAbsoluteTop (elem) {
  268. var doc = document.documentElement;
  269. var body = document.body;
  270. var top = elem.offsetTop;
  271. var e = elem.offsetParent;
  272. while (e != null && e != body && e != doc) {
  273. top += e.offsetTop;
  274. top -= e.scrollTop;
  275. e = e.offsetParent;
  276. }
  277. return top;
  278. };
  279. /**
  280. * Get the absolute, vertical mouse position from an event.
  281. * @param {Event} event
  282. * @return {Number} pageY
  283. */
  284. util.getPageY = function getPageY (event) {
  285. if ('pageY' in event) {
  286. return event.pageY;
  287. }
  288. else {
  289. var clientY;
  290. if (('targetTouches' in event) && event.targetTouches.length) {
  291. clientY = event.targetTouches[0].clientY;
  292. }
  293. else {
  294. clientY = event.clientY;
  295. }
  296. var doc = document.documentElement;
  297. var body = document.body;
  298. return clientY +
  299. ( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
  300. ( doc && doc.clientTop || body && body.clientTop || 0 );
  301. }
  302. };
  303. /**
  304. * Get the absolute, horizontal mouse position from an event.
  305. * @param {Event} event
  306. * @return {Number} pageX
  307. */
  308. util.getPageX = function getPageX (event) {
  309. if ('pageY' in event) {
  310. return event.pageX;
  311. }
  312. else {
  313. var clientX;
  314. if (('targetTouches' in event) && event.targetTouches.length) {
  315. clientX = event.targetTouches[0].clientX;
  316. }
  317. else {
  318. clientX = event.clientX;
  319. }
  320. var doc = document.documentElement;
  321. var body = document.body;
  322. return clientX +
  323. ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
  324. ( doc && doc.clientLeft || body && body.clientLeft || 0 );
  325. }
  326. };
  327. /**
  328. * add a className to the given elements style
  329. * @param {Element} elem
  330. * @param {String} className
  331. */
  332. util.addClassName = function addClassName(elem, className) {
  333. var classes = elem.className.split(' ');
  334. if (classes.indexOf(className) == -1) {
  335. classes.push(className); // add the class to the array
  336. elem.className = classes.join(' ');
  337. }
  338. };
  339. /**
  340. * add a className to the given elements style
  341. * @param {Element} elem
  342. * @param {String} className
  343. */
  344. util.removeClassName = function removeClassname(elem, className) {
  345. var classes = elem.className.split(' ');
  346. var index = classes.indexOf(className);
  347. if (index != -1) {
  348. classes.splice(index, 1); // remove the class from the array
  349. elem.className = classes.join(' ');
  350. }
  351. };
  352. /**
  353. * For each method for both arrays and objects.
  354. * In case of an array, the built-in Array.forEach() is applied.
  355. * In case of an Object, the method loops over all properties of the object.
  356. * @param {Object | Array} object An Object or Array
  357. * @param {function} callback Callback method, called for each item in
  358. * the object or array with three parameters:
  359. * callback(value, index, object)
  360. */
  361. util.forEach = function forEach (object, callback) {
  362. if (object instanceof Array) {
  363. // array
  364. object.forEach(callback);
  365. }
  366. else {
  367. // object
  368. for (var key in object) {
  369. if (object.hasOwnProperty(key)) {
  370. callback(object[key], key, object);
  371. }
  372. }
  373. }
  374. };
  375. /**
  376. * Update a property in an object
  377. * @param {Object} object
  378. * @param {String} key
  379. * @param {*} value
  380. * @return {Boolean} changed
  381. */
  382. util.updateProperty = function updateProp (object, key, value) {
  383. if (object[key] !== value) {
  384. object[key] = value;
  385. return true;
  386. }
  387. else {
  388. return false;
  389. }
  390. };
  391. /**
  392. * Add and event listener. Works for all browsers
  393. * @param {Element} element An html element
  394. * @param {string} action The action, for example "click",
  395. * without the prefix "on"
  396. * @param {function} listener The callback function to be executed
  397. * @param {boolean} [useCapture]
  398. */
  399. util.addEventListener = function addEventListener(element, action, listener, useCapture) {
  400. if (element.addEventListener) {
  401. if (useCapture === undefined)
  402. useCapture = false;
  403. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  404. action = "DOMMouseScroll"; // For Firefox
  405. }
  406. element.addEventListener(action, listener, useCapture);
  407. } else {
  408. element.attachEvent("on" + action, listener); // IE browsers
  409. }
  410. };
  411. /**
  412. * Remove an event listener from an element
  413. * @param {Element} element An html dom element
  414. * @param {string} action The name of the event, for example "mousedown"
  415. * @param {function} listener The listener function
  416. * @param {boolean} [useCapture]
  417. */
  418. util.removeEventListener = function removeEventListener(element, action, listener, useCapture) {
  419. if (element.removeEventListener) {
  420. // non-IE browsers
  421. if (useCapture === undefined)
  422. useCapture = false;
  423. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  424. action = "DOMMouseScroll"; // For Firefox
  425. }
  426. element.removeEventListener(action, listener, useCapture);
  427. } else {
  428. // IE browsers
  429. element.detachEvent("on" + action, listener);
  430. }
  431. };
  432. /**
  433. * Get HTML element which is the target of the event
  434. * @param {Event} event
  435. * @return {Element} target element
  436. */
  437. util.getTarget = function getTarget(event) {
  438. // code from http://www.quirksmode.org/js/events_properties.html
  439. if (!event) {
  440. event = window.event;
  441. }
  442. var target;
  443. if (event.target) {
  444. target = event.target;
  445. }
  446. else if (event.srcElement) {
  447. target = event.srcElement;
  448. }
  449. if (target.nodeType != undefined && target.nodeType == 3) {
  450. // defeat Safari bug
  451. target = target.parentNode;
  452. }
  453. return target;
  454. };
  455. /**
  456. * Stop event propagation
  457. */
  458. util.stopPropagation = function stopPropagation(event) {
  459. if (!event)
  460. event = window.event;
  461. if (event.stopPropagation) {
  462. event.stopPropagation(); // non-IE browsers
  463. }
  464. else {
  465. event.cancelBubble = true; // IE browsers
  466. }
  467. };
  468. /**
  469. * Cancels the event if it is cancelable, without stopping further propagation of the event.
  470. */
  471. util.preventDefault = function preventDefault (event) {
  472. if (!event)
  473. event = window.event;
  474. if (event.preventDefault) {
  475. event.preventDefault(); // non-IE browsers
  476. }
  477. else {
  478. event.returnValue = false; // IE browsers
  479. }
  480. };
  481. util.option = {};
  482. /**
  483. * Cast a value as boolean
  484. * @param {Boolean | function | undefined} value
  485. * @param {Boolean} [defaultValue]
  486. * @returns {Boolean} bool
  487. */
  488. util.option.asBoolean = function (value, defaultValue) {
  489. if (typeof value == 'function') {
  490. value = value();
  491. }
  492. if (value != null) {
  493. return (value != false);
  494. }
  495. return defaultValue || null;
  496. };
  497. /**
  498. * Cast a value as number
  499. * @param {Boolean | function | undefined} value
  500. * @param {Number} [defaultValue]
  501. * @returns {Number} number
  502. */
  503. util.option.asNumber = function (value, defaultValue) {
  504. if (typeof value == 'function') {
  505. value = value();
  506. }
  507. if (value != null) {
  508. return Number(value);
  509. }
  510. return defaultValue || null;
  511. };
  512. /**
  513. * Cast a value as string
  514. * @param {String | function | undefined} value
  515. * @param {String} [defaultValue]
  516. * @returns {String} str
  517. */
  518. util.option.asString = function (value, defaultValue) {
  519. if (typeof value == 'function') {
  520. value = value();
  521. }
  522. if (value != null) {
  523. return String(value);
  524. }
  525. return defaultValue || null;
  526. };
  527. /**
  528. * Cast a size or location in pixels or a percentage
  529. * @param {String | Number | function | undefined} value
  530. * @param {String} [defaultValue]
  531. * @returns {String} size
  532. */
  533. util.option.asSize = function (value, defaultValue) {
  534. if (typeof value == 'function') {
  535. value = value();
  536. }
  537. if (util.isString(value)) {
  538. return value;
  539. }
  540. else if (util.isNumber(value)) {
  541. return value + 'px';
  542. }
  543. else {
  544. return defaultValue || null;
  545. }
  546. };
  547. /**
  548. * Cast a value as DOM element
  549. * @param {HTMLElement | function | undefined} value
  550. * @param {HTMLElement} [defaultValue]
  551. * @returns {HTMLElement | null} dom
  552. */
  553. util.option.asElement = function (value, defaultValue) {
  554. if (typeof value == 'function') {
  555. value = value();
  556. }
  557. return value || defaultValue || null;
  558. };
  559. /**
  560. * load css from text
  561. * @param {String} css Text containing css
  562. */
  563. util.loadCss = function (css) {
  564. // get the script location, and built the css file name from the js file name
  565. // http://stackoverflow.com/a/2161748/1262753
  566. var scripts = document.getElementsByTagName('script');
  567. // var jsFile = scripts[scripts.length-1].src.split('?')[0];
  568. // var cssFile = jsFile.substring(0, jsFile.length - 2) + 'css';
  569. // inject css
  570. // http://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript
  571. var style = document.createElement('style');
  572. style.type = 'text/css';
  573. if (style.styleSheet){
  574. style.styleSheet.cssText = css;
  575. } else {
  576. style.appendChild(document.createTextNode(css));
  577. }
  578. document.getElementsByTagName('head')[0].appendChild(style);
  579. };
  580. // Internet Explorer 8 and older does not support Array.indexOf, so we define
  581. // it here in that case.
  582. // http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
  583. if(!Array.prototype.indexOf) {
  584. Array.prototype.indexOf = function(obj){
  585. for(var i = 0; i < this.length; i++){
  586. if(this[i] == obj){
  587. return i;
  588. }
  589. }
  590. return -1;
  591. };
  592. try {
  593. console.log("Warning: Ancient browser detected. Please update your browser");
  594. }
  595. catch (err) {
  596. }
  597. }
  598. // Internet Explorer 8 and older does not support Array.forEach, so we define
  599. // it here in that case.
  600. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
  601. if (!Array.prototype.forEach) {
  602. Array.prototype.forEach = function(fn, scope) {
  603. for(var i = 0, len = this.length; i < len; ++i) {
  604. fn.call(scope || this, this[i], i, this);
  605. }
  606. }
  607. }
  608. // Internet Explorer 8 and older does not support Array.map, so we define it
  609. // here in that case.
  610. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
  611. // Production steps of ECMA-262, Edition 5, 15.4.4.19
  612. // Reference: http://es5.github.com/#x15.4.4.19
  613. if (!Array.prototype.map) {
  614. Array.prototype.map = function(callback, thisArg) {
  615. var T, A, k;
  616. if (this == null) {
  617. throw new TypeError(" this is null or not defined");
  618. }
  619. // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
  620. var O = Object(this);
  621. // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
  622. // 3. Let len be ToUint32(lenValue).
  623. var len = O.length >>> 0;
  624. // 4. If IsCallable(callback) is false, throw a TypeError exception.
  625. // See: http://es5.github.com/#x9.11
  626. if (typeof callback !== "function") {
  627. throw new TypeError(callback + " is not a function");
  628. }
  629. // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
  630. if (thisArg) {
  631. T = thisArg;
  632. }
  633. // 6. Let A be a new array created as if by the expression new Array(len) where Array is
  634. // the standard built-in constructor with that name and len is the value of len.
  635. A = new Array(len);
  636. // 7. Let k be 0
  637. k = 0;
  638. // 8. Repeat, while k < len
  639. while(k < len) {
  640. var kValue, mappedValue;
  641. // a. Let Pk be ToString(k).
  642. // This is implicit for LHS operands of the in operator
  643. // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
  644. // This step can be combined with c
  645. // c. If kPresent is true, then
  646. if (k in O) {
  647. // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
  648. kValue = O[ k ];
  649. // ii. Let mappedValue be the result of calling the Call internal method of callback
  650. // with T as the this value and argument list containing kValue, k, and O.
  651. mappedValue = callback.call(T, kValue, k, O);
  652. // iii. Call the DefineOwnProperty internal method of A with arguments
  653. // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
  654. // and false.
  655. // In browsers that support Object.defineProperty, use the following:
  656. // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });
  657. // For best browser support, use the following:
  658. A[ k ] = mappedValue;
  659. }
  660. // d. Increase k by 1.
  661. k++;
  662. }
  663. // 9. return A
  664. return A;
  665. };
  666. }
  667. // Internet Explorer 8 and older does not support Array.filter, so we define it
  668. // here in that case.
  669. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
  670. if (!Array.prototype.filter) {
  671. Array.prototype.filter = function(fun /*, thisp */) {
  672. "use strict";
  673. if (this == null) {
  674. throw new TypeError();
  675. }
  676. var t = Object(this);
  677. var len = t.length >>> 0;
  678. if (typeof fun != "function") {
  679. throw new TypeError();
  680. }
  681. var res = [];
  682. var thisp = arguments[1];
  683. for (var i = 0; i < len; i++) {
  684. if (i in t) {
  685. var val = t[i]; // in case fun mutates this
  686. if (fun.call(thisp, val, i, t))
  687. res.push(val);
  688. }
  689. }
  690. return res;
  691. };
  692. }
  693. // Internet Explorer 8 and older does not support Object.keys, so we define it
  694. // here in that case.
  695. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys
  696. if (!Object.keys) {
  697. Object.keys = (function () {
  698. var hasOwnProperty = Object.prototype.hasOwnProperty,
  699. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  700. dontEnums = [
  701. 'toString',
  702. 'toLocaleString',
  703. 'valueOf',
  704. 'hasOwnProperty',
  705. 'isPrototypeOf',
  706. 'propertyIsEnumerable',
  707. 'constructor'
  708. ],
  709. dontEnumsLength = dontEnums.length;
  710. return function (obj) {
  711. if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
  712. throw new TypeError('Object.keys called on non-object');
  713. }
  714. var result = [];
  715. for (var prop in obj) {
  716. if (hasOwnProperty.call(obj, prop)) result.push(prop);
  717. }
  718. if (hasDontEnumBug) {
  719. for (var i=0; i < dontEnumsLength; i++) {
  720. if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
  721. }
  722. }
  723. return result;
  724. }
  725. })()
  726. }
  727. // Internet Explorer 8 and older does not support Array.isArray,
  728. // so we define it here in that case.
  729. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray
  730. if(!Array.isArray) {
  731. Array.isArray = function (vArg) {
  732. return Object.prototype.toString.call(vArg) === "[object Array]";
  733. };
  734. }
  735. /**
  736. * Event listener (singleton)
  737. */
  738. var events = {
  739. 'listeners': [],
  740. /**
  741. * Find a single listener by its object
  742. * @param {Object} object
  743. * @return {Number} index -1 when not found
  744. */
  745. 'indexOf': function (object) {
  746. var listeners = this.listeners;
  747. for (var i = 0, iMax = this.listeners.length; i < iMax; i++) {
  748. var listener = listeners[i];
  749. if (listener && listener.object == object) {
  750. return i;
  751. }
  752. }
  753. return -1;
  754. },
  755. /**
  756. * Add an event listener
  757. * @param {Object} object
  758. * @param {String} event The name of an event, for example 'select'
  759. * @param {function} callback The callback method, called when the
  760. * event takes place
  761. */
  762. 'addListener': function (object, event, callback) {
  763. var index = this.indexOf(object);
  764. var listener = this.listeners[index];
  765. if (!listener) {
  766. listener = {
  767. 'object': object,
  768. 'events': {}
  769. };
  770. this.listeners.push(listener);
  771. }
  772. var callbacks = listener.events[event];
  773. if (!callbacks) {
  774. callbacks = [];
  775. listener.events[event] = callbacks;
  776. }
  777. // add the callback if it does not yet exist
  778. if (callbacks.indexOf(callback) == -1) {
  779. callbacks.push(callback);
  780. }
  781. },
  782. /**
  783. * Remove an event listener
  784. * @param {Object} object
  785. * @param {String} event The name of an event, for example 'select'
  786. * @param {function} callback The registered callback method
  787. */
  788. 'removeListener': function (object, event, callback) {
  789. var index = this.indexOf(object);
  790. var listener = this.listeners[index];
  791. if (listener) {
  792. var callbacks = listener.events[event];
  793. if (callbacks) {
  794. index = callbacks.indexOf(callback);
  795. if (index != -1) {
  796. callbacks.splice(index, 1);
  797. }
  798. // remove the array when empty
  799. if (callbacks.length == 0) {
  800. delete listener.events[event];
  801. }
  802. }
  803. // count the number of registered events. remove listener when empty
  804. var count = 0;
  805. var events = listener.events;
  806. for (var e in events) {
  807. if (events.hasOwnProperty(e)) {
  808. count++;
  809. }
  810. }
  811. if (count == 0) {
  812. delete this.listeners[index];
  813. }
  814. }
  815. },
  816. /**
  817. * Remove all registered event listeners
  818. */
  819. 'removeAllListeners': function () {
  820. this.listeners = [];
  821. },
  822. /**
  823. * Trigger an event. All registered event handlers will be called
  824. * @param {Object} object
  825. * @param {String} event
  826. * @param {Object} properties (optional)
  827. */
  828. 'trigger': function (object, event, properties) {
  829. var index = this.indexOf(object);
  830. var listener = this.listeners[index];
  831. if (listener) {
  832. var callbacks = listener.events[event];
  833. if (callbacks) {
  834. for (var i = 0, iMax = callbacks.length; i < iMax; i++) {
  835. callbacks[i](properties);
  836. }
  837. }
  838. }
  839. }
  840. };
  841. /**
  842. * @constructor TimeStep
  843. * The class TimeStep is an iterator for dates. You provide a start date and an
  844. * end date. The class itself determines the best scale (step size) based on the
  845. * provided start Date, end Date, and minimumStep.
  846. *
  847. * If minimumStep is provided, the step size is chosen as close as possible
  848. * to the minimumStep but larger than minimumStep. If minimumStep is not
  849. * provided, the scale is set to 1 DAY.
  850. * The minimumStep should correspond with the onscreen size of about 6 characters
  851. *
  852. * Alternatively, you can set a scale by hand.
  853. * After creation, you can initialize the class by executing first(). Then you
  854. * can iterate from the start date to the end date via next(). You can check if
  855. * the end date is reached with the function hasNext(). After each step, you can
  856. * retrieve the current date via getCurrent().
  857. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  858. * days, to years.
  859. *
  860. * Version: 1.2
  861. *
  862. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  863. * or new Date(2010, 9, 21, 23, 45, 00)
  864. * @param {Date} [end] The end date
  865. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  866. */
  867. TimeStep = function(start, end, minimumStep) {
  868. // variables
  869. this.current = new Date();
  870. this._start = new Date();
  871. this._end = new Date();
  872. this.autoScale = true;
  873. this.scale = TimeStep.SCALE.DAY;
  874. this.step = 1;
  875. // initialize the range
  876. this.setRange(start, end, minimumStep);
  877. };
  878. /// enum scale
  879. TimeStep.SCALE = {
  880. MILLISECOND: 1,
  881. SECOND: 2,
  882. MINUTE: 3,
  883. HOUR: 4,
  884. DAY: 5,
  885. WEEKDAY: 6,
  886. MONTH: 7,
  887. YEAR: 8
  888. };
  889. /**
  890. * Set a new range
  891. * If minimumStep is provided, the step size is chosen as close as possible
  892. * to the minimumStep but larger than minimumStep. If minimumStep is not
  893. * provided, the scale is set to 1 DAY.
  894. * The minimumStep should correspond with the onscreen size of about 6 characters
  895. * @param {Date} start The start date and time.
  896. * @param {Date} end The end date and time.
  897. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  898. */
  899. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  900. if (!(start instanceof Date) || !(end instanceof Date)) {
  901. //throw "No legal start or end date in method setRange";
  902. return;
  903. }
  904. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  905. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  906. if (this.autoScale) {
  907. this.setMinimumStep(minimumStep);
  908. }
  909. };
  910. /**
  911. * Set the range iterator to the start date.
  912. */
  913. TimeStep.prototype.first = function() {
  914. this.current = new Date(this._start.valueOf());
  915. this.roundToMinor();
  916. };
  917. /**
  918. * Round the current date to the first minor date value
  919. * This must be executed once when the current date is set to start Date
  920. */
  921. TimeStep.prototype.roundToMinor = function() {
  922. // round to floor
  923. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  924. //noinspection FallthroughInSwitchStatementJS
  925. switch (this.scale) {
  926. case TimeStep.SCALE.YEAR:
  927. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  928. this.current.setMonth(0);
  929. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  930. case TimeStep.SCALE.DAY: // intentional fall through
  931. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  932. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  933. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  934. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  935. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  936. }
  937. if (this.step != 1) {
  938. // round down to the first minor value that is a multiple of the current step size
  939. switch (this.scale) {
  940. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  941. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  942. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  943. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  944. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  945. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  946. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  947. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  948. default: break;
  949. }
  950. }
  951. };
  952. /**
  953. * Check if the there is a next step
  954. * @return {boolean} true if the current date has not passed the end date
  955. */
  956. TimeStep.prototype.hasNext = function () {
  957. return (this.current.valueOf() <= this._end.valueOf());
  958. };
  959. /**
  960. * Do the next step
  961. */
  962. TimeStep.prototype.next = function() {
  963. var prev = this.current.valueOf();
  964. // Two cases, needed to prevent issues with switching daylight savings
  965. // (end of March and end of October)
  966. if (this.current.getMonth() < 6) {
  967. switch (this.scale) {
  968. case TimeStep.SCALE.MILLISECOND:
  969. this.current = new Date(this.current.valueOf() + this.step); break;
  970. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  971. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  972. case TimeStep.SCALE.HOUR:
  973. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  974. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  975. var h = this.current.getHours();
  976. this.current.setHours(h - (h % this.step));
  977. break;
  978. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  979. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  980. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  981. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  982. default: break;
  983. }
  984. }
  985. else {
  986. switch (this.scale) {
  987. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  988. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  989. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  990. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  991. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  992. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  993. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  994. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  995. default: break;
  996. }
  997. }
  998. if (this.step != 1) {
  999. // round down to the correct major value
  1000. switch (this.scale) {
  1001. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  1002. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  1003. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  1004. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  1005. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  1006. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  1007. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  1008. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  1009. default: break;
  1010. }
  1011. }
  1012. // safety mechanism: if current time is still unchanged, move to the end
  1013. if (this.current.valueOf() == prev) {
  1014. this.current = new Date(this._end.valueOf());
  1015. }
  1016. };
  1017. /**
  1018. * Get the current datetime
  1019. * @return {Date} current The current date
  1020. */
  1021. TimeStep.prototype.getCurrent = function() {
  1022. return this.current;
  1023. };
  1024. /**
  1025. * Set a custom scale. Autoscaling will be disabled.
  1026. * For example setScale(SCALE.MINUTES, 5) will result
  1027. * in minor steps of 5 minutes, and major steps of an hour.
  1028. *
  1029. * @param {TimeStep.SCALE} newScale
  1030. * A scale. Choose from SCALE.MILLISECOND,
  1031. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  1032. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  1033. * SCALE.YEAR.
  1034. * @param {Number} newStep A step size, by default 1. Choose for
  1035. * example 1, 2, 5, or 10.
  1036. */
  1037. TimeStep.prototype.setScale = function(newScale, newStep) {
  1038. this.scale = newScale;
  1039. if (newStep > 0) {
  1040. this.step = newStep;
  1041. }
  1042. this.autoScale = false;
  1043. };
  1044. /**
  1045. * Enable or disable autoscaling
  1046. * @param {boolean} enable If true, autoascaling is set true
  1047. */
  1048. TimeStep.prototype.setAutoScale = function (enable) {
  1049. this.autoScale = enable;
  1050. };
  1051. /**
  1052. * Automatically determine the scale that bests fits the provided minimum step
  1053. * @param {Number} minimumStep The minimum step size in milliseconds
  1054. */
  1055. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  1056. if (minimumStep == undefined) {
  1057. return;
  1058. }
  1059. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  1060. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  1061. var stepDay = (1000 * 60 * 60 * 24);
  1062. var stepHour = (1000 * 60 * 60);
  1063. var stepMinute = (1000 * 60);
  1064. var stepSecond = (1000);
  1065. var stepMillisecond= (1);
  1066. // find the smallest step that is larger than the provided minimumStep
  1067. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  1068. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  1069. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  1070. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  1071. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  1072. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  1073. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  1074. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  1075. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  1076. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  1077. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  1078. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  1079. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  1080. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  1081. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  1082. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  1083. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  1084. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  1085. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  1086. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  1087. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  1088. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  1089. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  1090. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  1091. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  1092. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  1093. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  1094. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  1095. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  1096. };
  1097. /**
  1098. * Snap a date to a rounded value. The snap intervals are dependent on the
  1099. * current scale and step.
  1100. * @param {Date} date the date to be snapped
  1101. */
  1102. TimeStep.prototype.snap = function(date) {
  1103. if (this.scale == TimeStep.SCALE.YEAR) {
  1104. var year = date.getFullYear() + Math.round(date.getMonth() / 12);
  1105. date.setFullYear(Math.round(year / this.step) * this.step);
  1106. date.setMonth(0);
  1107. date.setDate(0);
  1108. date.setHours(0);
  1109. date.setMinutes(0);
  1110. date.setSeconds(0);
  1111. date.setMilliseconds(0);
  1112. }
  1113. else if (this.scale == TimeStep.SCALE.MONTH) {
  1114. if (date.getDate() > 15) {
  1115. date.setDate(1);
  1116. date.setMonth(date.getMonth() + 1);
  1117. // important: first set Date to 1, after that change the month.
  1118. }
  1119. else {
  1120. date.setDate(1);
  1121. }
  1122. date.setHours(0);
  1123. date.setMinutes(0);
  1124. date.setSeconds(0);
  1125. date.setMilliseconds(0);
  1126. }
  1127. else if (this.scale == TimeStep.SCALE.DAY ||
  1128. this.scale == TimeStep.SCALE.WEEKDAY) {
  1129. //noinspection FallthroughInSwitchStatementJS
  1130. switch (this.step) {
  1131. case 5:
  1132. case 2:
  1133. date.setHours(Math.round(date.getHours() / 24) * 24); break;
  1134. default:
  1135. date.setHours(Math.round(date.getHours() / 12) * 12); break;
  1136. }
  1137. date.setMinutes(0);
  1138. date.setSeconds(0);
  1139. date.setMilliseconds(0);
  1140. }
  1141. else if (this.scale == TimeStep.SCALE.HOUR) {
  1142. switch (this.step) {
  1143. case 4:
  1144. date.setMinutes(Math.round(date.getMinutes() / 60) * 60); break;
  1145. default:
  1146. date.setMinutes(Math.round(date.getMinutes() / 30) * 30); break;
  1147. }
  1148. date.setSeconds(0);
  1149. date.setMilliseconds(0);
  1150. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  1151. //noinspection FallthroughInSwitchStatementJS
  1152. switch (this.step) {
  1153. case 15:
  1154. case 10:
  1155. date.setMinutes(Math.round(date.getMinutes() / 5) * 5);
  1156. date.setSeconds(0);
  1157. break;
  1158. case 5:
  1159. date.setSeconds(Math.round(date.getSeconds() / 60) * 60); break;
  1160. default:
  1161. date.setSeconds(Math.round(date.getSeconds() / 30) * 30); break;
  1162. }
  1163. date.setMilliseconds(0);
  1164. }
  1165. else if (this.scale == TimeStep.SCALE.SECOND) {
  1166. //noinspection FallthroughInSwitchStatementJS
  1167. switch (this.step) {
  1168. case 15:
  1169. case 10:
  1170. date.setSeconds(Math.round(date.getSeconds() / 5) * 5);
  1171. date.setMilliseconds(0);
  1172. break;
  1173. case 5:
  1174. date.setMilliseconds(Math.round(date.getMilliseconds() / 1000) * 1000); break;
  1175. default:
  1176. date.setMilliseconds(Math.round(date.getMilliseconds() / 500) * 500); break;
  1177. }
  1178. }
  1179. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  1180. var step = this.step > 5 ? this.step / 2 : 1;
  1181. date.setMilliseconds(Math.round(date.getMilliseconds() / step) * step);
  1182. }
  1183. };
  1184. /**
  1185. * Check if the current value is a major value (for example when the step
  1186. * is DAY, a major value is each first day of the MONTH)
  1187. * @return {boolean} true if current date is major, else false.
  1188. */
  1189. TimeStep.prototype.isMajor = function() {
  1190. switch (this.scale) {
  1191. case TimeStep.SCALE.MILLISECOND:
  1192. return (this.current.getMilliseconds() == 0);
  1193. case TimeStep.SCALE.SECOND:
  1194. return (this.current.getSeconds() == 0);
  1195. case TimeStep.SCALE.MINUTE:
  1196. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  1197. // Note: this is no bug. Major label is equal for both minute and hour scale
  1198. case TimeStep.SCALE.HOUR:
  1199. return (this.current.getHours() == 0);
  1200. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  1201. case TimeStep.SCALE.DAY:
  1202. return (this.current.getDate() == 1);
  1203. case TimeStep.SCALE.MONTH:
  1204. return (this.current.getMonth() == 0);
  1205. case TimeStep.SCALE.YEAR:
  1206. return false;
  1207. default:
  1208. return false;
  1209. }
  1210. };
  1211. /**
  1212. * Returns formatted text for the minor axislabel, depending on the current
  1213. * date and the scale. For example when scale is MINUTE, the current time is
  1214. * formatted as "hh:mm".
  1215. * @param {Date} [date] custom date. if not provided, current date is taken
  1216. */
  1217. TimeStep.prototype.getLabelMinor = function(date) {
  1218. if (date == undefined) {
  1219. date = this.current;
  1220. }
  1221. switch (this.scale) {
  1222. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  1223. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  1224. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  1225. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  1226. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  1227. case TimeStep.SCALE.DAY: return moment(date).format('D');
  1228. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  1229. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  1230. default: return '';
  1231. }
  1232. };
  1233. /**
  1234. * Returns formatted text for the major axislabel, depending on the current
  1235. * date and the scale. For example when scale is MINUTE, the major scale is
  1236. * hours, and the hour will be formatted as "hh".
  1237. * @param {Date} [date] custom date. if not provided, current date is taken
  1238. */
  1239. TimeStep.prototype.getLabelMajor = function(date) {
  1240. if (date == undefined) {
  1241. date = this.current;
  1242. }
  1243. //noinspection FallthroughInSwitchStatementJS
  1244. switch (this.scale) {
  1245. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  1246. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  1247. case TimeStep.SCALE.MINUTE:
  1248. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  1249. case TimeStep.SCALE.WEEKDAY:
  1250. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  1251. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  1252. case TimeStep.SCALE.YEAR: return '';
  1253. default: return '';
  1254. }
  1255. };
  1256. /**
  1257. * DataSet
  1258. *
  1259. * Usage:
  1260. * var dataSet = new DataSet({
  1261. * fieldId: '_id',
  1262. * fieldTypes: {
  1263. * // ...
  1264. * }
  1265. * });
  1266. *
  1267. * dataSet.add(item);
  1268. * dataSet.add(data);
  1269. * dataSet.update(item);
  1270. * dataSet.update(data);
  1271. * dataSet.remove(id);
  1272. * dataSet.remove(ids);
  1273. * var data = dataSet.get();
  1274. * var data = dataSet.get(id);
  1275. * var data = dataSet.get(ids);
  1276. * var data = dataSet.get(ids, options, data);
  1277. * dataSet.clear();
  1278. *
  1279. * A data set can:
  1280. * - add/remove/update data
  1281. * - gives triggers upon changes in the data
  1282. * - can import/export data in various data formats
  1283. * @param {Object} [options] Available options:
  1284. * {String} fieldId Field name of the id in the
  1285. * items, 'id' by default.
  1286. * {Object.<String, String} fieldTypes
  1287. * A map with field names as key,
  1288. * and the field type as value.
  1289. */
  1290. function DataSet (options) {
  1291. var me = this;
  1292. this.options = options || {};
  1293. this.data = {}; // map with data indexed by id
  1294. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  1295. this.fieldTypes = {}; // field types by field name
  1296. if (this.options.fieldTypes) {
  1297. util.forEach(this.options.fieldTypes, function (value, field) {
  1298. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1299. me.fieldTypes[field] = 'Date';
  1300. }
  1301. else {
  1302. me.fieldTypes[field] = value;
  1303. }
  1304. });
  1305. }
  1306. // event subscribers
  1307. this.subscribers = {};
  1308. this.internalIds = {}; // internally generated id's
  1309. }
  1310. /**
  1311. * Subscribe to an event, add an event listener
  1312. * @param {String} event Event name. Available events: 'put', 'update',
  1313. * 'remove'
  1314. * @param {function} callback Callback method. Called with three parameters:
  1315. * {String} event
  1316. * {Object | null} params
  1317. * {String} senderId
  1318. * @param {String} [id] Optional id for the sender, used to filter
  1319. * events triggered by the sender itself.
  1320. */
  1321. DataSet.prototype.subscribe = function (event, callback, id) {
  1322. var subscribers = this.subscribers[event];
  1323. if (!subscribers) {
  1324. subscribers = [];
  1325. this.subscribers[event] = subscribers;
  1326. }
  1327. subscribers.push({
  1328. id: id ? String(id) : null,
  1329. callback: callback
  1330. });
  1331. };
  1332. /**
  1333. * Unsubscribe from an event, remove an event listener
  1334. * @param {String} event
  1335. * @param {function} callback
  1336. */
  1337. DataSet.prototype.unsubscribe = function (event, callback) {
  1338. var subscribers = this.subscribers[event];
  1339. if (subscribers) {
  1340. this.subscribers[event] = subscribers.filter(function (listener) {
  1341. return (listener.callback != callback);
  1342. });
  1343. }
  1344. };
  1345. /**
  1346. * Trigger an event
  1347. * @param {String} event
  1348. * @param {Object | null} params
  1349. * @param {String} [senderId] Optional id of the sender. The event will
  1350. * be triggered for all subscribers except the
  1351. * sender itself.
  1352. * @private
  1353. */
  1354. DataSet.prototype._trigger = function (event, params, senderId) {
  1355. if (event == '*') {
  1356. throw new Error('Cannot trigger event *');
  1357. }
  1358. var subscribers = [];
  1359. if (event in this.subscribers) {
  1360. subscribers = subscribers.concat(this.subscribers[event]);
  1361. }
  1362. if ('*' in this.subscribers) {
  1363. subscribers = subscribers.concat(this.subscribers['*']);
  1364. }
  1365. subscribers.forEach(function (listener) {
  1366. if (listener.id != senderId && listener.callback) {
  1367. listener.callback(event, params, senderId || null);
  1368. }
  1369. });
  1370. };
  1371. /**
  1372. * Add data. Existing items with the same id will be overwritten.
  1373. * @param {Object | Array | DataTable} data
  1374. * @param {String} [senderId] Optional sender id, used to trigger events for
  1375. * all but this sender's event subscribers.
  1376. */
  1377. DataSet.prototype.add = function (data, senderId) {
  1378. var items = [],
  1379. id,
  1380. me = this;
  1381. if (data instanceof Array) {
  1382. // Array
  1383. data.forEach(function (item) {
  1384. var id = me._addItem(item);
  1385. items.push(id);
  1386. });
  1387. }
  1388. else if (util.isDataTable(data)) {
  1389. // Google DataTable
  1390. var columns = this._getColumnNames(data);
  1391. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1392. var item = {};
  1393. columns.forEach(function (field, col) {
  1394. item[field] = data.getValue(row, col);
  1395. });
  1396. id = me._addItem(item);
  1397. items.push(id);
  1398. }
  1399. }
  1400. else if (data instanceof Object) {
  1401. // Single item
  1402. id = me._addItem(data);
  1403. items.push(id);
  1404. }
  1405. else {
  1406. throw new Error('Unknown dataType');
  1407. }
  1408. this._trigger('add', {items: items}, senderId);
  1409. };
  1410. /**
  1411. * Update existing items. Items with the same id will be merged
  1412. * @param {Object | Array | DataTable} data
  1413. * @param {String} [senderId] Optional sender id, used to trigger events for
  1414. * all but this sender's event subscribers.
  1415. */
  1416. DataSet.prototype.update = function (data, senderId) {
  1417. var items = [],
  1418. id,
  1419. me = this;
  1420. if (data instanceof Array) {
  1421. // Array
  1422. data.forEach(function (item) {
  1423. var id = me._updateItem(item);
  1424. items.push(id);
  1425. });
  1426. }
  1427. else if (util.isDataTable(data)) {
  1428. // Google DataTable
  1429. var columns = this._getColumnNames(data);
  1430. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1431. var item = {};
  1432. columns.forEach(function (field, col) {
  1433. item[field] = data.getValue(row, col);
  1434. });
  1435. id = me._updateItem(item);
  1436. items.push(id);
  1437. }
  1438. }
  1439. else if (data instanceof Object) {
  1440. // Single item
  1441. id = me._updateItem(data);
  1442. items.push(id);
  1443. }
  1444. else {
  1445. throw new Error('Unknown dataType');
  1446. }
  1447. this._trigger('update', {items: items}, senderId);
  1448. };
  1449. /**
  1450. * Get a data item or multiple items
  1451. * @param {String | Number | Array | Object} [ids] Id of a single item, or an
  1452. * array with multiple id's, or
  1453. * undefined or an Object with options
  1454. * to retrieve all data.
  1455. * @param {Object} [options] Available options:
  1456. * {String} [type]
  1457. * 'DataTable' or 'Array' (default)
  1458. * {Object.<String, String>} [fieldTypes]
  1459. * {String[]} [fields] filter fields
  1460. * @param {Array | DataTable} [data] If provided, items will be appended
  1461. * to this array or table. Required
  1462. * in case of Google DataTable
  1463. * @return {Array | Object | DataTable | null} data
  1464. * @throws Error
  1465. */
  1466. DataSet.prototype.get = function (ids, options, data) {
  1467. var me = this;
  1468. // shift arguments when first argument contains the options
  1469. if (util.getType(ids) == 'Object') {
  1470. data = options;
  1471. options = ids;
  1472. ids = undefined;
  1473. }
  1474. // merge field types
  1475. var fieldTypes = {};
  1476. if (this.options && this.options.fieldTypes) {
  1477. util.forEach(this.options.fieldTypes, function (value, field) {
  1478. fieldTypes[field] = value;
  1479. });
  1480. }
  1481. if (options && options.fieldTypes) {
  1482. util.forEach(options.fieldTypes, function (value, field) {
  1483. fieldTypes[field] = value;
  1484. });
  1485. }
  1486. var fields = options ? options.fields : undefined;
  1487. // determine the return type
  1488. var type;
  1489. if (options && options.type) {
  1490. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  1491. if (data && (type != util.getType(data))) {
  1492. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1493. 'does not correspond with specified options.type (' + options.type + ')');
  1494. }
  1495. if (type == 'DataTable' && !util.isDataTable(data)) {
  1496. throw new Error('Parameter "data" must be a DataTable ' +
  1497. 'when options.type is "DataTable"');
  1498. }
  1499. }
  1500. else if (data) {
  1501. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1502. }
  1503. else {
  1504. type = 'Array';
  1505. }
  1506. if (type == 'DataTable') {
  1507. // return a Google DataTable
  1508. var columns = this._getColumnNames(data);
  1509. if (ids == undefined) {
  1510. // return all data
  1511. util.forEach(this.data, function (item) {
  1512. me._appendRow(data, columns, me._castItem(item));
  1513. });
  1514. }
  1515. else if (util.isNumber(ids) || util.isString(ids)) {
  1516. var item = me._castItem(me.data[ids], fieldTypes, fields);
  1517. this._appendRow(data, columns, item);
  1518. }
  1519. else if (ids instanceof Array) {
  1520. ids.forEach(function (id) {
  1521. var item = me._castItem(me.data[id], fieldTypes, fields);
  1522. me._appendRow(data, columns, item);
  1523. });
  1524. }
  1525. else {
  1526. throw new TypeError('Parameter "ids" must be ' +
  1527. 'undefined, a String, Number, or Array');
  1528. }
  1529. }
  1530. else {
  1531. // return an array
  1532. data = data || [];
  1533. if (ids == undefined) {
  1534. // return all data
  1535. util.forEach(this.data, function (item) {
  1536. data.push(me._castItem(item, fieldTypes, fields));
  1537. });
  1538. }
  1539. else if (util.isNumber(ids) || util.isString(ids)) {
  1540. // return a single item
  1541. return this._castItem(me.data[ids], fieldTypes, fields);
  1542. }
  1543. else if (ids instanceof Array) {
  1544. ids.forEach(function (id) {
  1545. data.push(me._castItem(me.data[id], fieldTypes, fields));
  1546. });
  1547. }
  1548. else {
  1549. throw new TypeError('Parameter "ids" must be ' +
  1550. 'undefined, a String, Number, or Array');
  1551. }
  1552. }
  1553. return data;
  1554. };
  1555. /**
  1556. * Remove an object by pointer or by id
  1557. * @param {String | Number | Object | Array} id Object or id, or an array with
  1558. * objects or ids to be removed
  1559. * @param {String} [senderId] Optional sender id, used to trigger events for
  1560. * all but this sender's event subscribers.
  1561. */
  1562. DataSet.prototype.remove = function (id, senderId) {
  1563. var items = [],
  1564. me = this;
  1565. if (util.isNumber(id) || util.isString(id)) {
  1566. delete this.data[id];
  1567. delete this.internalIds[id];
  1568. items.push(id);
  1569. }
  1570. else if (id instanceof Array) {
  1571. id.forEach(function (id) {
  1572. me.remove(id);
  1573. });
  1574. items = items.concat(id);
  1575. }
  1576. else if (id instanceof Object) {
  1577. // search for the object
  1578. for (var i in this.data) {
  1579. if (this.data.hasOwnProperty(i)) {
  1580. if (this.data[i] == id) {
  1581. delete this.data[i];
  1582. delete this.internalIds[i];
  1583. items.push(i);
  1584. }
  1585. }
  1586. }
  1587. }
  1588. this._trigger('remove', {items: items}, senderId);
  1589. };
  1590. /**
  1591. * Clear the data
  1592. * @param {String} [senderId] Optional sender id, used to trigger events for
  1593. * all but this sender's event subscribers.
  1594. */
  1595. DataSet.prototype.clear = function (senderId) {
  1596. var ids = Object.keys(this.data);
  1597. this.data = {};
  1598. this.internalIds = {};
  1599. this._trigger('remove', {items: ids}, senderId);
  1600. };
  1601. /**
  1602. * Find the item with maximum value of a specified field
  1603. * @param {String} field
  1604. * @return {Object} item Item containing max value, or null if no items
  1605. */
  1606. DataSet.prototype.max = function (field) {
  1607. var data = this.data,
  1608. ids = Object.keys(data);
  1609. var max = null;
  1610. var maxField = null;
  1611. ids.forEach(function (id) {
  1612. var item = data[id];
  1613. var itemField = item[field];
  1614. if (itemField != null && (!max || itemField > maxField)) {
  1615. max = item;
  1616. maxField = itemField;
  1617. }
  1618. });
  1619. return max;
  1620. };
  1621. /**
  1622. * Find the item with minimum value of a specified field
  1623. * @param {String} field
  1624. */
  1625. DataSet.prototype.min = function (field) {
  1626. var data = this.data,
  1627. ids = Object.keys(data);
  1628. var min = null;
  1629. var minField = null;
  1630. ids.forEach(function (id) {
  1631. var item = data[id];
  1632. var itemField = item[field];
  1633. if (itemField != null && (!min || itemField < minField)) {
  1634. min = item;
  1635. minField = itemField;
  1636. }
  1637. });
  1638. return min;
  1639. };
  1640. /**
  1641. * Add a single item
  1642. * @param {Object} item
  1643. * @return {String} id
  1644. * @private
  1645. */
  1646. DataSet.prototype._addItem = function (item) {
  1647. var id = item[this.fieldId];
  1648. if (id == undefined) {
  1649. // generate an id
  1650. id = util.randomUUID();
  1651. item[this.fieldId] = id;
  1652. this.internalIds[id] = item;
  1653. }
  1654. var d = {};
  1655. for (var field in item) {
  1656. if (item.hasOwnProperty(field)) {
  1657. var type = this.fieldTypes[field]; // type may be undefined
  1658. d[field] = util.cast(item[field], type);
  1659. }
  1660. }
  1661. this.data[id] = d;
  1662. //TODO: fail when an item with this id already exists?
  1663. return id;
  1664. };
  1665. /**
  1666. * Cast and filter the fields of an item
  1667. * @param {Object | undefined} item
  1668. * @param {Object.<String, String>} [fieldTypes]
  1669. * @param {String[]} [fields]
  1670. * @return {Object | null} castedItem
  1671. * @private
  1672. */
  1673. DataSet.prototype._castItem = function (item, fieldTypes, fields) {
  1674. var clone,
  1675. fieldId = this.fieldId,
  1676. internalIds = this.internalIds;
  1677. if (item) {
  1678. clone = {};
  1679. fieldTypes = fieldTypes || {};
  1680. if (fields) {
  1681. // output filtered fields
  1682. util.forEach(item, function (value, field) {
  1683. if (fields.indexOf(field) != -1) {
  1684. clone[field] = util.cast(value, fieldTypes[field]);
  1685. }
  1686. });
  1687. }
  1688. else {
  1689. // output all fields, except internal ids
  1690. util.forEach(item, function (value, field) {
  1691. if (field != fieldId || !(value in internalIds)) {
  1692. clone[field] = util.cast(value, fieldTypes[field]);
  1693. }
  1694. });
  1695. }
  1696. }
  1697. else {
  1698. clone = null;
  1699. }
  1700. return clone;
  1701. };
  1702. /**
  1703. * Update a single item: merge with existing item
  1704. * @param {Object} item
  1705. * @return {String} id
  1706. * @private
  1707. */
  1708. DataSet.prototype._updateItem = function (item) {
  1709. var id = item[this.fieldId];
  1710. if (id == undefined) {
  1711. throw new Error('Item has no id (item: ' + JSON.stringify(item) + ')');
  1712. }
  1713. var d = this.data[id];
  1714. if (d) {
  1715. // merge with current item
  1716. for (var field in item) {
  1717. if (item.hasOwnProperty(field)) {
  1718. var type = this.fieldTypes[field]; // type may be undefined
  1719. d[field] = util.cast(item[field], type);
  1720. }
  1721. }
  1722. }
  1723. else {
  1724. // create new item
  1725. this._addItem(item);
  1726. }
  1727. return id;
  1728. };
  1729. /**
  1730. * Get an array with the column names of a Google DataTable
  1731. * @param {DataTable} dataTable
  1732. * @return {Array} columnNames
  1733. * @private
  1734. */
  1735. DataSet.prototype._getColumnNames = function (dataTable) {
  1736. var columns = [];
  1737. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  1738. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  1739. }
  1740. return columns;
  1741. };
  1742. /**
  1743. * Append an item as a row to the dataTable
  1744. * @param dataTable
  1745. * @param columns
  1746. * @param item
  1747. * @private
  1748. */
  1749. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  1750. var row = dataTable.addRow();
  1751. columns.forEach(function (field, col) {
  1752. dataTable.setValue(row, col, item[field]);
  1753. });
  1754. };
  1755. /**
  1756. * @constructor Stack
  1757. * Stacks items on top of each other.
  1758. * @param {ItemSet} parent
  1759. * @param {Object} [options]
  1760. */
  1761. function Stack (parent, options) {
  1762. this.parent = parent;
  1763. this.options = {
  1764. order: function (a, b) {
  1765. return (b.width - a.width) || (a.left - b.left);
  1766. }
  1767. };
  1768. this.ordered = []; // ordered items
  1769. this.setOptions(options);
  1770. }
  1771. /**
  1772. * Set options for the stack
  1773. * @param {Object} options Available options:
  1774. * {ItemSet} parent
  1775. * {Number} margin
  1776. * {function} order Stacking order
  1777. */
  1778. Stack.prototype.setOptions = function (options) {
  1779. util.extend(this.options, options);
  1780. // TODO: register on data changes at the connected parent itemset, and update the changed part only and immediately
  1781. };
  1782. /**
  1783. * Stack the items such that they don't overlap. The items will have a minimal
  1784. * distance equal to options.margin.item.
  1785. */
  1786. Stack.prototype.update = function() {
  1787. this._order();
  1788. this._stack();
  1789. };
  1790. /**
  1791. * Order the items. The items are ordered by width first, and by left position
  1792. * second.
  1793. * If a custom order function has been provided via the options, then this will
  1794. * be used.
  1795. * @private
  1796. */
  1797. Stack.prototype._order = function() {
  1798. var items = this.parent.items;
  1799. if (!items) {
  1800. throw new Error('Cannot stack items: parent does not contain items');
  1801. }
  1802. // TODO: store the sorted items, to have less work later on
  1803. var ordered = [];
  1804. var index = 0;
  1805. util.forEach(items, function (item, id) {
  1806. ordered[index] = item;
  1807. index++;
  1808. });
  1809. //if a customer stack order function exists, use it.
  1810. var order = this.options.order;
  1811. if (!(typeof this.options.order === 'function')) {
  1812. throw new Error('Option order must be a function');
  1813. }
  1814. ordered.sort(order);
  1815. this.ordered = ordered;
  1816. };
  1817. /**
  1818. * Adjust vertical positions of the events such that they don't overlap each
  1819. * other.
  1820. * @private
  1821. */
  1822. Stack.prototype._stack = function() {
  1823. var i,
  1824. iMax,
  1825. ordered = this.ordered,
  1826. options = this.options,
  1827. axisOnTop = (options.orientation == 'top'),
  1828. margin = options.margin && options.margin.item || 0;
  1829. // calculate new, non-overlapping positions
  1830. for (i = 0, iMax = ordered.length; i < iMax; i++) {
  1831. var item = ordered[i];
  1832. var collidingItem = null;
  1833. do {
  1834. // TODO: optimize checking for overlap. when there is a gap without items,
  1835. // you only need to check for items from the next item on, not from zero
  1836. collidingItem = this.checkOverlap(ordered, i, 0, i - 1, margin);
  1837. if (collidingItem != null) {
  1838. // There is a collision. Reposition the event above the colliding element
  1839. if (axisOnTop) {
  1840. item.top = collidingItem.top + collidingItem.height + margin;
  1841. }
  1842. else {
  1843. item.top = collidingItem.top - item.height - margin;
  1844. }
  1845. }
  1846. } while (collidingItem);
  1847. }
  1848. };
  1849. /**
  1850. * Check if the destiny position of given item overlaps with any
  1851. * of the other items from index itemStart to itemEnd.
  1852. * @param {Array} items Array with items
  1853. * @param {int} itemIndex Number of the item to be checked for overlap
  1854. * @param {int} itemStart First item to be checked.
  1855. * @param {int} itemEnd Last item to be checked.
  1856. * @return {Object | null} colliding item, or undefined when no collisions
  1857. * @param {Number} margin A minimum required margin.
  1858. * If margin is provided, the two items will be
  1859. * marked colliding when they overlap or
  1860. * when the margin between the two is smaller than
  1861. * the requested margin.
  1862. */
  1863. Stack.prototype.checkOverlap = function(items, itemIndex, itemStart, itemEnd, margin) {
  1864. var collision = this.collision;
  1865. // we loop from end to start, as we suppose that the chance of a
  1866. // collision is larger for items at the end, so check these first.
  1867. var a = items[itemIndex];
  1868. for (var i = itemEnd; i >= itemStart; i--) {
  1869. var b = items[i];
  1870. if (collision(a, b, margin)) {
  1871. if (i != itemIndex) {
  1872. return b;
  1873. }
  1874. }
  1875. }
  1876. return null;
  1877. };
  1878. /**
  1879. * Test if the two provided items collide
  1880. * The items must have parameters left, width, top, and height.
  1881. * @param {Component} a The first item
  1882. * @param {Component} b The second item
  1883. * @param {Number} margin A minimum required margin.
  1884. * If margin is provided, the two items will be
  1885. * marked colliding when they overlap or
  1886. * when the margin between the two is smaller than
  1887. * the requested margin.
  1888. * @return {boolean} true if a and b collide, else false
  1889. */
  1890. Stack.prototype.collision = function(a, b, margin) {
  1891. return ((a.left - margin) < (b.left + b.width) &&
  1892. (a.left + a.width + margin) > b.left &&
  1893. (a.top - margin) < (b.top + b.height) &&
  1894. (a.top + a.height + margin) > b.top);
  1895. };
  1896. /**
  1897. * @constructor Range
  1898. * A Range controls a numeric range with a start and end value.
  1899. * The Range adjusts the range based on mouse events or programmatic changes,
  1900. * and triggers events when the range is changing or has been changed.
  1901. * @param {Object} [options] See description at Range.setOptions
  1902. * @extends Controller
  1903. */
  1904. function Range(options) {
  1905. this.id = util.randomUUID();
  1906. this.start = 0; // Number
  1907. this.end = 0; // Number
  1908. this.options = {
  1909. min: null,
  1910. max: null,
  1911. zoomMin: null,
  1912. zoomMax: null
  1913. };
  1914. this.setOptions(options);
  1915. this.listeners = [];
  1916. }
  1917. /**
  1918. * Set options for the range controller
  1919. * @param {Object} options Available options:
  1920. * {Number} start Set start value of the range
  1921. * {Number} end Set end value of the range
  1922. * {Number} min Minimum value for start
  1923. * {Number} max Maximum value for end
  1924. * {Number} zoomMin Set a minimum value for
  1925. * (end - start).
  1926. * {Number} zoomMax Set a maximum value for
  1927. * (end - start).
  1928. */
  1929. Range.prototype.setOptions = function (options) {
  1930. util.extend(this.options, options);
  1931. if (options.start != null || options.end != null) {
  1932. this.setRange(options.start, options.end);
  1933. }
  1934. };
  1935. /**
  1936. * Add listeners for mouse and touch events to the component
  1937. * @param {Component} component
  1938. * @param {String} event Available events: 'move', 'zoom'
  1939. * @param {String} direction Available directions: 'horizontal', 'vertical'
  1940. */
  1941. Range.prototype.subscribe = function (component, event, direction) {
  1942. var me = this;
  1943. var listener;
  1944. if (direction != 'horizontal' && direction != 'vertical') {
  1945. throw new TypeError('Unknown direction "' + direction + '". ' +
  1946. 'Choose "horizontal" or "vertical".');
  1947. }
  1948. //noinspection FallthroughInSwitchStatementJS
  1949. if (event == 'move') {
  1950. listener = {
  1951. component: component,
  1952. event: event,
  1953. direction: direction,
  1954. callback: function (event) {
  1955. me._onMouseDown(event, listener);
  1956. },
  1957. params: {}
  1958. };
  1959. component.on('mousedown', listener.callback);
  1960. me.listeners.push(listener);
  1961. }
  1962. else if (event == 'zoom') {
  1963. listener = {
  1964. component: component,
  1965. event: event,
  1966. direction: direction,
  1967. callback: function (event) {
  1968. me._onMouseWheel(event, listener);
  1969. },
  1970. params: {}
  1971. };
  1972. component.on('mousewheel', listener.callback);
  1973. me.listeners.push(listener);
  1974. }
  1975. else {
  1976. throw new TypeError('Unknown event "' + event + '". ' +
  1977. 'Choose "move" or "zoom".');
  1978. }
  1979. };
  1980. /**
  1981. * Event handler
  1982. * @param {String} event name of the event, for example 'click', 'mousemove'
  1983. * @param {function} callback callback handler, invoked with the raw HTML Event
  1984. * as parameter.
  1985. */
  1986. Range.prototype.on = function (event, callback) {
  1987. events.addListener(this, event, callback);
  1988. };
  1989. /**
  1990. * Trigger an event
  1991. * @param {String} event name of the event, available events: 'rangechange',
  1992. * 'rangechanged'
  1993. * @private
  1994. */
  1995. Range.prototype._trigger = function (event) {
  1996. events.trigger(this, event, {
  1997. start: this.start,
  1998. end: this.end
  1999. });
  2000. };
  2001. /**
  2002. * Set a new start and end range
  2003. * @param {Number} start
  2004. * @param {Number} end
  2005. */
  2006. Range.prototype.setRange = function(start, end) {
  2007. var changed = this._applyRange(start, end);
  2008. if (changed) {
  2009. this._trigger('rangechange');
  2010. this._trigger('rangechanged');
  2011. }
  2012. };
  2013. /**
  2014. * Set a new start and end range. This method is the same as setRange, but
  2015. * does not trigger a range change and range changed event, and it returns
  2016. * true when the range is changed
  2017. * @param {Number} start
  2018. * @param {Number} end
  2019. * @return {Boolean} changed
  2020. * @private
  2021. */
  2022. Range.prototype._applyRange = function(start, end) {
  2023. var newStart = (start != null) ? util.cast(start, 'Number') : this.start;
  2024. var newEnd = (end != null) ? util.cast(end, 'Number') : this.end;
  2025. var diff;
  2026. // check for valid number
  2027. if (isNaN(newStart)) {
  2028. throw new Error('Invalid start "' + start + '"');
  2029. }
  2030. if (isNaN(newEnd)) {
  2031. throw new Error('Invalid end "' + end + '"');
  2032. }
  2033. // prevent start < end
  2034. if (newEnd < newStart) {
  2035. newEnd = newStart;
  2036. }
  2037. // prevent start < min
  2038. if (this.options.min != null) {
  2039. var min = this.options.min.valueOf();
  2040. if (newStart < min) {
  2041. diff = (min - newStart);
  2042. newStart += diff;
  2043. newEnd += diff;
  2044. }
  2045. }
  2046. // prevent end > max
  2047. if (this.options.max != null) {
  2048. var max = this.options.max.valueOf();
  2049. if (newEnd > max) {
  2050. diff = (newEnd - max);
  2051. newStart -= diff;
  2052. newEnd -= diff;
  2053. }
  2054. }
  2055. // prevent (end-start) > zoomMin
  2056. if (this.options.zoomMin != null) {
  2057. var zoomMin = this.options.zoomMin.valueOf();
  2058. if (zoomMin < 0) {
  2059. zoomMin = 0;
  2060. }
  2061. if ((newEnd - newStart) < zoomMin) {
  2062. if ((this.end - this.start) > zoomMin) {
  2063. // zoom to the minimum
  2064. diff = (zoomMin - (newEnd - newStart));
  2065. newStart -= diff / 2;
  2066. newEnd += diff / 2;
  2067. }
  2068. else {
  2069. // ingore this action, we are already zoomed to the minimum
  2070. newStart = this.start;
  2071. newEnd = this.end;
  2072. }
  2073. }
  2074. }
  2075. // prevent (end-start) > zoomMin
  2076. if (this.options.zoomMax != null) {
  2077. var zoomMax = this.options.zoomMax.valueOf();
  2078. if (zoomMax < 0) {
  2079. zoomMax = 0;
  2080. }
  2081. if ((newEnd - newStart) > zoomMax) {
  2082. if ((this.end - this.start) < zoomMax) {
  2083. // zoom to the maximum
  2084. diff = ((newEnd - newStart) - zoomMax);
  2085. newStart += diff / 2;
  2086. newEnd -= diff / 2;
  2087. }
  2088. else {
  2089. // ingore this action, we are already zoomed to the maximum
  2090. newStart = this.start;
  2091. newEnd = this.end;
  2092. }
  2093. }
  2094. }
  2095. var changed = (this.start != newStart || this.end != newEnd);
  2096. this.start = newStart;
  2097. this.end = newEnd;
  2098. return changed;
  2099. };
  2100. /**
  2101. * Retrieve the current range.
  2102. * @return {Object} An object with start and end properties
  2103. */
  2104. Range.prototype.getRange = function() {
  2105. return {
  2106. start: this.start,
  2107. end: this.end
  2108. };
  2109. };
  2110. /**
  2111. * Calculate the conversion offset and factor for current range, based on
  2112. * the provided width
  2113. * @param {Number} width
  2114. * @returns {{offset: number, factor: number}} conversion
  2115. */
  2116. Range.prototype.conversion = function (width) {
  2117. var start = this.start;
  2118. var end = this.end;
  2119. return Range.conversion(this.start, this.end, width);
  2120. };
  2121. /**
  2122. * Static method to calculate the conversion offset and factor for a range,
  2123. * based on the provided start, end, and width
  2124. * @param {Number} start
  2125. * @param {Number} end
  2126. * @param {Number} width
  2127. * @returns {{offset: number, factor: number}} conversion
  2128. */
  2129. Range.conversion = function (start, end, width) {
  2130. if (width != 0 && (end - start != 0)) {
  2131. return {
  2132. offset: start,
  2133. factor: width / (end - start)
  2134. }
  2135. }
  2136. else {
  2137. return {
  2138. offset: 0,
  2139. factor: 1
  2140. };
  2141. }
  2142. };
  2143. /**
  2144. * Start moving horizontally or vertically
  2145. * @param {Event} event
  2146. * @param {Object} listener Listener containing the component and params
  2147. * @private
  2148. */
  2149. Range.prototype._onMouseDown = function(event, listener) {
  2150. event = event || window.event;
  2151. var params = listener.params;
  2152. // only react on left mouse button down
  2153. var leftButtonDown = event.which ? (event.which == 1) : (event.button == 1);
  2154. if (!leftButtonDown) {
  2155. return;
  2156. }
  2157. // get mouse position
  2158. params.mouseX = util.getPageX(event);
  2159. params.mouseY = util.getPageY(event);
  2160. params.previousLeft = 0;
  2161. params.previousOffset = 0;
  2162. params.moved = false;
  2163. params.start = this.start;
  2164. params.end = this.end;
  2165. var frame = listener.component.frame;
  2166. if (frame) {
  2167. frame.style.cursor = 'move';
  2168. }
  2169. // add event listeners to handle moving the contents
  2170. // we store the function onmousemove and onmouseup in the timeaxis,
  2171. // so we can remove the eventlisteners lateron in the function onmouseup
  2172. var me = this;
  2173. if (!params.onMouseMove) {
  2174. params.onMouseMove = function (event) {
  2175. me._onMouseMove(event, listener);
  2176. };
  2177. util.addEventListener(document, "mousemove", params.onMouseMove);
  2178. }
  2179. if (!params.onMouseUp) {
  2180. params.onMouseUp = function (event) {
  2181. me._onMouseUp(event, listener);
  2182. };
  2183. util.addEventListener(document, "mouseup", params.onMouseUp);
  2184. }
  2185. util.preventDefault(event);
  2186. };
  2187. /**
  2188. * Perform moving operating.
  2189. * This function activated from within the funcion TimeAxis._onMouseDown().
  2190. * @param {Event} event
  2191. * @param {Object} listener
  2192. * @private
  2193. */
  2194. Range.prototype._onMouseMove = function (event, listener) {
  2195. event = event || window.event;
  2196. var params = listener.params;
  2197. // calculate change in mouse position
  2198. var mouseX = util.getPageX(event);
  2199. var mouseY = util.getPageY(event);
  2200. if (params.mouseX == undefined) {
  2201. params.mouseX = mouseX;
  2202. }
  2203. if (params.mouseY == undefined) {
  2204. params.mouseY = mouseY;
  2205. }
  2206. var diffX = mouseX - params.mouseX;
  2207. var diffY = mouseY - params.mouseY;
  2208. var diff = (listener.direction == 'horizontal') ? diffX : diffY;
  2209. // if mouse movement is big enough, register it as a "moved" event
  2210. if (Math.abs(diff) >= 1) {
  2211. params.moved = true;
  2212. }
  2213. var interval = (params.end - params.start);
  2214. var width = (listener.direction == 'horizontal') ?
  2215. listener.component.width : listener.component.height;
  2216. var diffRange = -diff / width * interval;
  2217. this._applyRange(params.start + diffRange, params.end + diffRange);
  2218. // fire a rangechange event
  2219. this._trigger('rangechange');
  2220. util.preventDefault(event);
  2221. };
  2222. /**
  2223. * Stop moving operating.
  2224. * This function activated from within the function Range._onMouseDown().
  2225. * @param {event} event
  2226. * @param {Object} listener
  2227. * @private
  2228. */
  2229. Range.prototype._onMouseUp = function (event, listener) {
  2230. event = event || window.event;
  2231. var params = listener.params;
  2232. if (listener.component.frame) {
  2233. listener.component.frame.style.cursor = 'auto';
  2234. }
  2235. // remove event listeners here, important for Safari
  2236. if (params.onMouseMove) {
  2237. util.removeEventListener(document, "mousemove", params.onMouseMove);
  2238. params.onMouseMove = null;
  2239. }
  2240. if (params.onMouseUp) {
  2241. util.removeEventListener(document, "mouseup", params.onMouseUp);
  2242. params.onMouseUp = null;
  2243. }
  2244. //util.preventDefault(event);
  2245. if (params.moved) {
  2246. // fire a rangechanged event
  2247. this._trigger('rangechanged');
  2248. }
  2249. };
  2250. /**
  2251. * Event handler for mouse wheel event, used to zoom
  2252. * Code from http://adomas.org/javascript-mouse-wheel/
  2253. * @param {Event} event
  2254. * @param {Object} listener
  2255. * @private
  2256. */
  2257. Range.prototype._onMouseWheel = function(event, listener) {
  2258. event = event || window.event;
  2259. // retrieve delta
  2260. var delta = 0;
  2261. if (event.wheelDelta) { /* IE/Opera. */
  2262. delta = event.wheelDelta / 120;
  2263. } else if (event.detail) { /* Mozilla case. */
  2264. // In Mozilla, sign of delta is different than in IE.
  2265. // Also, delta is multiple of 3.
  2266. delta = -event.detail / 3;
  2267. }
  2268. // If delta is nonzero, handle it.
  2269. // Basically, delta is now positive if wheel was scrolled up,
  2270. // and negative, if wheel was scrolled down.
  2271. if (delta) {
  2272. var me = this;
  2273. var zoom = function () {
  2274. // perform the zoom action. Delta is normally 1 or -1
  2275. var zoomFactor = delta / 5.0;
  2276. var zoomAround = null;
  2277. var frame = listener.component.frame;
  2278. if (frame) {
  2279. var size, conversion;
  2280. if (listener.direction == 'horizontal') {
  2281. size = listener.component.width;
  2282. conversion = me.conversion(size);
  2283. var frameLeft = util.getAbsoluteLeft(frame);
  2284. var mouseX = util.getPageX(event);
  2285. zoomAround = (mouseX - frameLeft) / conversion.factor + conversion.offset;
  2286. }
  2287. else {
  2288. size = listener.component.height;
  2289. conversion = me.conversion(size);
  2290. var frameTop = util.getAbsoluteTop(frame);
  2291. var mouseY = util.getPageY(event);
  2292. zoomAround = ((frameTop + size - mouseY) - frameTop) / conversion.factor + conversion.offset;
  2293. }
  2294. }
  2295. me.zoom(zoomFactor, zoomAround);
  2296. };
  2297. zoom();
  2298. }
  2299. // Prevent default actions caused by mouse wheel.
  2300. // That might be ugly, but we handle scrolls somehow
  2301. // anyway, so don't bother here...
  2302. util.preventDefault(event);
  2303. };
  2304. /**
  2305. * Zoom the range the given zoomfactor in or out. Start and end date will
  2306. * be adjusted, and the timeline will be redrawn. You can optionally give a
  2307. * date around which to zoom.
  2308. * For example, try zoomfactor = 0.1 or -0.1
  2309. * @param {Number} zoomFactor Zooming amount. Positive value will zoom in,
  2310. * negative value will zoom out
  2311. * @param {Number} zoomAround Value around which will be zoomed. Optional
  2312. */
  2313. Range.prototype.zoom = function(zoomFactor, zoomAround) {
  2314. // if zoomAroundDate is not provided, take it half between start Date and end Date
  2315. if (zoomAround == null) {
  2316. zoomAround = (this.start + this.end) / 2;
  2317. }
  2318. // prevent zoom factor larger than 1 or smaller than -1 (larger than 1 will
  2319. // result in a start>=end )
  2320. if (zoomFactor >= 1) {
  2321. zoomFactor = 0.9;
  2322. }
  2323. if (zoomFactor <= -1) {
  2324. zoomFactor = -0.9;
  2325. }
  2326. // adjust a negative factor such that zooming in with 0.1 equals zooming
  2327. // out with a factor -0.1
  2328. if (zoomFactor < 0) {
  2329. zoomFactor = zoomFactor / (1 + zoomFactor);
  2330. }
  2331. // zoom start and end relative to the zoomAround value
  2332. var startDiff = (this.start - zoomAround);
  2333. var endDiff = (this.end - zoomAround);
  2334. // calculate new start and end
  2335. var newStart = this.start - startDiff * zoomFactor;
  2336. var newEnd = this.end - endDiff * zoomFactor;
  2337. this.setRange(newStart, newEnd);
  2338. };
  2339. /**
  2340. * Move the range with a given factor to the left or right. Start and end
  2341. * value will be adjusted. For example, try moveFactor = 0.1 or -0.1
  2342. * @param {Number} moveFactor Moving amount. Positive value will move right,
  2343. * negative value will move left
  2344. */
  2345. Range.prototype.move = function(moveFactor) {
  2346. // zoom start Date and end Date relative to the zoomAroundDate
  2347. var diff = (this.end - this.start);
  2348. // apply new values
  2349. var newStart = this.start + diff * moveFactor;
  2350. var newEnd = this.end + diff * moveFactor;
  2351. // TODO: reckon with min and max range
  2352. this.start = newStart;
  2353. this.end = newEnd;
  2354. };
  2355. /**
  2356. * @constructor Controller
  2357. *
  2358. * A Controller controls the reflows and repaints of all visual components
  2359. */
  2360. function Controller () {
  2361. this.id = util.randomUUID();
  2362. this.components = {};
  2363. this.repaintTimer = undefined;
  2364. this.reflowTimer = undefined;
  2365. }
  2366. /**
  2367. * Add a component to the controller
  2368. * @param {Component | Controller} component
  2369. */
  2370. Controller.prototype.add = function (component) {
  2371. // validate the component
  2372. if (component.id == undefined) {
  2373. throw new Error('Component has no field id');
  2374. }
  2375. if (!(component instanceof Component) && !(component instanceof Controller)) {
  2376. throw new TypeError('Component must be an instance of ' +
  2377. 'prototype Component or Controller');
  2378. }
  2379. // add the component
  2380. component.controller = this;
  2381. this.components[component.id] = component;
  2382. };
  2383. /**
  2384. * Request a reflow. The controller will schedule a reflow
  2385. */
  2386. Controller.prototype.requestReflow = function () {
  2387. if (!this.reflowTimer) {
  2388. var me = this;
  2389. this.reflowTimer = setTimeout(function () {
  2390. me.reflowTimer = undefined;
  2391. me.reflow();
  2392. }, 0);
  2393. }
  2394. };
  2395. /**
  2396. * Request a repaint. The controller will schedule a repaint
  2397. */
  2398. Controller.prototype.requestRepaint = function () {
  2399. if (!this.repaintTimer) {
  2400. var me = this;
  2401. this.repaintTimer = setTimeout(function () {
  2402. me.repaintTimer = undefined;
  2403. me.repaint();
  2404. }, 0);
  2405. }
  2406. };
  2407. /**
  2408. * Repaint all components
  2409. */
  2410. Controller.prototype.repaint = function () {
  2411. var changed = false;
  2412. // cancel any running repaint request
  2413. if (this.repaintTimer) {
  2414. clearTimeout(this.repaintTimer);
  2415. this.repaintTimer = undefined;
  2416. }
  2417. var done = {};
  2418. function repaint(component, id) {
  2419. if (!(id in done)) {
  2420. // first repaint the components on which this component is dependent
  2421. if (component.depends) {
  2422. component.depends.forEach(function (dep) {
  2423. repaint(dep, dep.id);
  2424. });
  2425. }
  2426. if (component.parent) {
  2427. repaint(component.parent, component.parent.id);
  2428. }
  2429. // repaint the component itself and mark as done
  2430. changed = component.repaint() || changed;
  2431. done[id] = true;
  2432. }
  2433. }
  2434. util.forEach(this.components, repaint);
  2435. // immediately reflow when needed
  2436. if (changed) {
  2437. this.reflow();
  2438. }
  2439. // TODO: limit the number of nested reflows/repaints, prevent loop
  2440. };
  2441. /**
  2442. * Reflow all components
  2443. */
  2444. Controller.prototype.reflow = function () {
  2445. var resized = false;
  2446. // cancel any running repaint request
  2447. if (this.reflowTimer) {
  2448. clearTimeout(this.reflowTimer);
  2449. this.reflowTimer = undefined;
  2450. }
  2451. var done = {};
  2452. function reflow(component, id) {
  2453. if (!(id in done)) {
  2454. // first reflow the components on which this component is dependent
  2455. if (component.depends) {
  2456. component.depends.forEach(function (dep) {
  2457. reflow(dep, dep.id);
  2458. });
  2459. }
  2460. if (component.parent) {
  2461. reflow(component.parent, component.parent.id);
  2462. }
  2463. // reflow the component itself and mark as done
  2464. resized = component.reflow() || resized;
  2465. done[id] = true;
  2466. }
  2467. }
  2468. util.forEach(this.components, reflow);
  2469. // immediately repaint when needed
  2470. if (resized) {
  2471. this.repaint();
  2472. }
  2473. // TODO: limit the number of nested reflows/repaints, prevent loop
  2474. };
  2475. /**
  2476. * Prototype for visual components
  2477. */
  2478. function Component () {
  2479. this.id = null;
  2480. this.parent = null;
  2481. this.depends = null;
  2482. this.controller = null;
  2483. this.options = null;
  2484. this.frame = null; // main DOM element
  2485. this.top = 0;
  2486. this.left = 0;
  2487. this.width = 0;
  2488. this.height = 0;
  2489. }
  2490. /**
  2491. * Set parameters for the frame. Parameters will be merged in current parameter
  2492. * set.
  2493. * @param {Object} options Available parameters:
  2494. * {String | function} [className]
  2495. * {String | Number | function} [left]
  2496. * {String | Number | function} [top]
  2497. * {String | Number | function} [width]
  2498. * {String | Number | function} [height]
  2499. */
  2500. Component.prototype.setOptions = function(options) {
  2501. if (options) {
  2502. util.extend(this.options, options);
  2503. }
  2504. if (this.controller) {
  2505. this.requestRepaint();
  2506. this.requestReflow();
  2507. }
  2508. };
  2509. /**
  2510. * Get the container element of the component, which can be used by a child to
  2511. * add its own widgets. Not all components do have a container for childs, in
  2512. * that case null is returned.
  2513. * @returns {HTMLElement | null} container
  2514. */
  2515. Component.prototype.getContainer = function () {
  2516. // should be implemented by the component
  2517. return null;
  2518. };
  2519. /**
  2520. * Get the frame element of the component, the outer HTML DOM element.
  2521. * @returns {HTMLElement | null} frame
  2522. */
  2523. Component.prototype.getFrame = function () {
  2524. return this.frame;
  2525. };
  2526. /**
  2527. * Repaint the component
  2528. * @return {Boolean} changed
  2529. */
  2530. Component.prototype.repaint = function () {
  2531. // should be implemented by the component
  2532. return false;
  2533. };
  2534. /**
  2535. * Reflow the component
  2536. * @return {Boolean} resized
  2537. */
  2538. Component.prototype.reflow = function () {
  2539. // should be implemented by the component
  2540. return false;
  2541. };
  2542. /**
  2543. * Request a repaint. The controller will schedule a repaint
  2544. */
  2545. Component.prototype.requestRepaint = function () {
  2546. if (this.controller) {
  2547. this.controller.requestRepaint();
  2548. }
  2549. else {
  2550. throw new Error('Cannot request a repaint: no controller configured');
  2551. // TODO: just do a repaint when no parent is configured?
  2552. }
  2553. };
  2554. /**
  2555. * Request a reflow. The controller will schedule a reflow
  2556. */
  2557. Component.prototype.requestReflow = function () {
  2558. if (this.controller) {
  2559. this.controller.requestReflow();
  2560. }
  2561. else {
  2562. throw new Error('Cannot request a reflow: no controller configured');
  2563. // TODO: just do a reflow when no parent is configured?
  2564. }
  2565. };
  2566. /**
  2567. * Event handler
  2568. * @param {String} event name of the event, for example 'click', 'mousemove'
  2569. * @param {function} callback callback handler, invoked with the raw HTML Event
  2570. * as parameter.
  2571. */
  2572. Component.prototype.on = function (event, callback) {
  2573. // TODO: rethink the way of event delegation
  2574. if (this.parent) {
  2575. this.parent.on(event, callback);
  2576. }
  2577. else {
  2578. throw new Error('Cannot attach event: no root panel found');
  2579. }
  2580. };
  2581. /**
  2582. * A panel can contain components
  2583. * @param {Component} [parent]
  2584. * @param {Component[]} [depends] Components on which this components depends
  2585. * (except for the parent)
  2586. * @param {Object} [options] Available parameters:
  2587. * {String | Number | function} [left]
  2588. * {String | Number | function} [top]
  2589. * {String | Number | function} [width]
  2590. * {String | Number | function} [height]
  2591. * {String | function} [className]
  2592. * @constructor Panel
  2593. * @extends Component
  2594. */
  2595. function Panel(parent, depends, options) {
  2596. this.id = util.randomUUID();
  2597. this.parent = parent;
  2598. this.depends = depends;
  2599. this.options = {};
  2600. this.setOptions(options);
  2601. }
  2602. Panel.prototype = new Component();
  2603. /**
  2604. * Get the container element of the panel, which can be used by a child to
  2605. * add its own widgets.
  2606. * @returns {HTMLElement} container
  2607. */
  2608. Panel.prototype.getContainer = function () {
  2609. return this.frame;
  2610. };
  2611. /**
  2612. * Repaint the component
  2613. * @return {Boolean} changed
  2614. */
  2615. Panel.prototype.repaint = function () {
  2616. var changed = 0,
  2617. update = util.updateProperty,
  2618. asSize = util.option.asSize,
  2619. options = this.options,
  2620. frame = this.frame;
  2621. if (!frame) {
  2622. frame = document.createElement('div');
  2623. frame.className = 'panel';
  2624. if (options.className) {
  2625. if (typeof options.className == 'function') {
  2626. util.addClassName(frame, String(options.className()));
  2627. }
  2628. else {
  2629. util.addClassName(frame, String(options.className));
  2630. }
  2631. }
  2632. this.frame = frame;
  2633. changed += 1;
  2634. }
  2635. if (!frame.parentNode) {
  2636. if (!this.parent) {
  2637. throw new Error('Cannot repaint panel: no parent attached');
  2638. }
  2639. var parentContainer = this.parent.getContainer();
  2640. if (!parentContainer) {
  2641. throw new Error('Cannot repaint panel: parent has no container element');
  2642. }
  2643. parentContainer.appendChild(frame);
  2644. changed += 1;
  2645. }
  2646. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  2647. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  2648. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  2649. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  2650. return (changed > 0);
  2651. };
  2652. /**
  2653. * Reflow the component
  2654. * @return {Boolean} resized
  2655. */
  2656. Panel.prototype.reflow = function () {
  2657. var changed = 0,
  2658. update = util.updateProperty,
  2659. frame = this.frame;
  2660. if (frame) {
  2661. changed += update(this, 'top', frame.offsetTop);
  2662. changed += update(this, 'left', frame.offsetLeft);
  2663. changed += update(this, 'width', frame.offsetWidth);
  2664. changed += update(this, 'height', frame.offsetHeight);
  2665. }
  2666. else {
  2667. changed += 1;
  2668. }
  2669. return (changed > 0);
  2670. };
  2671. /**
  2672. * A root panel can hold components. The root panel must be initialized with
  2673. * a DOM element as container.
  2674. * @param {HTMLElement} container
  2675. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  2676. * @constructor RootPanel
  2677. * @extends Panel
  2678. */
  2679. function RootPanel(container, options) {
  2680. this.id = util.randomUUID();
  2681. this.container = container;
  2682. this.options = {
  2683. autoResize: true
  2684. };
  2685. this.listeners = {}; // event listeners
  2686. this.setOptions(options);
  2687. }
  2688. RootPanel.prototype = new Panel();
  2689. /**
  2690. * Set options. Will extend the current options.
  2691. * @param {Object} [options] Available parameters:
  2692. * {String | function} [className]
  2693. * {String | Number | function} [left]
  2694. * {String | Number | function} [top]
  2695. * {String | Number | function} [width]
  2696. * {String | Number | function} [height]
  2697. * {String | Number | function} [height]
  2698. * {Boolean | function} [autoResize]
  2699. */
  2700. RootPanel.prototype.setOptions = function (options) {
  2701. util.extend(this.options, options);
  2702. if (this.options.autoResize) {
  2703. this._watch();
  2704. }
  2705. else {
  2706. this._unwatch();
  2707. }
  2708. };
  2709. /**
  2710. * Repaint the component
  2711. * @return {Boolean} changed
  2712. */
  2713. RootPanel.prototype.repaint = function () {
  2714. var changed = 0,
  2715. update = util.updateProperty,
  2716. asSize = util.option.asSize,
  2717. options = this.options,
  2718. frame = this.frame;
  2719. if (!frame) {
  2720. frame = document.createElement('div');
  2721. frame.className = 'graph panel';
  2722. if (options.className) {
  2723. util.addClassName(frame, util.option.asString(options.className));
  2724. }
  2725. this.frame = frame;
  2726. changed += 1;
  2727. }
  2728. if (!frame.parentNode) {
  2729. if (!this.container) {
  2730. throw new Error('Cannot repaint root panel: no container attached');
  2731. }
  2732. this.container.appendChild(frame);
  2733. changed += 1;
  2734. }
  2735. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  2736. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  2737. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  2738. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  2739. this._updateEventEmitters();
  2740. return (changed > 0);
  2741. };
  2742. /**
  2743. * Reflow the component
  2744. * @return {Boolean} resized
  2745. */
  2746. RootPanel.prototype.reflow = function () {
  2747. var changed = 0,
  2748. update = util.updateProperty,
  2749. frame = this.frame;
  2750. if (frame) {
  2751. changed += update(this, 'top', frame.offsetTop);
  2752. changed += update(this, 'left', frame.offsetLeft);
  2753. changed += update(this, 'width', frame.offsetWidth);
  2754. changed += update(this, 'height', frame.offsetHeight);
  2755. }
  2756. else {
  2757. changed += 1;
  2758. }
  2759. return (changed > 0);
  2760. };
  2761. /**
  2762. * Watch for changes in the size of the frame. On resize, the Panel will
  2763. * automatically redraw itself.
  2764. * @private
  2765. */
  2766. RootPanel.prototype._watch = function () {
  2767. var me = this;
  2768. this._unwatch();
  2769. var checkSize = function () {
  2770. if (!me.options.autoResize) {
  2771. // stop watching when the option autoResize is changed to false
  2772. me._unwatch();
  2773. return;
  2774. }
  2775. if (me.frame) {
  2776. // check whether the frame is resized
  2777. if ((me.frame.clientWidth != me.width) ||
  2778. (me.frame.clientHeight != me.height)) {
  2779. me.requestReflow();
  2780. }
  2781. }
  2782. };
  2783. // TODO: automatically cleanup the event listener when the frame is deleted
  2784. util.addEventListener(window, 'resize', checkSize);
  2785. this.watchTimer = setInterval(checkSize, 1000);
  2786. };
  2787. /**
  2788. * Stop watching for a resize of the frame.
  2789. * @private
  2790. */
  2791. RootPanel.prototype._unwatch = function () {
  2792. if (this.watchTimer) {
  2793. clearInterval(this.watchTimer);
  2794. this.watchTimer = undefined;
  2795. }
  2796. // TODO: remove event listener on window.resize
  2797. };
  2798. /**
  2799. * Event handler
  2800. * @param {String} event name of the event, for example 'click', 'mousemove'
  2801. * @param {function} callback callback handler, invoked with the raw HTML Event
  2802. * as parameter.
  2803. */
  2804. RootPanel.prototype.on = function (event, callback) {
  2805. // register the listener at this component
  2806. var arr = this.listeners[event];
  2807. if (!arr) {
  2808. arr = [];
  2809. this.listeners[event] = arr;
  2810. }
  2811. arr.push(callback);
  2812. this._updateEventEmitters();
  2813. };
  2814. /**
  2815. * Update the event listeners for all event emitters
  2816. * @private
  2817. */
  2818. RootPanel.prototype._updateEventEmitters = function () {
  2819. if (this.listeners) {
  2820. var me = this;
  2821. util.forEach(this.listeners, function (listeners, event) {
  2822. if (!me.emitters) {
  2823. me.emitters = {};
  2824. }
  2825. if (!(event in me.emitters)) {
  2826. // create event
  2827. var frame = me.frame;
  2828. if (frame) {
  2829. //console.log('Created a listener for event ' + event + ' on component ' + me.id); // TODO: cleanup logging
  2830. var callback = function(event) {
  2831. listeners.forEach(function (listener) {
  2832. // TODO: filter on event target!
  2833. listener(event);
  2834. });
  2835. };
  2836. me.emitters[event] = callback;
  2837. util.addEventListener(frame, event, callback);
  2838. }
  2839. }
  2840. });
  2841. // TODO: be able to delete event listeners
  2842. // TODO: be able to move event listeners to a parent when available
  2843. }
  2844. };
  2845. /**
  2846. * A horizontal time axis
  2847. * @param {Component} parent
  2848. * @param {Component[]} [depends] Components on which this components depends
  2849. * (except for the parent)
  2850. * @param {Object} [options] See TimeAxis.setOptions for the available
  2851. * options.
  2852. * @constructor TimeAxis
  2853. * @extends Component
  2854. */
  2855. function TimeAxis (parent, depends, options) {
  2856. this.id = util.randomUUID();
  2857. this.parent = parent;
  2858. this.depends = depends;
  2859. this.dom = {
  2860. majorLines: [],
  2861. majorTexts: [],
  2862. minorLines: [],
  2863. minorTexts: [],
  2864. redundant: {
  2865. majorLines: [],
  2866. majorTexts: [],
  2867. minorLines: [],
  2868. minorTexts: []
  2869. }
  2870. };
  2871. this.props = {
  2872. range: {
  2873. start: 0,
  2874. end: 0,
  2875. minimumStep: 0
  2876. },
  2877. lineTop: 0
  2878. };
  2879. this.options = {
  2880. orientation: 'bottom', // supported: 'top', 'bottom'
  2881. // TODO: implement timeaxis orientations 'left' and 'right'
  2882. showMinorLabels: true,
  2883. showMajorLabels: true
  2884. };
  2885. this.conversion = null;
  2886. this.range = null;
  2887. this.setOptions(options);
  2888. }
  2889. TimeAxis.prototype = new Component();
  2890. // TODO: comment options
  2891. TimeAxis.prototype.setOptions = function (options) {
  2892. util.extend(this.options, options);
  2893. };
  2894. /**
  2895. * Set a range (start and end)
  2896. * @param {Range | Object} range A Range or an object containing start and end.
  2897. */
  2898. TimeAxis.prototype.setRange = function (range) {
  2899. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  2900. throw new TypeError('Range must be an instance of Range, ' +
  2901. 'or an object containing start and end.');
  2902. }
  2903. this.range = range;
  2904. };
  2905. /**
  2906. * Convert a position on screen (pixels) to a datetime
  2907. * @param {int} x Position on the screen in pixels
  2908. * @return {Date} time The datetime the corresponds with given position x
  2909. */
  2910. TimeAxis.prototype.toTime = function(x) {
  2911. var conversion = this.conversion;
  2912. return new Date(x / conversion.factor + conversion.offset);
  2913. };
  2914. /**
  2915. * Convert a datetime (Date object) into a position on the screen
  2916. * @param {Date} time A date
  2917. * @return {int} x The position on the screen in pixels which corresponds
  2918. * with the given date.
  2919. * @private
  2920. */
  2921. TimeAxis.prototype.toScreen = function(time) {
  2922. var conversion = this.conversion;
  2923. return (time.valueOf() - conversion.offset) * conversion.factor;
  2924. };
  2925. /**
  2926. * Repaint the component
  2927. * @return {Boolean} changed
  2928. */
  2929. TimeAxis.prototype.repaint = function () {
  2930. var changed = 0,
  2931. update = util.updateProperty,
  2932. asSize = util.option.asSize,
  2933. options = this.options,
  2934. props = this.props,
  2935. step = this.step;
  2936. var frame = this.frame;
  2937. if (!frame) {
  2938. frame = document.createElement('div');
  2939. this.frame = frame;
  2940. changed += 1;
  2941. }
  2942. frame.className = 'axis ' + options.orientation;
  2943. // TODO: custom className?
  2944. if (!frame.parentNode) {
  2945. if (!this.parent) {
  2946. throw new Error('Cannot repaint time axis: no parent attached');
  2947. }
  2948. var parentContainer = this.parent.getContainer();
  2949. if (!parentContainer) {
  2950. throw new Error('Cannot repaint time axis: parent has no container element');
  2951. }
  2952. parentContainer.appendChild(frame);
  2953. changed += 1;
  2954. }
  2955. var parent = frame.parentNode;
  2956. if (parent) {
  2957. var beforeChild = frame.nextSibling;
  2958. parent.removeChild(frame); // take frame offline while updating (is almost twice as fast)
  2959. var orientation = options.orientation;
  2960. var defaultTop = (orientation == 'bottom' && this.props.parentHeight && this.height) ?
  2961. (this.props.parentHeight - this.height) + 'px' :
  2962. '0px';
  2963. changed += update(frame.style, 'top', asSize(options.top, defaultTop));
  2964. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  2965. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  2966. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  2967. // get characters width and height
  2968. this._repaintMeasureChars();
  2969. if (this.step) {
  2970. this._repaintStart();
  2971. step.first();
  2972. var xFirstMajorLabel = undefined;
  2973. var max = 0;
  2974. while (step.hasNext() && max < 1000) {
  2975. max++;
  2976. var cur = step.getCurrent(),
  2977. x = this.toScreen(cur),
  2978. isMajor = step.isMajor();
  2979. // TODO: lines must have a width, such that we can create css backgrounds
  2980. if (options.showMinorLabels) {
  2981. this._repaintMinorText(x, step.getLabelMinor());
  2982. }
  2983. if (isMajor && options.showMajorLabels) {
  2984. if (x > 0) {
  2985. if (xFirstMajorLabel == undefined) {
  2986. xFirstMajorLabel = x;
  2987. }
  2988. this._repaintMajorText(x, step.getLabelMajor());
  2989. }
  2990. this._repaintMajorLine(x);
  2991. }
  2992. else {
  2993. this._repaintMinorLine(x);
  2994. }
  2995. step.next();
  2996. }
  2997. // create a major label on the left when needed
  2998. if (options.showMajorLabels) {
  2999. var leftTime = this.toTime(0),
  3000. leftText = step.getLabelMajor(leftTime),
  3001. widthText = leftText.length * (props.majorCharWidth || 10) + 10; // upper bound estimation
  3002. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3003. this._repaintMajorText(0, leftText);
  3004. }
  3005. }
  3006. this._repaintEnd();
  3007. }
  3008. this._repaintLine();
  3009. // put frame online again
  3010. if (beforeChild) {
  3011. parent.insertBefore(frame, beforeChild);
  3012. }
  3013. else {
  3014. parent.appendChild(frame)
  3015. }
  3016. }
  3017. return (changed > 0);
  3018. };
  3019. /**
  3020. * Start a repaint. Move all DOM elements to a redundant list, where they
  3021. * can be picked for re-use, or can be cleaned up in the end
  3022. * @private
  3023. */
  3024. TimeAxis.prototype._repaintStart = function () {
  3025. var dom = this.dom,
  3026. redundant = dom.redundant;
  3027. redundant.majorLines = dom.majorLines;
  3028. redundant.majorTexts = dom.majorTexts;
  3029. redundant.minorLines = dom.minorLines;
  3030. redundant.minorTexts = dom.minorTexts;
  3031. dom.majorLines = [];
  3032. dom.majorTexts = [];
  3033. dom.minorLines = [];
  3034. dom.minorTexts = [];
  3035. };
  3036. /**
  3037. * End a repaint. Cleanup leftover DOM elements in the redundant list
  3038. * @private
  3039. */
  3040. TimeAxis.prototype._repaintEnd = function () {
  3041. util.forEach(this.dom.redundant, function (arr) {
  3042. while (arr.length) {
  3043. var elem = arr.pop();
  3044. if (elem && elem.parentNode) {
  3045. elem.parentNode.removeChild(elem);
  3046. }
  3047. }
  3048. });
  3049. };
  3050. /**
  3051. * Create a minor label for the axis at position x
  3052. * @param {Number} x
  3053. * @param {String} text
  3054. * @private
  3055. */
  3056. TimeAxis.prototype._repaintMinorText = function (x, text) {
  3057. // reuse redundant label
  3058. var label = this.dom.redundant.minorTexts.shift();
  3059. if (!label) {
  3060. // create new label
  3061. var content = document.createTextNode('');
  3062. label = document.createElement('div');
  3063. label.appendChild(content);
  3064. label.className = 'text minor';
  3065. this.frame.appendChild(label);
  3066. }
  3067. this.dom.minorTexts.push(label);
  3068. label.childNodes[0].nodeValue = text;
  3069. label.style.left = x + 'px';
  3070. label.style.top = this.props.minorLabelTop + 'px';
  3071. //label.title = title; // TODO: this is a heavy operation
  3072. };
  3073. /**
  3074. * Create a Major label for the axis at position x
  3075. * @param {Number} x
  3076. * @param {String} text
  3077. * @private
  3078. */
  3079. TimeAxis.prototype._repaintMajorText = function (x, text) {
  3080. // reuse redundant label
  3081. var label = this.dom.redundant.majorTexts.shift();
  3082. if (!label) {
  3083. // create label
  3084. var content = document.createTextNode(text);
  3085. label = document.createElement('div');
  3086. label.className = 'text major';
  3087. label.appendChild(content);
  3088. this.frame.appendChild(label);
  3089. }
  3090. this.dom.majorTexts.push(label);
  3091. label.childNodes[0].nodeValue = text;
  3092. label.style.top = this.props.majorLabelTop + 'px';
  3093. label.style.left = x + 'px';
  3094. //label.title = title; // TODO: this is a heavy operation
  3095. };
  3096. /**
  3097. * Create a minor line for the axis at position x
  3098. * @param {Number} x
  3099. * @private
  3100. */
  3101. TimeAxis.prototype._repaintMinorLine = function (x) {
  3102. // reuse redundant line
  3103. var line = this.dom.redundant.minorLines.shift();
  3104. if (!line) {
  3105. // create vertical line
  3106. line = document.createElement('div');
  3107. line.className = 'grid vertical minor';
  3108. this.frame.appendChild(line);
  3109. }
  3110. this.dom.minorLines.push(line);
  3111. var props = this.props;
  3112. line.style.top = props.minorLineTop + 'px';
  3113. line.style.height = props.minorLineHeight + 'px';
  3114. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  3115. };
  3116. /**
  3117. * Create a Major line for the axis at position x
  3118. * @param {Number} x
  3119. * @private
  3120. */
  3121. TimeAxis.prototype._repaintMajorLine = function (x) {
  3122. // reuse redundant line
  3123. var line = this.dom.redundant.majorLines.shift();
  3124. if (!line) {
  3125. // create vertical line
  3126. line = document.createElement('DIV');
  3127. line.className = 'grid vertical major';
  3128. this.frame.appendChild(line);
  3129. }
  3130. this.dom.majorLines.push(line);
  3131. var props = this.props;
  3132. line.style.top = props.majorLineTop + 'px';
  3133. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  3134. line.style.height = props.majorLineHeight + 'px';
  3135. };
  3136. /**
  3137. * Repaint the horizontal line for the axis
  3138. * @private
  3139. */
  3140. TimeAxis.prototype._repaintLine = function() {
  3141. var line = this.dom.line,
  3142. frame = this.frame,
  3143. options = this.options;
  3144. // line before all axis elements
  3145. if (options.showMinorLabels || options.showMajorLabels) {
  3146. if (line) {
  3147. // put this line at the end of all childs
  3148. frame.removeChild(line);
  3149. frame.appendChild(line);
  3150. }
  3151. else {
  3152. // create the axis line
  3153. line = document.createElement('div');
  3154. line.className = 'grid horizontal major';
  3155. frame.appendChild(line);
  3156. this.dom.line = line;
  3157. }
  3158. line.style.top = this.props.lineTop + 'px';
  3159. }
  3160. else {
  3161. if (line && axis.parentElement) {
  3162. frame.removeChild(axis.line);
  3163. delete this.dom.line;
  3164. }
  3165. }
  3166. };
  3167. /**
  3168. * Create characters used to determine the size of text on the axis
  3169. * @private
  3170. */
  3171. TimeAxis.prototype._repaintMeasureChars = function () {
  3172. // calculate the width and height of a single character
  3173. // this is used to calculate the step size, and also the positioning of the
  3174. // axis
  3175. var dom = this.dom,
  3176. text;
  3177. if (!dom.characterMinor) {
  3178. text = document.createTextNode('0');
  3179. var measureCharMinor = document.createElement('DIV');
  3180. measureCharMinor.className = 'text minor measure';
  3181. measureCharMinor.appendChild(text);
  3182. this.frame.appendChild(measureCharMinor);
  3183. dom.measureCharMinor = measureCharMinor;
  3184. }
  3185. if (!dom.characterMajor) {
  3186. text = document.createTextNode('0');
  3187. var measureCharMajor = document.createElement('DIV');
  3188. measureCharMajor.className = 'text major measure';
  3189. measureCharMajor.appendChild(text);
  3190. this.frame.appendChild(measureCharMajor);
  3191. dom.measureCharMajor = measureCharMajor;
  3192. }
  3193. };
  3194. /**
  3195. * Reflow the component
  3196. * @return {Boolean} resized
  3197. */
  3198. TimeAxis.prototype.reflow = function () {
  3199. var changed = 0,
  3200. update = util.updateProperty,
  3201. frame = this.frame,
  3202. range = this.range;
  3203. if (!range) {
  3204. throw new Error('Cannot repaint time axis: no range configured');
  3205. }
  3206. if (frame) {
  3207. changed += update(this, 'top', frame.offsetTop);
  3208. changed += update(this, 'left', frame.offsetLeft);
  3209. // calculate size of a character
  3210. var props = this.props,
  3211. showMinorLabels = this.options.showMinorLabels,
  3212. showMajorLabels = this.options.showMajorLabels,
  3213. measureCharMinor = this.dom.measureCharMinor,
  3214. measureCharMajor = this.dom.measureCharMajor;
  3215. if (measureCharMinor) {
  3216. props.minorCharHeight = measureCharMinor.clientHeight;
  3217. props.minorCharWidth = measureCharMinor.clientWidth;
  3218. }
  3219. if (measureCharMajor) {
  3220. props.majorCharHeight = measureCharMajor.clientHeight;
  3221. props.majorCharWidth = measureCharMajor.clientWidth;
  3222. }
  3223. var parentHeight = frame.parentNode ? frame.parentNode.offsetHeight : 0;
  3224. if (parentHeight != props.parentHeight) {
  3225. props.parentHeight = parentHeight;
  3226. changed += 1;
  3227. }
  3228. switch (this.options.orientation) {
  3229. case 'bottom':
  3230. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  3231. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  3232. props.minorLabelTop = 0;
  3233. props.majorLabelTop = props.minorLabelTop + props.minorLabelHeight;
  3234. props.minorLineTop = -this.top;
  3235. props.minorLineHeight = Math.max(this.top + props.majorLabelHeight, 0);
  3236. props.minorLineWidth = 1; // TODO: really calculate width
  3237. props.majorLineTop = -this.top;
  3238. props.majorLineHeight = Math.max(this.top + props.minorLabelHeight + props.majorLabelHeight, 0);
  3239. props.majorLineWidth = 1; // TODO: really calculate width
  3240. props.lineTop = 0;
  3241. break;
  3242. case 'top':
  3243. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  3244. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  3245. props.majorLabelTop = 0;
  3246. props.minorLabelTop = props.majorLabelTop + props.majorLabelHeight;
  3247. props.minorLineTop = props.minorLabelTop;
  3248. props.minorLineHeight = Math.max(parentHeight - props.majorLabelHeight - this.top);
  3249. props.minorLineWidth = 1; // TODO: really calculate width
  3250. props.majorLineTop = 0;
  3251. props.majorLineHeight = Math.max(parentHeight - this.top);
  3252. props.majorLineWidth = 1; // TODO: really calculate width
  3253. props.lineTop = props.majorLabelHeight + props.minorLabelHeight;
  3254. break;
  3255. default:
  3256. throw new Error('Unkown orientation "' + this.options.orientation + '"');
  3257. }
  3258. var height = props.minorLabelHeight + props.majorLabelHeight;
  3259. changed += update(this, 'width', frame.offsetWidth);
  3260. changed += update(this, 'height', height);
  3261. // calculate range and step
  3262. this._updateConversion();
  3263. var start = util.cast(range.start, 'Date'),
  3264. end = util.cast(range.end, 'Date'),
  3265. minimumStep = this.toTime((props.minorCharWidth || 10) * 5) - this.toTime(0);
  3266. this.step = new TimeStep(start, end, minimumStep);
  3267. changed += update(props.range, 'start', start.valueOf());
  3268. changed += update(props.range, 'end', end.valueOf());
  3269. changed += update(props.range, 'minimumStep', minimumStep.valueOf());
  3270. }
  3271. return (changed > 0);
  3272. };
  3273. /**
  3274. * Calculate the factor and offset to convert a position on screen to the
  3275. * corresponding date and vice versa.
  3276. * After the method _updateConversion is executed once, the methods toTime
  3277. * and toScreen can be used.
  3278. * @private
  3279. */
  3280. TimeAxis.prototype._updateConversion = function() {
  3281. var range = this.range;
  3282. if (!range) {
  3283. throw new Error('No range configured');
  3284. }
  3285. if (range.conversion) {
  3286. this.conversion = range.conversion(this.width);
  3287. }
  3288. else {
  3289. this.conversion = Range.conversion(range.start, range.end, this.width);
  3290. }
  3291. };
  3292. /**
  3293. * An ItemSet holds a set of items and ranges which can be displayed in a
  3294. * range. The width is determined by the parent of the ItemSet, and the height
  3295. * is determined by the size of the items.
  3296. * @param {Component} parent
  3297. * @param {Component[]} [depends] Components on which this components depends
  3298. * (except for the parent)
  3299. * @param {Object} [options] See ItemSet.setOptions for the available
  3300. * options.
  3301. * @constructor ItemSet
  3302. * @extends Panel
  3303. */
  3304. function ItemSet(parent, depends, options) {
  3305. this.id = util.randomUUID();
  3306. this.parent = parent;
  3307. this.depends = depends;
  3308. // one options object is shared by this itemset and all its items
  3309. this.options = {
  3310. style: 'box',
  3311. align: 'center',
  3312. orientation: 'bottom',
  3313. margin: {
  3314. axis: 20,
  3315. item: 10
  3316. },
  3317. padding: 5
  3318. };
  3319. this.dom = {};
  3320. var me = this;
  3321. this.data = null; // DataSet
  3322. this.range = null; // Range or Object {start: number, end: number}
  3323. this.listeners = {
  3324. 'add': function (event, params) {
  3325. me._onAdd(params.items);
  3326. },
  3327. 'update': function (event, params) {
  3328. me._onUpdate(params.items);
  3329. },
  3330. 'remove': function (event, params) {
  3331. me._onRemove(params.items);
  3332. }
  3333. };
  3334. this.items = {};
  3335. this.queue = {}; // queue with items to be added/updated/removed
  3336. this.stack = new Stack(this);
  3337. this.conversion = null;
  3338. this.setOptions(options);
  3339. }
  3340. ItemSet.prototype = new Panel();
  3341. // available item types will be registered here
  3342. ItemSet.types = {
  3343. box: ItemBox,
  3344. range: ItemRange,
  3345. point: ItemPoint
  3346. };
  3347. /**
  3348. * Set options for the ItemSet. Existing options will be extended/overwritten.
  3349. * @param {Object} [options] The following options are available:
  3350. * {String | function} [className]
  3351. * class name for the itemset
  3352. * {String} [style]
  3353. * Default style for the items. Choose from 'box'
  3354. * (default), 'point', or 'range'. The default
  3355. * Style can be overwritten by individual items.
  3356. * {String} align
  3357. * Alignment for the items, only applicable for
  3358. * ItemBox. Choose 'center' (default), 'left', or
  3359. * 'right'.
  3360. * {String} orientation
  3361. * Orientation of the item set. Choose 'top' or
  3362. * 'bottom' (default).
  3363. * {Number} margin.axis
  3364. * Margin between the axis and the items in pixels.
  3365. * Default is 20.
  3366. * {Number} margin.item
  3367. * Margin between items in pixels. Default is 10.
  3368. * {Number} padding
  3369. * Padding of the contents of an item in pixels.
  3370. * Must correspond with the items css. Default is 5.
  3371. */
  3372. ItemSet.prototype.setOptions = function (options) {
  3373. util.extend(this.options, options);
  3374. // TODO: ItemSet should also attach event listeners for rangechange and rangechanged, like timeaxis
  3375. this.stack.setOptions(this.options);
  3376. };
  3377. /**
  3378. * Set range (start and end).
  3379. * @param {Range | Object} range A Range or an object containing start and end.
  3380. */
  3381. ItemSet.prototype.setRange = function (range) {
  3382. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  3383. throw new TypeError('Range must be an instance of Range, ' +
  3384. 'or an object containing start and end.');
  3385. }
  3386. this.range = range;
  3387. };
  3388. /**
  3389. * Repaint the component
  3390. * @return {Boolean} changed
  3391. */
  3392. ItemSet.prototype.repaint = function () {
  3393. var changed = 0,
  3394. update = util.updateProperty,
  3395. asSize = util.option.asSize,
  3396. options = this.options,
  3397. frame = this.frame;
  3398. if (!frame) {
  3399. frame = document.createElement('div');
  3400. frame.className = 'itemset';
  3401. if (options.className) {
  3402. util.addClassName(frame, util.option.asString(options.className));
  3403. }
  3404. // create background panel
  3405. var background = document.createElement('div');
  3406. background.className = 'background';
  3407. frame.appendChild(background);
  3408. this.dom.background = background;
  3409. // create foreground panel
  3410. var foreground = document.createElement('div');
  3411. foreground.className = 'foreground';
  3412. frame.appendChild(foreground);
  3413. this.dom.foreground = foreground;
  3414. // create axis panel
  3415. var axis = document.createElement('div');
  3416. axis.className = 'itemset-axis';
  3417. //frame.appendChild(axis);
  3418. this.dom.axis = axis;
  3419. this.frame = frame;
  3420. changed += 1;
  3421. }
  3422. if (!this.parent) {
  3423. throw new Error('Cannot repaint itemset: no parent attached');
  3424. }
  3425. var parentContainer = this.parent.getContainer();
  3426. if (!parentContainer) {
  3427. throw new Error('Cannot repaint itemset: parent has no container element');
  3428. }
  3429. if (!frame.parentNode) {
  3430. parentContainer.appendChild(frame);
  3431. changed += 1;
  3432. }
  3433. if (!this.dom.axis.parentNode) {
  3434. parentContainer.appendChild(this.dom.axis);
  3435. changed += 1;
  3436. }
  3437. // reposition frame
  3438. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  3439. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3440. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3441. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3442. // reposition axis
  3443. changed += update(this.dom.axis.style, 'top', asSize(options.top, '0px'));
  3444. this._updateConversion();
  3445. var me = this,
  3446. queue = this.queue,
  3447. data = this.data,
  3448. items = this.items,
  3449. dataOptions = {
  3450. fields: ['id', 'start', 'end', 'content', 'type']
  3451. };
  3452. // TODO: copy options from the itemset itself?
  3453. // TODO: make orientation dynamically changable for the items
  3454. // show/hide added/changed/removed items
  3455. Object.keys(queue).forEach(function (id) {
  3456. var entry = queue[id];
  3457. var item = entry.item;
  3458. //noinspection FallthroughInSwitchStatementJS
  3459. switch (entry.action) {
  3460. case 'add':
  3461. case 'update':
  3462. var itemData = data.get(id, dataOptions);
  3463. var type = itemData.type ||
  3464. (itemData.start && itemData.end && 'range') ||
  3465. 'box';
  3466. var constructor = ItemSet.types[type];
  3467. // TODO: how to handle items with invalid data? hide them and give a warning? or throw an error?
  3468. if (item) {
  3469. // update item
  3470. if (!constructor || !(item instanceof constructor)) {
  3471. // item type has changed, delete the item
  3472. item.visible = false;
  3473. changed += item.repaint();
  3474. item = null;
  3475. }
  3476. else {
  3477. item.data = itemData; // TODO: create a method item.setData ?
  3478. changed += item.repaint();
  3479. }
  3480. }
  3481. if (!item) {
  3482. // create item
  3483. if (constructor) {
  3484. item = new constructor(me, itemData, options);
  3485. changed += item.repaint();
  3486. }
  3487. else {
  3488. throw new TypeError('Unknown item type "' + type + '"');
  3489. }
  3490. }
  3491. // update lists
  3492. items[id] = item;
  3493. delete queue[id];
  3494. break;
  3495. case 'remove':
  3496. if (item) {
  3497. // TODO: remove dom of the item
  3498. item.visible = false;
  3499. changed += item.repaint();
  3500. }
  3501. // update lists
  3502. delete items[id];
  3503. delete queue[id];
  3504. break;
  3505. default:
  3506. console.log('Error: unknown action "' + entry.action + '"');
  3507. }
  3508. });
  3509. // reposition all items
  3510. util.forEach(this.items, function (item) {
  3511. item.reposition();
  3512. });
  3513. return (changed > 0);
  3514. };
  3515. /**
  3516. * Get the foreground container element
  3517. * @return {HTMLElement} foreground
  3518. */
  3519. ItemSet.prototype.getForeground = function () {
  3520. return this.dom.foreground;
  3521. };
  3522. /**
  3523. * Get the background container element
  3524. * @return {HTMLElement} background
  3525. */
  3526. ItemSet.prototype.getBackground = function () {
  3527. return this.dom.background;
  3528. };
  3529. /**
  3530. * Reflow the component
  3531. * @return {Boolean} resized
  3532. */
  3533. ItemSet.prototype.reflow = function () {
  3534. var changed = 0,
  3535. options = this.options,
  3536. update = util.updateProperty,
  3537. asNumber = util.option.asNumber,
  3538. frame = this.frame;
  3539. if (frame) {
  3540. this._updateConversion();
  3541. util.forEach(this.items, function (item) {
  3542. changed += item.reflow();
  3543. });
  3544. // TODO: stack.update should be triggered via an event, in stack itself
  3545. // TODO: only update the stack when there are changed items
  3546. this.stack.update();
  3547. var maxHeight = asNumber(options.maxHeight);
  3548. var height;
  3549. if (options.height != null) {
  3550. height = frame.offsetHeight;
  3551. if (maxHeight != null) {
  3552. height = Math.min(height, maxHeight);
  3553. }
  3554. changed += update(this, 'height', height);
  3555. }
  3556. else {
  3557. // height is not specified, determine the height from the height and positioned items
  3558. var frameHeight = this.height;
  3559. height = 0;
  3560. if (options.orientation == 'top') {
  3561. util.forEach(this.items, function (item) {
  3562. height = Math.max(height, item.top + item.height);
  3563. });
  3564. }
  3565. else {
  3566. // orientation == 'bottom'
  3567. util.forEach(this.items, function (item) {
  3568. height = Math.max(height, frameHeight - item.top);
  3569. });
  3570. }
  3571. height += options.margin.axis;
  3572. if (maxHeight != null) {
  3573. height = Math.min(height, maxHeight);
  3574. }
  3575. changed += update(this, 'height', height);
  3576. }
  3577. // calculate height from items
  3578. changed += update(this, 'top', frame.offsetTop);
  3579. changed += update(this, 'left', frame.offsetLeft);
  3580. changed += update(this, 'width', frame.offsetWidth);
  3581. }
  3582. else {
  3583. changed += 1;
  3584. }
  3585. return (changed > 0);
  3586. };
  3587. /**
  3588. * Set data
  3589. * @param {DataSet | Array | DataTable} data
  3590. */
  3591. ItemSet.prototype.setData = function(data) {
  3592. // unsubscribe from current dataset
  3593. var current = this.data;
  3594. if (current) {
  3595. util.forEach(this.listeners, function (callback, event) {
  3596. current.unsubscribe(event, callback);
  3597. });
  3598. }
  3599. if (data instanceof DataSet) {
  3600. this.data = data;
  3601. }
  3602. else {
  3603. this.data = new DataSet({
  3604. fieldTypes: {
  3605. start: 'Date',
  3606. end: 'Date'
  3607. }
  3608. });
  3609. this.data.add(data);
  3610. }
  3611. var id = this.id;
  3612. var me = this;
  3613. util.forEach(this.listeners, function (callback, event) {
  3614. me.data.subscribe(event, callback, id);
  3615. });
  3616. var dataItems = this.data.get({filter: ['id']});
  3617. var ids = [];
  3618. util.forEach(dataItems, function (dataItem, index) {
  3619. ids[index] = dataItem.id;
  3620. });
  3621. this._onAdd(ids);
  3622. };
  3623. /**
  3624. * Get the data range of the item set.
  3625. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  3626. * When no minimum is found, min==null
  3627. * When no maximum is found, max==null
  3628. */
  3629. ItemSet.prototype.getDataRange = function () {
  3630. // calculate min from start filed
  3631. var data = this.data;
  3632. var min = data.min('start');
  3633. min = min ? min.start.valueOf() : null;
  3634. // calculate max of both start and end fields
  3635. var maxStart = data.max('start');
  3636. var maxEnd = data.max('end');
  3637. maxStart = maxStart ? maxStart.start.valueOf() : null;
  3638. maxEnd = maxEnd ? maxEnd.end.valueOf() : null;
  3639. var max = Math.max(maxStart, maxEnd);
  3640. return {
  3641. min: new Date(min),
  3642. max: new Date(max)
  3643. };
  3644. };
  3645. /**
  3646. * Handle updated items
  3647. * @param {Number[]} ids
  3648. * @private
  3649. */
  3650. ItemSet.prototype._onUpdate = function(ids) {
  3651. this._toQueue(ids, 'update');
  3652. };
  3653. /**
  3654. * Handle changed items
  3655. * @param {Number[]} ids
  3656. * @private
  3657. */
  3658. ItemSet.prototype._onAdd = function(ids) {
  3659. this._toQueue(ids, 'add');
  3660. };
  3661. /**
  3662. * Handle removed items
  3663. * @param {Number[]} ids
  3664. * @private
  3665. */
  3666. ItemSet.prototype._onRemove = function(ids) {
  3667. this._toQueue(ids, 'remove');
  3668. };
  3669. /**
  3670. * Put items in the queue to be added/updated/remove
  3671. * @param {Number[]} ids
  3672. * @param {String} action can be 'add', 'update', 'remove'
  3673. */
  3674. ItemSet.prototype._toQueue = function (ids, action) {
  3675. var items = this.items;
  3676. var queue = this.queue;
  3677. ids.forEach(function (id) {
  3678. var entry = queue[id];
  3679. if (entry) {
  3680. // already queued, update the action of the entry
  3681. entry.action = action;
  3682. }
  3683. else {
  3684. // not yet queued, add an entry to the queue
  3685. queue[id] = {
  3686. item: items[id] || null,
  3687. action: action
  3688. };
  3689. }
  3690. });
  3691. if (this.controller) {
  3692. //this.requestReflow();
  3693. this.requestRepaint();
  3694. }
  3695. };
  3696. /**
  3697. * Calculate the factor and offset to convert a position on screen to the
  3698. * corresponding date and vice versa.
  3699. * After the method _updateConversion is executed once, the methods toTime
  3700. * and toScreen can be used.
  3701. * @private
  3702. */
  3703. ItemSet.prototype._updateConversion = function() {
  3704. var range = this.range;
  3705. if (!range) {
  3706. throw new Error('No range configured');
  3707. }
  3708. if (range.conversion) {
  3709. this.conversion = range.conversion(this.width);
  3710. }
  3711. else {
  3712. this.conversion = Range.conversion(range.start, range.end, this.width);
  3713. }
  3714. };
  3715. /**
  3716. * Convert a position on screen (pixels) to a datetime
  3717. * Before this method can be used, the method _updateConversion must be
  3718. * executed once.
  3719. * @param {int} x Position on the screen in pixels
  3720. * @return {Date} time The datetime the corresponds with given position x
  3721. */
  3722. ItemSet.prototype.toTime = function(x) {
  3723. var conversion = this.conversion;
  3724. return new Date(x / conversion.factor + conversion.offset);
  3725. };
  3726. /**
  3727. * Convert a datetime (Date object) into a position on the screen
  3728. * Before this method can be used, the method _updateConversion must be
  3729. * executed once.
  3730. * @param {Date} time A date
  3731. * @return {int} x The position on the screen in pixels which corresponds
  3732. * with the given date.
  3733. */
  3734. ItemSet.prototype.toScreen = function(time) {
  3735. var conversion = this.conversion;
  3736. return (time.valueOf() - conversion.offset) * conversion.factor;
  3737. };
  3738. /**
  3739. * @constructor Item
  3740. * @param {ItemSet} parent
  3741. * @param {Object} data Object containing (optional) parameters type,
  3742. * start, end, content, group, className.
  3743. * @param {Object} [options] Options to set initial property values
  3744. * // TODO: describe available options
  3745. */
  3746. function Item (parent, data, options) {
  3747. this.parent = parent;
  3748. this.data = data;
  3749. this.selected = false;
  3750. this.visible = true;
  3751. this.dom = null;
  3752. this.options = options;
  3753. }
  3754. Item.prototype = new Component();
  3755. /**
  3756. * Select current item
  3757. */
  3758. Item.prototype.select = function () {
  3759. this.selected = true;
  3760. };
  3761. /**
  3762. * Unselect current item
  3763. */
  3764. Item.prototype.unselect = function () {
  3765. this.selected = false;
  3766. };
  3767. /**
  3768. * @constructor ItemBox
  3769. * @extends Item
  3770. * @param {ItemSet} parent
  3771. * @param {Object} data Object containing parameters start
  3772. * content, className.
  3773. * @param {Object} [options] Options to set initial property values
  3774. * // TODO: describe available options
  3775. */
  3776. function ItemBox (parent, data, options) {
  3777. this.props = {
  3778. dot: {
  3779. left: 0,
  3780. top: 0,
  3781. width: 0,
  3782. height: 0
  3783. },
  3784. line: {
  3785. top: 0,
  3786. left: 0,
  3787. width: 0,
  3788. height: 0
  3789. }
  3790. };
  3791. Item.call(this, parent, data, options);
  3792. }
  3793. ItemBox.prototype = new Item (null, null);
  3794. /**
  3795. * Select the item
  3796. * @override
  3797. */
  3798. ItemBox.prototype.select = function () {
  3799. this.selected = true;
  3800. // TODO: select and unselect
  3801. };
  3802. /**
  3803. * Unselect the item
  3804. * @override
  3805. */
  3806. ItemBox.prototype.unselect = function () {
  3807. this.selected = false;
  3808. // TODO: select and unselect
  3809. };
  3810. /**
  3811. * Repaint the item
  3812. * @return {Boolean} changed
  3813. */
  3814. ItemBox.prototype.repaint = function () {
  3815. // TODO: make an efficient repaint
  3816. var changed = false;
  3817. var dom = this.dom;
  3818. if (this.visible) {
  3819. if (!dom) {
  3820. this._create();
  3821. changed = true;
  3822. }
  3823. dom = this.dom;
  3824. if (dom) {
  3825. if (!this.options && !this.parent) {
  3826. throw new Error('Cannot repaint item: no parent attached');
  3827. }
  3828. var foreground = this.parent.getForeground();
  3829. if (!foreground) {
  3830. throw new Error('Cannot repaint time axis: ' +
  3831. 'parent has no foreground container element');
  3832. }
  3833. var background = this.parent.getBackground();
  3834. if (!background) {
  3835. throw new Error('Cannot repaint time axis: ' +
  3836. 'parent has no background container element');
  3837. }
  3838. if (!dom.box.parentNode) {
  3839. foreground.appendChild(dom.box);
  3840. changed = true;
  3841. }
  3842. if (!dom.line.parentNode) {
  3843. background.appendChild(dom.line);
  3844. changed = true;
  3845. }
  3846. if (!dom.dot.parentNode) {
  3847. this.parent.dom.axis.appendChild(dom.dot);
  3848. changed = true;
  3849. }
  3850. // update contents
  3851. if (this.data.content != this.content) {
  3852. this.content = this.data.content;
  3853. if (this.content instanceof Element) {
  3854. dom.content.innerHTML = '';
  3855. dom.content.appendChild(this.content);
  3856. }
  3857. else if (this.data.content != undefined) {
  3858. dom.content.innerHTML = this.content;
  3859. }
  3860. else {
  3861. throw new Error('Property "content" missing in item ' + this.data.id);
  3862. }
  3863. changed = true;
  3864. }
  3865. // update class
  3866. var className = (this.data.className? ' ' + this.data.className : '') +
  3867. (this.selected ? ' selected' : '');
  3868. if (this.className != className) {
  3869. this.className = className;
  3870. dom.box.className = 'item box' + className;
  3871. dom.line.className = 'item line' + className;
  3872. dom.dot.className = 'item dot' + className;
  3873. changed = true;
  3874. }
  3875. }
  3876. }
  3877. else {
  3878. // hide when visible
  3879. if (dom) {
  3880. if (dom.box.parentNode) {
  3881. dom.box.parentNode.removeChild(dom.box);
  3882. changed = true;
  3883. }
  3884. if (dom.line.parentNode) {
  3885. dom.line.parentNode.removeChild(dom.line);
  3886. changed = true;
  3887. }
  3888. if (dom.dot.parentNode) {
  3889. dom.dot.parentNode.removeChild(dom.dot);
  3890. changed = true;
  3891. }
  3892. }
  3893. }
  3894. return changed;
  3895. };
  3896. /**
  3897. * Reflow the item: calculate its actual size and position from the DOM
  3898. * @return {boolean} resized returns true if the axis is resized
  3899. * @override
  3900. */
  3901. ItemBox.prototype.reflow = function () {
  3902. if (this.data.start == undefined) {
  3903. throw new Error('Property "start" missing in item ' + this.data.id);
  3904. }
  3905. var update = util.updateProperty,
  3906. dom = this.dom,
  3907. props = this.props,
  3908. options = this.options,
  3909. start = this.parent.toScreen(this.data.start),
  3910. align = options && options.align,
  3911. orientation = options.orientation,
  3912. changed = 0,
  3913. top,
  3914. left;
  3915. if (dom) {
  3916. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  3917. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  3918. changed += update(props.line, 'width', dom.line.offsetWidth);
  3919. changed += update(props.line, 'width', dom.line.offsetWidth);
  3920. changed += update(this, 'width', dom.box.offsetWidth);
  3921. changed += update(this, 'height', dom.box.offsetHeight);
  3922. if (align == 'right') {
  3923. left = start - this.width;
  3924. }
  3925. else if (align == 'left') {
  3926. left = start;
  3927. }
  3928. else {
  3929. // default or 'center'
  3930. left = start - this.width / 2;
  3931. }
  3932. changed += update(this, 'left', left);
  3933. changed += update(props.line, 'left', start - props.line.width / 2);
  3934. changed += update(props.dot, 'left', start - props.dot.width / 2);
  3935. if (orientation == 'top') {
  3936. top = options.margin.axis;
  3937. changed += update(this, 'top', top);
  3938. changed += update(props.line, 'top', 0);
  3939. changed += update(props.line, 'height', top);
  3940. changed += update(props.dot, 'top', -props.dot.height / 2);
  3941. }
  3942. else {
  3943. // default or 'bottom'
  3944. var parentHeight = this.parent.height;
  3945. top = parentHeight - this.height - options.margin.axis;
  3946. changed += update(this, 'top', top);
  3947. changed += update(props.line, 'top', top + this.height);
  3948. changed += update(props.line, 'height', Math.max(options.margin.axis, 0));
  3949. changed += update(props.dot, 'top', parentHeight - props.dot.height / 2);
  3950. }
  3951. }
  3952. else {
  3953. changed += 1;
  3954. }
  3955. return (changed > 0);
  3956. };
  3957. /**
  3958. * Create an items DOM
  3959. * @private
  3960. */
  3961. ItemBox.prototype._create = function () {
  3962. var dom = this.dom;
  3963. if (!dom) {
  3964. this.dom = dom = {};
  3965. // create the box
  3966. dom.box = document.createElement('DIV');
  3967. // className is updated in repaint()
  3968. // contents box (inside the background box). used for making margins
  3969. dom.content = document.createElement('DIV');
  3970. dom.content.className = 'content';
  3971. dom.box.appendChild(dom.content);
  3972. // line to axis
  3973. dom.line = document.createElement('DIV');
  3974. dom.line.className = 'line';
  3975. // dot on axis
  3976. dom.dot = document.createElement('DIV');
  3977. dom.dot.className = 'dot';
  3978. }
  3979. };
  3980. /**
  3981. * Reposition the item, recalculate its left, top, and width, using the current
  3982. * range and size of the items itemset
  3983. * @override
  3984. */
  3985. ItemBox.prototype.reposition = function () {
  3986. var dom = this.dom,
  3987. props = this.props,
  3988. orientation = this.options.orientation;
  3989. if (dom) {
  3990. var box = dom.box,
  3991. line = dom.line,
  3992. dot = dom.dot;
  3993. box.style.left = this.left + 'px';
  3994. box.style.top = this.top + 'px';
  3995. line.style.left = props.line.left + 'px';
  3996. if (orientation == 'top') {
  3997. line.style.top = 0 + 'px';
  3998. line.style.height = this.top + 'px';
  3999. }
  4000. else {
  4001. // orientation 'bottom'
  4002. line.style.top = props.line.top + 'px';
  4003. line.style.top = (this.top + this.height) + 'px';
  4004. line.style.height = Math.max(props.dot.top - this.top - this.height, 0) + 'px';
  4005. }
  4006. dot.style.left = props.dot.left + 'px';
  4007. dot.style.top = props.dot.top + 'px';
  4008. }
  4009. };
  4010. /**
  4011. * @constructor ItemPoint
  4012. * @extends Item
  4013. * @param {ItemSet} parent
  4014. * @param {Object} data Object containing parameters start
  4015. * content, className.
  4016. * @param {Object} [options] Options to set initial property values
  4017. * // TODO: describe available options
  4018. */
  4019. function ItemPoint (parent, data, options) {
  4020. this.props = {
  4021. dot: {
  4022. top: 0,
  4023. width: 0,
  4024. height: 0
  4025. },
  4026. content: {
  4027. height: 0,
  4028. marginLeft: 0
  4029. }
  4030. };
  4031. Item.call(this, parent, data, options);
  4032. }
  4033. ItemPoint.prototype = new Item (null, null);
  4034. /**
  4035. * Select the item
  4036. * @override
  4037. */
  4038. ItemPoint.prototype.select = function () {
  4039. this.selected = true;
  4040. // TODO: select and unselect
  4041. };
  4042. /**
  4043. * Unselect the item
  4044. * @override
  4045. */
  4046. ItemPoint.prototype.unselect = function () {
  4047. this.selected = false;
  4048. // TODO: select and unselect
  4049. };
  4050. /**
  4051. * Repaint the item
  4052. * @return {Boolean} changed
  4053. */
  4054. ItemPoint.prototype.repaint = function () {
  4055. // TODO: make an efficient repaint
  4056. var changed = false;
  4057. var dom = this.dom;
  4058. if (this.visible) {
  4059. if (!dom) {
  4060. this._create();
  4061. changed = true;
  4062. }
  4063. dom = this.dom;
  4064. if (dom) {
  4065. if (!this.options && !this.options.parent) {
  4066. throw new Error('Cannot repaint item: no parent attached');
  4067. }
  4068. var foreground = this.parent.getForeground();
  4069. if (!foreground) {
  4070. throw new Error('Cannot repaint time axis: ' +
  4071. 'parent has no foreground container element');
  4072. }
  4073. if (!dom.point.parentNode) {
  4074. foreground.appendChild(dom.point);
  4075. foreground.appendChild(dom.point);
  4076. changed = true;
  4077. }
  4078. // update contents
  4079. if (this.data.content != this.content) {
  4080. this.content = this.data.content;
  4081. if (this.content instanceof Element) {
  4082. dom.content.innerHTML = '';
  4083. dom.content.appendChild(this.content);
  4084. }
  4085. else if (this.data.content != undefined) {
  4086. dom.content.innerHTML = this.content;
  4087. }
  4088. else {
  4089. throw new Error('Property "content" missing in item ' + this.data.id);
  4090. }
  4091. changed = true;
  4092. }
  4093. // update class
  4094. var className = (this.data.className? ' ' + this.data.className : '') +
  4095. (this.selected ? ' selected' : '');
  4096. if (this.className != className) {
  4097. this.className = className;
  4098. dom.point.className = 'item point' + className;
  4099. changed = true;
  4100. }
  4101. }
  4102. }
  4103. else {
  4104. // hide when visible
  4105. if (dom) {
  4106. if (dom.point.parentNode) {
  4107. dom.point.parentNode.removeChild(dom.point);
  4108. changed = true;
  4109. }
  4110. }
  4111. }
  4112. return changed;
  4113. };
  4114. /**
  4115. * Reflow the item: calculate its actual size from the DOM
  4116. * @return {boolean} resized returns true if the axis is resized
  4117. * @override
  4118. */
  4119. ItemPoint.prototype.reflow = function () {
  4120. if (this.data.start == undefined) {
  4121. throw new Error('Property "start" missing in item ' + this.data.id);
  4122. }
  4123. var update = util.updateProperty,
  4124. dom = this.dom,
  4125. props = this.props,
  4126. options = this.options,
  4127. orientation = options.orientation,
  4128. start = this.parent.toScreen(this.data.start),
  4129. changed = 0,
  4130. top;
  4131. if (dom) {
  4132. changed += update(this, 'width', dom.point.offsetWidth);
  4133. changed += update(this, 'height', dom.point.offsetHeight);
  4134. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  4135. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  4136. changed += update(props.content, 'height', dom.content.offsetHeight);
  4137. if (orientation == 'top') {
  4138. top = options.margin.axis;
  4139. }
  4140. else {
  4141. // default or 'bottom'
  4142. var parentHeight = this.parent.height;
  4143. top = Math.max(parentHeight - this.height - options.margin.axis, 0);
  4144. }
  4145. changed += update(this, 'top', top);
  4146. changed += update(this, 'left', start - props.dot.width / 2);
  4147. changed += update(props.content, 'marginLeft', 1.5 * props.dot.width);
  4148. //changed += update(props.content, 'marginRight', 0.5 * props.dot.width); // TODO
  4149. changed += update(props.dot, 'top', (this.height - props.dot.height) / 2);
  4150. }
  4151. else {
  4152. changed += 1;
  4153. }
  4154. return (changed > 0);
  4155. };
  4156. /**
  4157. * Create an items DOM
  4158. * @private
  4159. */
  4160. ItemPoint.prototype._create = function () {
  4161. var dom = this.dom;
  4162. if (!dom) {
  4163. this.dom = dom = {};
  4164. // background box
  4165. dom.point = document.createElement('div');
  4166. // className is updated in repaint()
  4167. // contents box, right from the dot
  4168. dom.content = document.createElement('div');
  4169. dom.content.className = 'content';
  4170. dom.point.appendChild(dom.content);
  4171. // dot at start
  4172. dom.dot = document.createElement('div');
  4173. dom.dot.className = 'dot';
  4174. dom.point.appendChild(dom.dot);
  4175. }
  4176. };
  4177. /**
  4178. * Reposition the item, recalculate its left, top, and width, using the current
  4179. * range and size of the items itemset
  4180. * @override
  4181. */
  4182. ItemPoint.prototype.reposition = function () {
  4183. var dom = this.dom,
  4184. props = this.props;
  4185. if (dom) {
  4186. dom.point.style.top = this.top + 'px';
  4187. dom.point.style.left = this.left + 'px';
  4188. dom.content.style.marginLeft = props.content.marginLeft + 'px';
  4189. //dom.content.style.marginRight = props.content.marginRight + 'px'; // TODO
  4190. dom.dot.style.top = props.dot.top + 'px';
  4191. }
  4192. };
  4193. /**
  4194. * @constructor ItemRange
  4195. * @extends Item
  4196. * @param {ItemSet} parent
  4197. * @param {Object} data Object containing parameters start, end
  4198. * content, className.
  4199. * @param {Object} [options] Options to set initial property values
  4200. * // TODO: describe available options
  4201. */
  4202. function ItemRange (parent, data, options) {
  4203. this.props = {
  4204. content: {
  4205. left: 0,
  4206. width: 0
  4207. }
  4208. };
  4209. Item.call(this, parent, data, options);
  4210. }
  4211. ItemRange.prototype = new Item (null, null);
  4212. /**
  4213. * Select the item
  4214. * @override
  4215. */
  4216. ItemRange.prototype.select = function () {
  4217. this.selected = true;
  4218. // TODO: select and unselect
  4219. };
  4220. /**
  4221. * Unselect the item
  4222. * @override
  4223. */
  4224. ItemRange.prototype.unselect = function () {
  4225. this.selected = false;
  4226. // TODO: select and unselect
  4227. };
  4228. /**
  4229. * Repaint the item
  4230. * @return {Boolean} changed
  4231. */
  4232. ItemRange.prototype.repaint = function () {
  4233. // TODO: make an efficient repaint
  4234. var changed = false;
  4235. var dom = this.dom;
  4236. if (this.visible) {
  4237. if (!dom) {
  4238. this._create();
  4239. changed = true;
  4240. }
  4241. dom = this.dom;
  4242. if (dom) {
  4243. if (!this.options && !this.options.parent) {
  4244. throw new Error('Cannot repaint item: no parent attached');
  4245. }
  4246. var foreground = this.parent.getForeground();
  4247. if (!foreground) {
  4248. throw new Error('Cannot repaint time axis: ' +
  4249. 'parent has no foreground container element');
  4250. }
  4251. if (!dom.box.parentNode) {
  4252. foreground.appendChild(dom.box);
  4253. changed = true;
  4254. }
  4255. // update content
  4256. if (this.data.content != this.content) {
  4257. this.content = this.data.content;
  4258. if (this.content instanceof Element) {
  4259. dom.content.innerHTML = '';
  4260. dom.content.appendChild(this.content);
  4261. }
  4262. else if (this.data.content != undefined) {
  4263. dom.content.innerHTML = this.content;
  4264. }
  4265. else {
  4266. throw new Error('Property "content" missing in item ' + this.data.id);
  4267. }
  4268. changed = true;
  4269. }
  4270. // update class
  4271. var className = this.data.className ? ('' + this.data.className) : '';
  4272. if (this.className != className) {
  4273. this.className = className;
  4274. dom.box.className = 'item range' + className;
  4275. changed = true;
  4276. }
  4277. }
  4278. }
  4279. else {
  4280. // hide when visible
  4281. if (dom) {
  4282. if (dom.box.parentNode) {
  4283. dom.box.parentNode.removeChild(dom.box);
  4284. changed = true;
  4285. }
  4286. }
  4287. }
  4288. return changed;
  4289. };
  4290. /**
  4291. * Reflow the item: calculate its actual size from the DOM
  4292. * @return {boolean} resized returns true if the axis is resized
  4293. * @override
  4294. */
  4295. ItemRange.prototype.reflow = function () {
  4296. if (this.data.start == undefined) {
  4297. throw new Error('Property "start" missing in item ' + this.data.id);
  4298. }
  4299. if (this.data.end == undefined) {
  4300. throw new Error('Property "end" missing in item ' + this.data.id);
  4301. }
  4302. var dom = this.dom,
  4303. props = this.props,
  4304. options = this.options,
  4305. parent = this.parent,
  4306. start = parent.toScreen(this.data.start),
  4307. end = parent.toScreen(this.data.end),
  4308. changed = 0;
  4309. if (dom) {
  4310. var update = util.updateProperty,
  4311. box = dom.box,
  4312. parentWidth = parent.width,
  4313. orientation = options.orientation,
  4314. contentLeft,
  4315. top;
  4316. changed += update(props.content, 'width', dom.content.offsetWidth);
  4317. changed += update(this, 'height', box.offsetHeight);
  4318. // limit the width of the this, as browsers cannot draw very wide divs
  4319. if (start < -parentWidth) {
  4320. start = -parentWidth;
  4321. }
  4322. if (end > 2 * parentWidth) {
  4323. end = 2 * parentWidth;
  4324. }
  4325. // when range exceeds left of the window, position the contents at the left of the visible area
  4326. if (start < 0) {
  4327. contentLeft = Math.min(-start,
  4328. (end - start - props.content.width - 2 * options.padding));
  4329. // TODO: remove the need for options.padding. it's terrible.
  4330. }
  4331. else {
  4332. contentLeft = 0;
  4333. }
  4334. changed += update(props.content, 'left', contentLeft);
  4335. if (orientation == 'top') {
  4336. top = options.margin.axis;
  4337. changed += update(this, 'top', top);
  4338. }
  4339. else {
  4340. // default or 'bottom'
  4341. top = parent.height - this.height - options.margin.axis;
  4342. changed += update(this, 'top', top);
  4343. }
  4344. changed += update(this, 'left', start);
  4345. changed += update(this, 'width', Math.max(end - start, 1)); // TODO: reckon with border width;
  4346. }
  4347. else {
  4348. changed += 1;
  4349. }
  4350. return (changed > 0);
  4351. };
  4352. /**
  4353. * Create an items DOM
  4354. * @private
  4355. */
  4356. ItemRange.prototype._create = function () {
  4357. var dom = this.dom;
  4358. if (!dom) {
  4359. this.dom = dom = {};
  4360. // background box
  4361. dom.box = document.createElement('div');
  4362. // className is updated in repaint()
  4363. // contents box
  4364. dom.content = document.createElement('div');
  4365. dom.content.className = 'content';
  4366. dom.box.appendChild(dom.content);
  4367. }
  4368. };
  4369. /**
  4370. * Reposition the item, recalculate its left, top, and width, using the current
  4371. * range and size of the items itemset
  4372. * @override
  4373. */
  4374. ItemRange.prototype.reposition = function () {
  4375. var dom = this.dom,
  4376. props = this.props;
  4377. if (dom) {
  4378. dom.box.style.top = this.top + 'px';
  4379. dom.box.style.left = this.left + 'px';
  4380. dom.box.style.width = this.width + 'px';
  4381. dom.content.style.left = props.content.left + 'px';
  4382. }
  4383. };
  4384. /**
  4385. * Create a timeline visualization
  4386. * @param {HTMLElement} container
  4387. * @param {DataSet | Array | DataTable} [data]
  4388. * @param {Object} [options] See Timeline.setOptions for the available options.
  4389. * @constructor
  4390. */
  4391. function Timeline (container, data, options) {
  4392. var me = this;
  4393. this.options = {
  4394. orientation: 'bottom',
  4395. zoomMin: 10, // milliseconds
  4396. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  4397. moveable: true,
  4398. zoomable: true
  4399. };
  4400. // controller
  4401. this.controller = new Controller();
  4402. // main panel
  4403. if (!container) {
  4404. throw new Error('No container element provided');
  4405. }
  4406. this.main = new RootPanel(container, {
  4407. autoResize: false,
  4408. height: function () {
  4409. return me.timeaxis.height + me.itemset.height;
  4410. }
  4411. });
  4412. this.controller.add(this.main);
  4413. // range
  4414. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  4415. this.range = new Range({
  4416. start: now.clone().add('days', -3).valueOf(),
  4417. end: now.clone().add('days', 4).valueOf()
  4418. });
  4419. // TODO: reckon with options moveable and zoomable
  4420. this.range.subscribe(this.main, 'move', 'horizontal');
  4421. this.range.subscribe(this.main, 'zoom', 'horizontal');
  4422. this.range.on('rangechange', function () {
  4423. // TODO: fix the delay in reflow/repaint, does not feel snappy
  4424. me.controller.requestReflow();
  4425. });
  4426. this.range.on('rangechanged', function () {
  4427. me.controller.requestReflow();
  4428. });
  4429. // TODO: put the listeners in setOptions, be able to dynamically change with options moveable and zoomable
  4430. // time axis
  4431. this.timeaxis = new TimeAxis(this.main, [], {
  4432. orientation: this.options.orientation,
  4433. range: this.range
  4434. });
  4435. this.timeaxis.setRange(this.range);
  4436. this.controller.add(this.timeaxis);
  4437. // items panel
  4438. this.itemset = new ItemSet(this.main, [this.timeaxis], {
  4439. orientation: this.options.orientation
  4440. });
  4441. this.itemset.setRange(this.range);
  4442. this.controller.add(this.itemset);
  4443. // set data
  4444. if (data) {
  4445. this.setData(data);
  4446. }
  4447. this.setOptions(options);
  4448. }
  4449. /**
  4450. * Set options
  4451. * @param {Object} options TODO: describe the available options
  4452. */
  4453. Timeline.prototype.setOptions = function (options) {
  4454. util.extend(this.options, options);
  4455. // update options the timeaxis
  4456. this.timeaxis.setOptions(this.options);
  4457. // update options for the range
  4458. this.range.setOptions(this.options);
  4459. // update options the itemset
  4460. var top,
  4461. me = this;
  4462. if (this.options.orientation == 'top') {
  4463. top = function () {
  4464. return me.timeaxis.height;
  4465. }
  4466. }
  4467. else {
  4468. top = function () {
  4469. return me.main.height - me.timeaxis.height - me.itemset.height;
  4470. }
  4471. }
  4472. this.itemset.setOptions({
  4473. orientation: this.options.orientation,
  4474. top: top
  4475. });
  4476. this.controller.repaint();
  4477. };
  4478. /**
  4479. * Set data
  4480. * @param {DataSet | Array | DataTable} data
  4481. */
  4482. Timeline.prototype.setData = function(data) {
  4483. var dataset = this.itemset.data;
  4484. if (!dataset) {
  4485. // first load of data
  4486. this.itemset.setData(data);
  4487. // apply the data range as range
  4488. var dataRange = this.itemset.getDataRange();
  4489. // add 5% on both sides
  4490. var min = dataRange.min;
  4491. var max = dataRange.max;
  4492. if (min != null && max != null) {
  4493. var interval = (max.valueOf() - min.valueOf());
  4494. min = new Date(min.valueOf() - interval * 0.05);
  4495. max = new Date(max.valueOf() + interval * 0.05);
  4496. }
  4497. // apply range if there is a min or max available
  4498. if (min != null || max != null) {
  4499. this.range.setRange(min, max);
  4500. }
  4501. }
  4502. else {
  4503. // updated data
  4504. this.itemset.setData(data);
  4505. }
  4506. };
  4507. /**
  4508. * vis.js library exports
  4509. */
  4510. var vis = {
  4511. util: util,
  4512. events: events,
  4513. Controller: Controller,
  4514. DataSet: DataSet,
  4515. Range: Range,
  4516. Stack: Stack,
  4517. TimeStep: TimeStep,
  4518. components: {
  4519. items: {
  4520. Item: Item,
  4521. ItemBox: ItemBox,
  4522. ItemPoint: ItemPoint,
  4523. ItemRange: ItemRange
  4524. },
  4525. Component: Component,
  4526. Panel: Panel,
  4527. RootPanel: RootPanel,
  4528. ItemSet: ItemSet,
  4529. TimeAxis: TimeAxis
  4530. },
  4531. Timeline: Timeline
  4532. };
  4533. /**
  4534. * CommonJS module exports
  4535. */
  4536. if (typeof exports !== 'undefined') {
  4537. exports = vis;
  4538. }
  4539. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  4540. module.exports = vis;
  4541. }
  4542. /**
  4543. * AMD module exports
  4544. */
  4545. if (typeof(define) === 'function') {
  4546. define(function () {
  4547. return vis;
  4548. });
  4549. }
  4550. /**
  4551. * Window exports
  4552. */
  4553. if (typeof window !== 'undefined') {
  4554. // attach the module to the window, load as a regular javascript file
  4555. window['vis'] = vis;
  4556. }
  4557. util.loadCss("/* vis.js stylesheet */\n\n.graph {\n position: relative;\n border: 1px solid #bfbfbf;\n}\n\n.graph .panel {\n position: absolute;\n}\n\n.graph .itemset {\n position: absolute;\n padding: 0;\n margin: 0;\n overflow: hidden;\n}\n\n.graph .background {\n}\n\n.graph .foreground {\n}\n\n.graph .itemset-axis {\n position: absolute;\n}\n\n.graph .item {\n position: absolute;\n color: #1A1A1A;\n border-color: #97B0F8;\n background-color: #D5DDF6;\n display: inline-block;\n}\n\n.graph .item.selected {\n border-color: #FFC200;\n background-color: #FFF785;\n z-index: 999;\n}\n\n.graph .item.cluster {\n /* TODO: use another color or pattern? */\n background: #97B0F8 url('img/cluster_bg.png');\n color: white;\n}\n.graph .item.cluster.point {\n border-color: #D5DDF6;\n}\n\n.graph .item.box {\n text-align: center;\n border-style: solid;\n border-width: 1px;\n border-radius: 5px;\n -moz-border-radius: 5px; /* For Firefox 3.6 and older */\n}\n\n.graph .item.point {\n background: none;\n}\n\n.graph .dot {\n border: 5px solid #97B0F8;\n position: absolute;\n border-radius: 5px;\n -moz-border-radius: 5px; /* For Firefox 3.6 and older */\n}\n\n.graph .item.range {\n overflow: hidden;\n border-style: solid;\n border-width: 1px;\n border-radius: 2px;\n -moz-border-radius: 2px; /* For Firefox 3.6 and older */\n}\n\n.graph .item.range .drag-left {\n cursor: w-resize;\n z-index: 1000;\n}\n\n.graph .item.range .drag-right {\n cursor: e-resize;\n z-index: 1000;\n}\n\n.graph .item.range .content {\n position: relative;\n display: inline-block;\n}\n\n.graph .item.line {\n position: absolute;\n width: 0;\n border-left-width: 1px;\n border-left-style: solid;\n}\n\n.graph .item .content {\n margin: 5px;\n white-space: nowrap;\n overflow: hidden;\n}\n\n/* TODO: better css name, 'graph' is way to generic */\n\n.graph {\n overflow: hidden;\n}\n\n.graph .axis {\n position: relative;\n}\n\n.graph .axis .text {\n position: absolute;\n color: #4d4d4d;\n padding: 3px;\n white-space: nowrap;\n}\n\n.graph .axis .text.measure {\n position: absolute;\n padding-left: 0;\n padding-right: 0;\n margin-left: 0;\n margin-right: 0;\n visibility: hidden;\n}\n\n.graph .axis .grid.vertical {\n position: absolute;\n width: 0;\n border-right: 1px solid;\n}\n\n.graph .axis .grid.horizontal {\n position: absolute;\n left: 0;\n width: 100%;\n height: 0;\n border-bottom: 1px solid;\n}\n\n.graph .axis .grid.minor {\n border-color: #e5e5e5;\n}\n\n.graph .axis .grid.major {\n border-color: #bfbfbf;\n}\n\n");
  4558. },{"moment":2}],2:[function(require,module,exports){
  4559. (function(){// moment.js
  4560. // version : 2.0.0
  4561. // author : Tim Wood
  4562. // license : MIT
  4563. // momentjs.com
  4564. (function (undefined) {
  4565. /************************************
  4566. Constants
  4567. ************************************/
  4568. var moment,
  4569. VERSION = "2.0.0",
  4570. round = Math.round, i,
  4571. // internal storage for language config files
  4572. languages = {},
  4573. // check for nodeJS
  4574. hasModule = (typeof module !== 'undefined' && module.exports),
  4575. // ASP.NET json date format regex
  4576. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  4577. // format tokens
  4578. formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|YYYYY|YYYY|YY|a|A|hh?|HH?|mm?|ss?|SS?S?|X|zz?|ZZ?|.)/g,
  4579. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  4580. // parsing tokens
  4581. parseMultipleFormatChunker = /([0-9a-zA-Z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)/gi,
  4582. // parsing token regexes
  4583. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  4584. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  4585. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  4586. parseTokenFourDigits = /\d{1,4}/, // 0 - 9999
  4587. parseTokenSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  4588. parseTokenWord = /[0-9]*[a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF]+\s*?[\u0600-\u06FF]+/i, // any word (or two) characters or numbers including two word month in arabic.
  4589. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/i, // +00:00 -00:00 +0000 -0000 or Z
  4590. parseTokenT = /T/i, // T (ISO seperator)
  4591. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  4592. // preliminary iso regex
  4593. // 0000-00-00 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000
  4594. isoRegex = /^\s*\d{4}-\d\d-\d\d((T| )(\d\d(:\d\d(:\d\d(\.\d\d?\d?)?)?)?)?([\+\-]\d\d:?\d\d)?)?/,
  4595. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  4596. // iso time formats and regexes
  4597. isoTimes = [
  4598. ['HH:mm:ss.S', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/],
  4599. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  4600. ['HH:mm', /(T| )\d\d:\d\d/],
  4601. ['HH', /(T| )\d\d/]
  4602. ],
  4603. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  4604. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  4605. // getter and setter names
  4606. proxyGettersAndSetters = 'Month|Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  4607. unitMillisecondFactors = {
  4608. 'Milliseconds' : 1,
  4609. 'Seconds' : 1e3,
  4610. 'Minutes' : 6e4,
  4611. 'Hours' : 36e5,
  4612. 'Days' : 864e5,
  4613. 'Months' : 2592e6,
  4614. 'Years' : 31536e6
  4615. },
  4616. // format function strings
  4617. formatFunctions = {},
  4618. // tokens to ordinalize and pad
  4619. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  4620. paddedTokens = 'M D H h m s w W'.split(' '),
  4621. formatTokenFunctions = {
  4622. M : function () {
  4623. return this.month() + 1;
  4624. },
  4625. MMM : function (format) {
  4626. return this.lang().monthsShort(this, format);
  4627. },
  4628. MMMM : function (format) {
  4629. return this.lang().months(this, format);
  4630. },
  4631. D : function () {
  4632. return this.date();
  4633. },
  4634. DDD : function () {
  4635. return this.dayOfYear();
  4636. },
  4637. d : function () {
  4638. return this.day();
  4639. },
  4640. dd : function (format) {
  4641. return this.lang().weekdaysMin(this, format);
  4642. },
  4643. ddd : function (format) {
  4644. return this.lang().weekdaysShort(this, format);
  4645. },
  4646. dddd : function (format) {
  4647. return this.lang().weekdays(this, format);
  4648. },
  4649. w : function () {
  4650. return this.week();
  4651. },
  4652. W : function () {
  4653. return this.isoWeek();
  4654. },
  4655. YY : function () {
  4656. return leftZeroFill(this.year() % 100, 2);
  4657. },
  4658. YYYY : function () {
  4659. return leftZeroFill(this.year(), 4);
  4660. },
  4661. YYYYY : function () {
  4662. return leftZeroFill(this.year(), 5);
  4663. },
  4664. a : function () {
  4665. return this.lang().meridiem(this.hours(), this.minutes(), true);
  4666. },
  4667. A : function () {
  4668. return this.lang().meridiem(this.hours(), this.minutes(), false);
  4669. },
  4670. H : function () {
  4671. return this.hours();
  4672. },
  4673. h : function () {
  4674. return this.hours() % 12 || 12;
  4675. },
  4676. m : function () {
  4677. return this.minutes();
  4678. },
  4679. s : function () {
  4680. return this.seconds();
  4681. },
  4682. S : function () {
  4683. return ~~(this.milliseconds() / 100);
  4684. },
  4685. SS : function () {
  4686. return leftZeroFill(~~(this.milliseconds() / 10), 2);
  4687. },
  4688. SSS : function () {
  4689. return leftZeroFill(this.milliseconds(), 3);
  4690. },
  4691. Z : function () {
  4692. var a = -this.zone(),
  4693. b = "+";
  4694. if (a < 0) {
  4695. a = -a;
  4696. b = "-";
  4697. }
  4698. return b + leftZeroFill(~~(a / 60), 2) + ":" + leftZeroFill(~~a % 60, 2);
  4699. },
  4700. ZZ : function () {
  4701. var a = -this.zone(),
  4702. b = "+";
  4703. if (a < 0) {
  4704. a = -a;
  4705. b = "-";
  4706. }
  4707. return b + leftZeroFill(~~(10 * a / 6), 4);
  4708. },
  4709. X : function () {
  4710. return this.unix();
  4711. }
  4712. };
  4713. function padToken(func, count) {
  4714. return function (a) {
  4715. return leftZeroFill(func.call(this, a), count);
  4716. };
  4717. }
  4718. function ordinalizeToken(func) {
  4719. return function (a) {
  4720. return this.lang().ordinal(func.call(this, a));
  4721. };
  4722. }
  4723. while (ordinalizeTokens.length) {
  4724. i = ordinalizeTokens.pop();
  4725. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i]);
  4726. }
  4727. while (paddedTokens.length) {
  4728. i = paddedTokens.pop();
  4729. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  4730. }
  4731. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  4732. /************************************
  4733. Constructors
  4734. ************************************/
  4735. function Language() {
  4736. }
  4737. // Moment prototype object
  4738. function Moment(config) {
  4739. extend(this, config);
  4740. }
  4741. // Duration Constructor
  4742. function Duration(duration) {
  4743. var data = this._data = {},
  4744. years = duration.years || duration.year || duration.y || 0,
  4745. months = duration.months || duration.month || duration.M || 0,
  4746. weeks = duration.weeks || duration.week || duration.w || 0,
  4747. days = duration.days || duration.day || duration.d || 0,
  4748. hours = duration.hours || duration.hour || duration.h || 0,
  4749. minutes = duration.minutes || duration.minute || duration.m || 0,
  4750. seconds = duration.seconds || duration.second || duration.s || 0,
  4751. milliseconds = duration.milliseconds || duration.millisecond || duration.ms || 0;
  4752. // representation for dateAddRemove
  4753. this._milliseconds = milliseconds +
  4754. seconds * 1e3 + // 1000
  4755. minutes * 6e4 + // 1000 * 60
  4756. hours * 36e5; // 1000 * 60 * 60
  4757. // Because of dateAddRemove treats 24 hours as different from a
  4758. // day when working around DST, we need to store them separately
  4759. this._days = days +
  4760. weeks * 7;
  4761. // It is impossible translate months into days without knowing
  4762. // which months you are are talking about, so we have to store
  4763. // it separately.
  4764. this._months = months +
  4765. years * 12;
  4766. // The following code bubbles up values, see the tests for
  4767. // examples of what that means.
  4768. data.milliseconds = milliseconds % 1000;
  4769. seconds += absRound(milliseconds / 1000);
  4770. data.seconds = seconds % 60;
  4771. minutes += absRound(seconds / 60);
  4772. data.minutes = minutes % 60;
  4773. hours += absRound(minutes / 60);
  4774. data.hours = hours % 24;
  4775. days += absRound(hours / 24);
  4776. days += weeks * 7;
  4777. data.days = days % 30;
  4778. months += absRound(days / 30);
  4779. data.months = months % 12;
  4780. years += absRound(months / 12);
  4781. data.years = years;
  4782. }
  4783. /************************************
  4784. Helpers
  4785. ************************************/
  4786. function extend(a, b) {
  4787. for (var i in b) {
  4788. if (b.hasOwnProperty(i)) {
  4789. a[i] = b[i];
  4790. }
  4791. }
  4792. return a;
  4793. }
  4794. function absRound(number) {
  4795. if (number < 0) {
  4796. return Math.ceil(number);
  4797. } else {
  4798. return Math.floor(number);
  4799. }
  4800. }
  4801. // left zero fill a number
  4802. // see http://jsperf.com/left-zero-filling for performance comparison
  4803. function leftZeroFill(number, targetLength) {
  4804. var output = number + '';
  4805. while (output.length < targetLength) {
  4806. output = '0' + output;
  4807. }
  4808. return output;
  4809. }
  4810. // helper function for _.addTime and _.subtractTime
  4811. function addOrSubtractDurationFromMoment(mom, duration, isAdding) {
  4812. var ms = duration._milliseconds,
  4813. d = duration._days,
  4814. M = duration._months,
  4815. currentDate;
  4816. if (ms) {
  4817. mom._d.setTime(+mom + ms * isAdding);
  4818. }
  4819. if (d) {
  4820. mom.date(mom.date() + d * isAdding);
  4821. }
  4822. if (M) {
  4823. currentDate = mom.date();
  4824. mom.date(1)
  4825. .month(mom.month() + M * isAdding)
  4826. .date(Math.min(currentDate, mom.daysInMonth()));
  4827. }
  4828. }
  4829. // check if is an array
  4830. function isArray(input) {
  4831. return Object.prototype.toString.call(input) === '[object Array]';
  4832. }
  4833. // compare two arrays, return the number of differences
  4834. function compareArrays(array1, array2) {
  4835. var len = Math.min(array1.length, array2.length),
  4836. lengthDiff = Math.abs(array1.length - array2.length),
  4837. diffs = 0,
  4838. i;
  4839. for (i = 0; i < len; i++) {
  4840. if (~~array1[i] !== ~~array2[i]) {
  4841. diffs++;
  4842. }
  4843. }
  4844. return diffs + lengthDiff;
  4845. }
  4846. /************************************
  4847. Languages
  4848. ************************************/
  4849. Language.prototype = {
  4850. set : function (config) {
  4851. var prop, i;
  4852. for (i in config) {
  4853. prop = config[i];
  4854. if (typeof prop === 'function') {
  4855. this[i] = prop;
  4856. } else {
  4857. this['_' + i] = prop;
  4858. }
  4859. }
  4860. },
  4861. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  4862. months : function (m) {
  4863. return this._months[m.month()];
  4864. },
  4865. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  4866. monthsShort : function (m) {
  4867. return this._monthsShort[m.month()];
  4868. },
  4869. monthsParse : function (monthName) {
  4870. var i, mom, regex, output;
  4871. if (!this._monthsParse) {
  4872. this._monthsParse = [];
  4873. }
  4874. for (i = 0; i < 12; i++) {
  4875. // make the regex if we don't have it already
  4876. if (!this._monthsParse[i]) {
  4877. mom = moment([2000, i]);
  4878. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  4879. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  4880. }
  4881. // test the regex
  4882. if (this._monthsParse[i].test(monthName)) {
  4883. return i;
  4884. }
  4885. }
  4886. },
  4887. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  4888. weekdays : function (m) {
  4889. return this._weekdays[m.day()];
  4890. },
  4891. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  4892. weekdaysShort : function (m) {
  4893. return this._weekdaysShort[m.day()];
  4894. },
  4895. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  4896. weekdaysMin : function (m) {
  4897. return this._weekdaysMin[m.day()];
  4898. },
  4899. _longDateFormat : {
  4900. LT : "h:mm A",
  4901. L : "MM/DD/YYYY",
  4902. LL : "MMMM D YYYY",
  4903. LLL : "MMMM D YYYY LT",
  4904. LLLL : "dddd, MMMM D YYYY LT"
  4905. },
  4906. longDateFormat : function (key) {
  4907. var output = this._longDateFormat[key];
  4908. if (!output && this._longDateFormat[key.toUpperCase()]) {
  4909. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  4910. return val.slice(1);
  4911. });
  4912. this._longDateFormat[key] = output;
  4913. }
  4914. return output;
  4915. },
  4916. meridiem : function (hours, minutes, isLower) {
  4917. if (hours > 11) {
  4918. return isLower ? 'pm' : 'PM';
  4919. } else {
  4920. return isLower ? 'am' : 'AM';
  4921. }
  4922. },
  4923. _calendar : {
  4924. sameDay : '[Today at] LT',
  4925. nextDay : '[Tomorrow at] LT',
  4926. nextWeek : 'dddd [at] LT',
  4927. lastDay : '[Yesterday at] LT',
  4928. lastWeek : '[last] dddd [at] LT',
  4929. sameElse : 'L'
  4930. },
  4931. calendar : function (key, mom) {
  4932. var output = this._calendar[key];
  4933. return typeof output === 'function' ? output.apply(mom) : output;
  4934. },
  4935. _relativeTime : {
  4936. future : "in %s",
  4937. past : "%s ago",
  4938. s : "a few seconds",
  4939. m : "a minute",
  4940. mm : "%d minutes",
  4941. h : "an hour",
  4942. hh : "%d hours",
  4943. d : "a day",
  4944. dd : "%d days",
  4945. M : "a month",
  4946. MM : "%d months",
  4947. y : "a year",
  4948. yy : "%d years"
  4949. },
  4950. relativeTime : function (number, withoutSuffix, string, isFuture) {
  4951. var output = this._relativeTime[string];
  4952. return (typeof output === 'function') ?
  4953. output(number, withoutSuffix, string, isFuture) :
  4954. output.replace(/%d/i, number);
  4955. },
  4956. pastFuture : function (diff, output) {
  4957. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  4958. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  4959. },
  4960. ordinal : function (number) {
  4961. return this._ordinal.replace("%d", number);
  4962. },
  4963. _ordinal : "%d",
  4964. preparse : function (string) {
  4965. return string;
  4966. },
  4967. postformat : function (string) {
  4968. return string;
  4969. },
  4970. week : function (mom) {
  4971. return weekOfYear(mom, this._week.dow, this._week.doy);
  4972. },
  4973. _week : {
  4974. dow : 0, // Sunday is the first day of the week.
  4975. doy : 6 // The week that contains Jan 1st is the first week of the year.
  4976. }
  4977. };
  4978. // Loads a language definition into the `languages` cache. The function
  4979. // takes a key and optionally values. If not in the browser and no values
  4980. // are provided, it will load the language file module. As a convenience,
  4981. // this function also returns the language values.
  4982. function loadLang(key, values) {
  4983. values.abbr = key;
  4984. if (!languages[key]) {
  4985. languages[key] = new Language();
  4986. }
  4987. languages[key].set(values);
  4988. return languages[key];
  4989. }
  4990. // Determines which language definition to use and returns it.
  4991. //
  4992. // With no parameters, it will return the global language. If you
  4993. // pass in a language key, such as 'en', it will return the
  4994. // definition for 'en', so long as 'en' has already been loaded using
  4995. // moment.lang.
  4996. function getLangDefinition(key) {
  4997. if (!key) {
  4998. return moment.fn._lang;
  4999. }
  5000. if (!languages[key] && hasModule) {
  5001. require('./lang/' + key);
  5002. }
  5003. return languages[key];
  5004. }
  5005. /************************************
  5006. Formatting
  5007. ************************************/
  5008. function removeFormattingTokens(input) {
  5009. if (input.match(/\[.*\]/)) {
  5010. return input.replace(/^\[|\]$/g, "");
  5011. }
  5012. return input.replace(/\\/g, "");
  5013. }
  5014. function makeFormatFunction(format) {
  5015. var array = format.match(formattingTokens), i, length;
  5016. for (i = 0, length = array.length; i < length; i++) {
  5017. if (formatTokenFunctions[array[i]]) {
  5018. array[i] = formatTokenFunctions[array[i]];
  5019. } else {
  5020. array[i] = removeFormattingTokens(array[i]);
  5021. }
  5022. }
  5023. return function (mom) {
  5024. var output = "";
  5025. for (i = 0; i < length; i++) {
  5026. output += typeof array[i].call === 'function' ? array[i].call(mom, format) : array[i];
  5027. }
  5028. return output;
  5029. };
  5030. }
  5031. // format date using native date object
  5032. function formatMoment(m, format) {
  5033. var i = 5;
  5034. function replaceLongDateFormatTokens(input) {
  5035. return m.lang().longDateFormat(input) || input;
  5036. }
  5037. while (i-- && localFormattingTokens.test(format)) {
  5038. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  5039. }
  5040. if (!formatFunctions[format]) {
  5041. formatFunctions[format] = makeFormatFunction(format);
  5042. }
  5043. return formatFunctions[format](m);
  5044. }
  5045. /************************************
  5046. Parsing
  5047. ************************************/
  5048. // get the regex to find the next token
  5049. function getParseRegexForToken(token) {
  5050. switch (token) {
  5051. case 'DDDD':
  5052. return parseTokenThreeDigits;
  5053. case 'YYYY':
  5054. return parseTokenFourDigits;
  5055. case 'YYYYY':
  5056. return parseTokenSixDigits;
  5057. case 'S':
  5058. case 'SS':
  5059. case 'SSS':
  5060. case 'DDD':
  5061. return parseTokenOneToThreeDigits;
  5062. case 'MMM':
  5063. case 'MMMM':
  5064. case 'dd':
  5065. case 'ddd':
  5066. case 'dddd':
  5067. case 'a':
  5068. case 'A':
  5069. return parseTokenWord;
  5070. case 'X':
  5071. return parseTokenTimestampMs;
  5072. case 'Z':
  5073. case 'ZZ':
  5074. return parseTokenTimezone;
  5075. case 'T':
  5076. return parseTokenT;
  5077. case 'MM':
  5078. case 'DD':
  5079. case 'YY':
  5080. case 'HH':
  5081. case 'hh':
  5082. case 'mm':
  5083. case 'ss':
  5084. case 'M':
  5085. case 'D':
  5086. case 'd':
  5087. case 'H':
  5088. case 'h':
  5089. case 'm':
  5090. case 's':
  5091. return parseTokenOneOrTwoDigits;
  5092. default :
  5093. return new RegExp(token.replace('\\', ''));
  5094. }
  5095. }
  5096. // function to convert string input to date
  5097. function addTimeToArrayFromToken(token, input, config) {
  5098. var a, b,
  5099. datePartArray = config._a;
  5100. switch (token) {
  5101. // MONTH
  5102. case 'M' : // fall through to MM
  5103. case 'MM' :
  5104. datePartArray[1] = (input == null) ? 0 : ~~input - 1;
  5105. break;
  5106. case 'MMM' : // fall through to MMMM
  5107. case 'MMMM' :
  5108. a = getLangDefinition(config._l).monthsParse(input);
  5109. // if we didn't find a month name, mark the date as invalid.
  5110. if (a != null) {
  5111. datePartArray[1] = a;
  5112. } else {
  5113. config._isValid = false;
  5114. }
  5115. break;
  5116. // DAY OF MONTH
  5117. case 'D' : // fall through to DDDD
  5118. case 'DD' : // fall through to DDDD
  5119. case 'DDD' : // fall through to DDDD
  5120. case 'DDDD' :
  5121. if (input != null) {
  5122. datePartArray[2] = ~~input;
  5123. }
  5124. break;
  5125. // YEAR
  5126. case 'YY' :
  5127. datePartArray[0] = ~~input + (~~input > 68 ? 1900 : 2000);
  5128. break;
  5129. case 'YYYY' :
  5130. case 'YYYYY' :
  5131. datePartArray[0] = ~~input;
  5132. break;
  5133. // AM / PM
  5134. case 'a' : // fall through to A
  5135. case 'A' :
  5136. config._isPm = ((input + '').toLowerCase() === 'pm');
  5137. break;
  5138. // 24 HOUR
  5139. case 'H' : // fall through to hh
  5140. case 'HH' : // fall through to hh
  5141. case 'h' : // fall through to hh
  5142. case 'hh' :
  5143. datePartArray[3] = ~~input;
  5144. break;
  5145. // MINUTE
  5146. case 'm' : // fall through to mm
  5147. case 'mm' :
  5148. datePartArray[4] = ~~input;
  5149. break;
  5150. // SECOND
  5151. case 's' : // fall through to ss
  5152. case 'ss' :
  5153. datePartArray[5] = ~~input;
  5154. break;
  5155. // MILLISECOND
  5156. case 'S' :
  5157. case 'SS' :
  5158. case 'SSS' :
  5159. datePartArray[6] = ~~ (('0.' + input) * 1000);
  5160. break;
  5161. // UNIX TIMESTAMP WITH MS
  5162. case 'X':
  5163. config._d = new Date(parseFloat(input) * 1000);
  5164. break;
  5165. // TIMEZONE
  5166. case 'Z' : // fall through to ZZ
  5167. case 'ZZ' :
  5168. config._useUTC = true;
  5169. a = (input + '').match(parseTimezoneChunker);
  5170. if (a && a[1]) {
  5171. config._tzh = ~~a[1];
  5172. }
  5173. if (a && a[2]) {
  5174. config._tzm = ~~a[2];
  5175. }
  5176. // reverse offsets
  5177. if (a && a[0] === '+') {
  5178. config._tzh = -config._tzh;
  5179. config._tzm = -config._tzm;
  5180. }
  5181. break;
  5182. }
  5183. // if the input is null, the date is not valid
  5184. if (input == null) {
  5185. config._isValid = false;
  5186. }
  5187. }
  5188. // convert an array to a date.
  5189. // the array should mirror the parameters below
  5190. // note: all values past the year are optional and will default to the lowest possible value.
  5191. // [year, month, day , hour, minute, second, millisecond]
  5192. function dateFromArray(config) {
  5193. var i, date, input = [];
  5194. if (config._d) {
  5195. return;
  5196. }
  5197. for (i = 0; i < 7; i++) {
  5198. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  5199. }
  5200. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  5201. input[3] += config._tzh || 0;
  5202. input[4] += config._tzm || 0;
  5203. date = new Date(0);
  5204. if (config._useUTC) {
  5205. date.setUTCFullYear(input[0], input[1], input[2]);
  5206. date.setUTCHours(input[3], input[4], input[5], input[6]);
  5207. } else {
  5208. date.setFullYear(input[0], input[1], input[2]);
  5209. date.setHours(input[3], input[4], input[5], input[6]);
  5210. }
  5211. config._d = date;
  5212. }
  5213. // date from string and format string
  5214. function makeDateFromStringAndFormat(config) {
  5215. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  5216. var tokens = config._f.match(formattingTokens),
  5217. string = config._i,
  5218. i, parsedInput;
  5219. config._a = [];
  5220. for (i = 0; i < tokens.length; i++) {
  5221. parsedInput = (getParseRegexForToken(tokens[i]).exec(string) || [])[0];
  5222. if (parsedInput) {
  5223. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  5224. }
  5225. // don't parse if its not a known token
  5226. if (formatTokenFunctions[tokens[i]]) {
  5227. addTimeToArrayFromToken(tokens[i], parsedInput, config);
  5228. }
  5229. }
  5230. // handle am pm
  5231. if (config._isPm && config._a[3] < 12) {
  5232. config._a[3] += 12;
  5233. }
  5234. // if is 12 am, change hours to 0
  5235. if (config._isPm === false && config._a[3] === 12) {
  5236. config._a[3] = 0;
  5237. }
  5238. // return
  5239. dateFromArray(config);
  5240. }
  5241. // date from string and array of format strings
  5242. function makeDateFromStringAndArray(config) {
  5243. var tempConfig,
  5244. tempMoment,
  5245. bestMoment,
  5246. scoreToBeat = 99,
  5247. i,
  5248. currentDate,
  5249. currentScore;
  5250. while (config._f.length) {
  5251. tempConfig = extend({}, config);
  5252. tempConfig._f = config._f.pop();
  5253. makeDateFromStringAndFormat(tempConfig);
  5254. tempMoment = new Moment(tempConfig);
  5255. if (tempMoment.isValid()) {
  5256. bestMoment = tempMoment;
  5257. break;
  5258. }
  5259. currentScore = compareArrays(tempConfig._a, tempMoment.toArray());
  5260. if (currentScore < scoreToBeat) {
  5261. scoreToBeat = currentScore;
  5262. bestMoment = tempMoment;
  5263. }
  5264. }
  5265. extend(config, bestMoment);
  5266. }
  5267. // date from iso format
  5268. function makeDateFromString(config) {
  5269. var i,
  5270. string = config._i;
  5271. if (isoRegex.exec(string)) {
  5272. config._f = 'YYYY-MM-DDT';
  5273. for (i = 0; i < 4; i++) {
  5274. if (isoTimes[i][1].exec(string)) {
  5275. config._f += isoTimes[i][0];
  5276. break;
  5277. }
  5278. }
  5279. if (parseTokenTimezone.exec(string)) {
  5280. config._f += " Z";
  5281. }
  5282. makeDateFromStringAndFormat(config);
  5283. } else {
  5284. config._d = new Date(string);
  5285. }
  5286. }
  5287. function makeDateFromInput(config) {
  5288. var input = config._i,
  5289. matched = aspNetJsonRegex.exec(input);
  5290. if (input === undefined) {
  5291. config._d = new Date();
  5292. } else if (matched) {
  5293. config._d = new Date(+matched[1]);
  5294. } else if (typeof input === 'string') {
  5295. makeDateFromString(config);
  5296. } else if (isArray(input)) {
  5297. config._a = input.slice(0);
  5298. dateFromArray(config);
  5299. } else {
  5300. config._d = input instanceof Date ? new Date(+input) : new Date(input);
  5301. }
  5302. }
  5303. /************************************
  5304. Relative Time
  5305. ************************************/
  5306. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  5307. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  5308. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  5309. }
  5310. function relativeTime(milliseconds, withoutSuffix, lang) {
  5311. var seconds = round(Math.abs(milliseconds) / 1000),
  5312. minutes = round(seconds / 60),
  5313. hours = round(minutes / 60),
  5314. days = round(hours / 24),
  5315. years = round(days / 365),
  5316. args = seconds < 45 && ['s', seconds] ||
  5317. minutes === 1 && ['m'] ||
  5318. minutes < 45 && ['mm', minutes] ||
  5319. hours === 1 && ['h'] ||
  5320. hours < 22 && ['hh', hours] ||
  5321. days === 1 && ['d'] ||
  5322. days <= 25 && ['dd', days] ||
  5323. days <= 45 && ['M'] ||
  5324. days < 345 && ['MM', round(days / 30)] ||
  5325. years === 1 && ['y'] || ['yy', years];
  5326. args[2] = withoutSuffix;
  5327. args[3] = milliseconds > 0;
  5328. args[4] = lang;
  5329. return substituteTimeAgo.apply({}, args);
  5330. }
  5331. /************************************
  5332. Week of Year
  5333. ************************************/
  5334. // firstDayOfWeek 0 = sun, 6 = sat
  5335. // the day of the week that starts the week
  5336. // (usually sunday or monday)
  5337. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  5338. // the first week is the week that contains the first
  5339. // of this day of the week
  5340. // (eg. ISO weeks use thursday (4))
  5341. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  5342. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  5343. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day();
  5344. if (daysToDayOfWeek > end) {
  5345. daysToDayOfWeek -= 7;
  5346. }
  5347. if (daysToDayOfWeek < end - 7) {
  5348. daysToDayOfWeek += 7;
  5349. }
  5350. return Math.ceil(moment(mom).add('d', daysToDayOfWeek).dayOfYear() / 7);
  5351. }
  5352. /************************************
  5353. Top Level Functions
  5354. ************************************/
  5355. function makeMoment(config) {
  5356. var input = config._i,
  5357. format = config._f;
  5358. if (input === null || input === '') {
  5359. return null;
  5360. }
  5361. if (typeof input === 'string') {
  5362. config._i = input = getLangDefinition().preparse(input);
  5363. }
  5364. if (moment.isMoment(input)) {
  5365. config = extend({}, input);
  5366. config._d = new Date(+input._d);
  5367. } else if (format) {
  5368. if (isArray(format)) {
  5369. makeDateFromStringAndArray(config);
  5370. } else {
  5371. makeDateFromStringAndFormat(config);
  5372. }
  5373. } else {
  5374. makeDateFromInput(config);
  5375. }
  5376. return new Moment(config);
  5377. }
  5378. moment = function (input, format, lang) {
  5379. return makeMoment({
  5380. _i : input,
  5381. _f : format,
  5382. _l : lang,
  5383. _isUTC : false
  5384. });
  5385. };
  5386. // creating with utc
  5387. moment.utc = function (input, format, lang) {
  5388. return makeMoment({
  5389. _useUTC : true,
  5390. _isUTC : true,
  5391. _l : lang,
  5392. _i : input,
  5393. _f : format
  5394. });
  5395. };
  5396. // creating with unix timestamp (in seconds)
  5397. moment.unix = function (input) {
  5398. return moment(input * 1000);
  5399. };
  5400. // duration
  5401. moment.duration = function (input, key) {
  5402. var isDuration = moment.isDuration(input),
  5403. isNumber = (typeof input === 'number'),
  5404. duration = (isDuration ? input._data : (isNumber ? {} : input)),
  5405. ret;
  5406. if (isNumber) {
  5407. if (key) {
  5408. duration[key] = input;
  5409. } else {
  5410. duration.milliseconds = input;
  5411. }
  5412. }
  5413. ret = new Duration(duration);
  5414. if (isDuration && input.hasOwnProperty('_lang')) {
  5415. ret._lang = input._lang;
  5416. }
  5417. return ret;
  5418. };
  5419. // version number
  5420. moment.version = VERSION;
  5421. // default format
  5422. moment.defaultFormat = isoFormat;
  5423. // This function will load languages and then set the global language. If
  5424. // no arguments are passed in, it will simply return the current global
  5425. // language key.
  5426. moment.lang = function (key, values) {
  5427. var i;
  5428. if (!key) {
  5429. return moment.fn._lang._abbr;
  5430. }
  5431. if (values) {
  5432. loadLang(key, values);
  5433. } else if (!languages[key]) {
  5434. getLangDefinition(key);
  5435. }
  5436. moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  5437. };
  5438. // returns language data
  5439. moment.langData = function (key) {
  5440. if (key && key._lang && key._lang._abbr) {
  5441. key = key._lang._abbr;
  5442. }
  5443. return getLangDefinition(key);
  5444. };
  5445. // compare moment object
  5446. moment.isMoment = function (obj) {
  5447. return obj instanceof Moment;
  5448. };
  5449. // for typechecking Duration objects
  5450. moment.isDuration = function (obj) {
  5451. return obj instanceof Duration;
  5452. };
  5453. /************************************
  5454. Moment Prototype
  5455. ************************************/
  5456. moment.fn = Moment.prototype = {
  5457. clone : function () {
  5458. return moment(this);
  5459. },
  5460. valueOf : function () {
  5461. return +this._d;
  5462. },
  5463. unix : function () {
  5464. return Math.floor(+this._d / 1000);
  5465. },
  5466. toString : function () {
  5467. return this.format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  5468. },
  5469. toDate : function () {
  5470. return this._d;
  5471. },
  5472. toJSON : function () {
  5473. return moment.utc(this).format('YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  5474. },
  5475. toArray : function () {
  5476. var m = this;
  5477. return [
  5478. m.year(),
  5479. m.month(),
  5480. m.date(),
  5481. m.hours(),
  5482. m.minutes(),
  5483. m.seconds(),
  5484. m.milliseconds()
  5485. ];
  5486. },
  5487. isValid : function () {
  5488. if (this._isValid == null) {
  5489. if (this._a) {
  5490. this._isValid = !compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray());
  5491. } else {
  5492. this._isValid = !isNaN(this._d.getTime());
  5493. }
  5494. }
  5495. return !!this._isValid;
  5496. },
  5497. utc : function () {
  5498. this._isUTC = true;
  5499. return this;
  5500. },
  5501. local : function () {
  5502. this._isUTC = false;
  5503. return this;
  5504. },
  5505. format : function (inputString) {
  5506. var output = formatMoment(this, inputString || moment.defaultFormat);
  5507. return this.lang().postformat(output);
  5508. },
  5509. add : function (input, val) {
  5510. var dur;
  5511. // switch args to support add('s', 1) and add(1, 's')
  5512. if (typeof input === 'string') {
  5513. dur = moment.duration(+val, input);
  5514. } else {
  5515. dur = moment.duration(input, val);
  5516. }
  5517. addOrSubtractDurationFromMoment(this, dur, 1);
  5518. return this;
  5519. },
  5520. subtract : function (input, val) {
  5521. var dur;
  5522. // switch args to support subtract('s', 1) and subtract(1, 's')
  5523. if (typeof input === 'string') {
  5524. dur = moment.duration(+val, input);
  5525. } else {
  5526. dur = moment.duration(input, val);
  5527. }
  5528. addOrSubtractDurationFromMoment(this, dur, -1);
  5529. return this;
  5530. },
  5531. diff : function (input, units, asFloat) {
  5532. var that = this._isUTC ? moment(input).utc() : moment(input).local(),
  5533. zoneDiff = (this.zone() - that.zone()) * 6e4,
  5534. diff, output;
  5535. if (units) {
  5536. // standardize on singular form
  5537. units = units.replace(/s$/, '');
  5538. }
  5539. if (units === 'year' || units === 'month') {
  5540. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  5541. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  5542. output += ((this - moment(this).startOf('month')) - (that - moment(that).startOf('month'))) / diff;
  5543. if (units === 'year') {
  5544. output = output / 12;
  5545. }
  5546. } else {
  5547. diff = (this - that) - zoneDiff;
  5548. output = units === 'second' ? diff / 1e3 : // 1000
  5549. units === 'minute' ? diff / 6e4 : // 1000 * 60
  5550. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  5551. units === 'day' ? diff / 864e5 : // 1000 * 60 * 60 * 24
  5552. units === 'week' ? diff / 6048e5 : // 1000 * 60 * 60 * 24 * 7
  5553. diff;
  5554. }
  5555. return asFloat ? output : absRound(output);
  5556. },
  5557. from : function (time, withoutSuffix) {
  5558. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  5559. },
  5560. fromNow : function (withoutSuffix) {
  5561. return this.from(moment(), withoutSuffix);
  5562. },
  5563. calendar : function () {
  5564. var diff = this.diff(moment().startOf('day'), 'days', true),
  5565. format = diff < -6 ? 'sameElse' :
  5566. diff < -1 ? 'lastWeek' :
  5567. diff < 0 ? 'lastDay' :
  5568. diff < 1 ? 'sameDay' :
  5569. diff < 2 ? 'nextDay' :
  5570. diff < 7 ? 'nextWeek' : 'sameElse';
  5571. return this.format(this.lang().calendar(format, this));
  5572. },
  5573. isLeapYear : function () {
  5574. var year = this.year();
  5575. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  5576. },
  5577. isDST : function () {
  5578. return (this.zone() < moment([this.year()]).zone() ||
  5579. this.zone() < moment([this.year(), 5]).zone());
  5580. },
  5581. day : function (input) {
  5582. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  5583. return input == null ? day :
  5584. this.add({ d : input - day });
  5585. },
  5586. startOf: function (units) {
  5587. units = units.replace(/s$/, '');
  5588. // the following switch intentionally omits break keywords
  5589. // to utilize falling through the cases.
  5590. switch (units) {
  5591. case 'year':
  5592. this.month(0);
  5593. /* falls through */
  5594. case 'month':
  5595. this.date(1);
  5596. /* falls through */
  5597. case 'week':
  5598. case 'day':
  5599. this.hours(0);
  5600. /* falls through */
  5601. case 'hour':
  5602. this.minutes(0);
  5603. /* falls through */
  5604. case 'minute':
  5605. this.seconds(0);
  5606. /* falls through */
  5607. case 'second':
  5608. this.milliseconds(0);
  5609. /* falls through */
  5610. }
  5611. // weeks are a special case
  5612. if (units === 'week') {
  5613. this.day(0);
  5614. }
  5615. return this;
  5616. },
  5617. endOf: function (units) {
  5618. return this.startOf(units).add(units.replace(/s?$/, 's'), 1).subtract('ms', 1);
  5619. },
  5620. isAfter: function (input, units) {
  5621. units = typeof units !== 'undefined' ? units : 'millisecond';
  5622. return +this.clone().startOf(units) > +moment(input).startOf(units);
  5623. },
  5624. isBefore: function (input, units) {
  5625. units = typeof units !== 'undefined' ? units : 'millisecond';
  5626. return +this.clone().startOf(units) < +moment(input).startOf(units);
  5627. },
  5628. isSame: function (input, units) {
  5629. units = typeof units !== 'undefined' ? units : 'millisecond';
  5630. return +this.clone().startOf(units) === +moment(input).startOf(units);
  5631. },
  5632. zone : function () {
  5633. return this._isUTC ? 0 : this._d.getTimezoneOffset();
  5634. },
  5635. daysInMonth : function () {
  5636. return moment.utc([this.year(), this.month() + 1, 0]).date();
  5637. },
  5638. dayOfYear : function (input) {
  5639. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  5640. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  5641. },
  5642. isoWeek : function (input) {
  5643. var week = weekOfYear(this, 1, 4);
  5644. return input == null ? week : this.add("d", (input - week) * 7);
  5645. },
  5646. week : function (input) {
  5647. var week = this.lang().week(this);
  5648. return input == null ? week : this.add("d", (input - week) * 7);
  5649. },
  5650. // If passed a language key, it will set the language for this
  5651. // instance. Otherwise, it will return the language configuration
  5652. // variables for this instance.
  5653. lang : function (key) {
  5654. if (key === undefined) {
  5655. return this._lang;
  5656. } else {
  5657. this._lang = getLangDefinition(key);
  5658. return this;
  5659. }
  5660. }
  5661. };
  5662. // helper for adding shortcuts
  5663. function makeGetterAndSetter(name, key) {
  5664. moment.fn[name] = moment.fn[name + 's'] = function (input) {
  5665. var utc = this._isUTC ? 'UTC' : '';
  5666. if (input != null) {
  5667. this._d['set' + utc + key](input);
  5668. return this;
  5669. } else {
  5670. return this._d['get' + utc + key]();
  5671. }
  5672. };
  5673. }
  5674. // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds)
  5675. for (i = 0; i < proxyGettersAndSetters.length; i ++) {
  5676. makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]);
  5677. }
  5678. // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear')
  5679. makeGetterAndSetter('year', 'FullYear');
  5680. // add plural methods
  5681. moment.fn.days = moment.fn.day;
  5682. moment.fn.weeks = moment.fn.week;
  5683. moment.fn.isoWeeks = moment.fn.isoWeek;
  5684. /************************************
  5685. Duration Prototype
  5686. ************************************/
  5687. moment.duration.fn = Duration.prototype = {
  5688. weeks : function () {
  5689. return absRound(this.days() / 7);
  5690. },
  5691. valueOf : function () {
  5692. return this._milliseconds +
  5693. this._days * 864e5 +
  5694. this._months * 2592e6;
  5695. },
  5696. humanize : function (withSuffix) {
  5697. var difference = +this,
  5698. output = relativeTime(difference, !withSuffix, this.lang());
  5699. if (withSuffix) {
  5700. output = this.lang().pastFuture(difference, output);
  5701. }
  5702. return this.lang().postformat(output);
  5703. },
  5704. lang : moment.fn.lang
  5705. };
  5706. function makeDurationGetter(name) {
  5707. moment.duration.fn[name] = function () {
  5708. return this._data[name];
  5709. };
  5710. }
  5711. function makeDurationAsGetter(name, factor) {
  5712. moment.duration.fn['as' + name] = function () {
  5713. return +this / factor;
  5714. };
  5715. }
  5716. for (i in unitMillisecondFactors) {
  5717. if (unitMillisecondFactors.hasOwnProperty(i)) {
  5718. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  5719. makeDurationGetter(i.toLowerCase());
  5720. }
  5721. }
  5722. makeDurationAsGetter('Weeks', 6048e5);
  5723. /************************************
  5724. Default Lang
  5725. ************************************/
  5726. // Set default language, other languages will inherit from English.
  5727. moment.lang('en', {
  5728. ordinal : function (number) {
  5729. var b = number % 10,
  5730. output = (~~ (number % 100 / 10) === 1) ? 'th' :
  5731. (b === 1) ? 'st' :
  5732. (b === 2) ? 'nd' :
  5733. (b === 3) ? 'rd' : 'th';
  5734. return number + output;
  5735. }
  5736. });
  5737. /************************************
  5738. Exposing Moment
  5739. ************************************/
  5740. // CommonJS module is defined
  5741. if (hasModule) {
  5742. module.exports = moment;
  5743. }
  5744. /*global ender:false */
  5745. if (typeof ender === 'undefined') {
  5746. // here, `this` means `window` in the browser, or `global` on the server
  5747. // add `moment` as a global object via a string identifier,
  5748. // for Closure Compiler "advanced" mode
  5749. this['moment'] = moment;
  5750. }
  5751. /*global define:false */
  5752. if (typeof define === "function" && define.amd) {
  5753. define("moment", [], function () {
  5754. return moment;
  5755. });
  5756. }
  5757. }).call(this);
  5758. })()
  5759. },{}]},{},[1])(1)
  5760. });
  5761. ;