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.

6638 lines
203 KiB

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