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.

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