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.

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