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.

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