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.

12795 lines
383 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version 0.1.0-SNAPSHOT
  8. * @date 2013-06-18
  9. *
  10. * @license
  11. * Copyright (C) 2011-2013 Almende B.V, http://almende.com
  12. *
  13. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  14. * use this file except in compliance with the License. You may obtain a copy
  15. * of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing, software
  20. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  21. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  22. * License for the specific language governing permissions and limitations under
  23. * the License.
  24. */
  25. (function(e){if("function"==typeof bootstrap)bootstrap("vis",e);else if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else if("undefined"!=typeof ses){if(!ses.ok())return;ses.makeVis=e}else"undefined"!=typeof window?window.vis=e():global.vis=e()})(function(){var define,ses,bootstrap,module,exports;
  26. return (function(e,t,n){function i(n,s){if(!t[n]){if(!e[n]){var o=typeof require=="function"&&require;if(!s&&o)return o(n,!0);if(r)return r(n,!0);throw new Error("Cannot find module '"+n+"'")}var u=t[n]={exports:{}};e[n][0].call(u.exports,function(t){var r=e[n][1][t];return i(r?r:t)},u,u.exports)}return t[n].exports}var r=typeof require=="function"&&require;for(var s=0;s<n.length;s++)i(n[s]);return i})({1:[function(require,module,exports){
  27. (function(){/**
  28. * vis.js module imports
  29. */
  30. var moment = require('moment');
  31. /**
  32. * utility functions
  33. */
  34. var util = {};
  35. /**
  36. * Test whether given object is a number
  37. * @param {*} object
  38. * @return {Boolean} isNumber
  39. */
  40. util.isNumber = function isNumber(object) {
  41. return (object instanceof Number || typeof object == 'number');
  42. };
  43. /**
  44. * Test whether given object is a string
  45. * @param {*} object
  46. * @return {Boolean} isString
  47. */
  48. util.isString = function isString(object) {
  49. return (object instanceof String || typeof object == 'string');
  50. };
  51. /**
  52. * Test whether given object is a Date, or a String containing a Date
  53. * @param {Date | String} object
  54. * @return {Boolean} isDate
  55. */
  56. util.isDate = function isDate(object) {
  57. if (object instanceof Date) {
  58. return true;
  59. }
  60. else if (util.isString(object)) {
  61. // test whether this string contains a date
  62. var match = ASPDateRegex.exec(object);
  63. if (match) {
  64. return true;
  65. }
  66. else if (!isNaN(Date.parse(object))) {
  67. return true;
  68. }
  69. }
  70. return false;
  71. };
  72. /**
  73. * Test whether given object is an instance of google.visualization.DataTable
  74. * @param {*} object
  75. * @return {Boolean} isDataTable
  76. */
  77. util.isDataTable = function isDataTable(object) {
  78. return (typeof (google) !== 'undefined') &&
  79. (google.visualization) &&
  80. (google.visualization.DataTable) &&
  81. (object instanceof google.visualization.DataTable);
  82. };
  83. /**
  84. * Create a semi UUID
  85. * source: http://stackoverflow.com/a/105074/1262753
  86. * @return {String} uuid
  87. */
  88. util.randomUUID = function randomUUID () {
  89. var S4 = function () {
  90. return Math.floor(
  91. Math.random() * 0x10000 /* 65536 */
  92. ).toString(16);
  93. };
  94. return (
  95. S4() + S4() + '-' +
  96. S4() + '-' +
  97. S4() + '-' +
  98. S4() + '-' +
  99. S4() + S4() + S4()
  100. );
  101. };
  102. /**
  103. * Extend object a with the properties of object b or a series of objects
  104. * Only properties with defined values are copied
  105. * @param {Object} a
  106. * @param {... Object} b
  107. * @return {Object} a
  108. */
  109. util.extend = function (a, b) {
  110. for (var i = 1, len = arguments.length; i < len; i++) {
  111. var other = arguments[i];
  112. for (var prop in other) {
  113. if (other.hasOwnProperty(prop) && other[prop] !== undefined) {
  114. a[prop] = other[prop];
  115. }
  116. }
  117. }
  118. return a;
  119. };
  120. /**
  121. * Cast an object to another type
  122. * @param {Boolean | Number | String | Date | Moment | Null | undefined} object
  123. * @param {String | undefined} type Name of the type. Available types:
  124. * 'Boolean', 'Number', 'String',
  125. * 'Date', 'Moment', ISODate', 'ASPDate'.
  126. * @return {*} object
  127. * @throws Error
  128. */
  129. util.cast = function cast(object, type) {
  130. var match;
  131. if (object === undefined) {
  132. return undefined;
  133. }
  134. if (object === null) {
  135. return null;
  136. }
  137. if (!type) {
  138. return object;
  139. }
  140. if (!(typeof type === 'string') && !(type instanceof String)) {
  141. throw new Error('Type must be a string');
  142. }
  143. //noinspection FallthroughInSwitchStatementJS
  144. switch (type) {
  145. case 'boolean':
  146. case 'Boolean':
  147. return Boolean(object);
  148. case 'number':
  149. case 'Number':
  150. return Number(object);
  151. case 'string':
  152. case 'String':
  153. return String(object);
  154. case 'Date':
  155. if (util.isNumber(object)) {
  156. return new Date(object);
  157. }
  158. if (object instanceof Date) {
  159. return new Date(object.valueOf());
  160. }
  161. else if (moment.isMoment(object)) {
  162. return new Date(object.valueOf());
  163. }
  164. if (util.isString(object)) {
  165. // parse ASP.Net Date pattern,
  166. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  167. // code from http://momentjs.com/
  168. match = ASPDateRegex.exec(object);
  169. if (match) {
  170. return new Date(Number(match[1])); // parse number
  171. }
  172. else {
  173. return moment(object).toDate(); // parse string
  174. }
  175. }
  176. else {
  177. throw new Error(
  178. 'Cannot cast object of type ' + util.getType(object) +
  179. ' to type Date');
  180. }
  181. case 'Moment':
  182. if (util.isNumber(object)) {
  183. return moment(object);
  184. }
  185. if (object instanceof Date) {
  186. return moment(object.valueOf());
  187. }
  188. else if (moment.isMoment(object)) {
  189. return moment.clone();
  190. }
  191. if (util.isString(object)) {
  192. // parse ASP.Net Date pattern,
  193. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  194. // code from http://momentjs.com/
  195. match = ASPDateRegex.exec(object);
  196. if (match) {
  197. return moment(Number(match[1])); // parse number
  198. }
  199. else {
  200. return moment(object); // parse string
  201. }
  202. }
  203. else {
  204. throw new Error(
  205. 'Cannot cast object of type ' + util.getType(object) +
  206. ' to type Date');
  207. }
  208. case 'ISODate':
  209. if (object instanceof Date) {
  210. return object.toISOString();
  211. }
  212. else if (moment.isMoment(object)) {
  213. return object.toDate().toISOString();
  214. }
  215. else if (util.isNumber(object) || util.isString(object)) {
  216. return moment(object).toDate().toISOString();
  217. }
  218. else {
  219. throw new Error(
  220. 'Cannot cast object of type ' + util.getType(object) +
  221. ' to type ISODate');
  222. }
  223. case 'ASPDate':
  224. if (object instanceof Date) {
  225. return '/Date(' + object.valueOf() + ')/';
  226. }
  227. else if (util.isNumber(object) || util.isString(object)) {
  228. return '/Date(' + moment(object).valueOf() + ')/';
  229. }
  230. else {
  231. throw new Error(
  232. 'Cannot cast object of type ' + util.getType(object) +
  233. ' to type ASPDate');
  234. }
  235. default:
  236. throw new Error('Cannot cast object of type ' + util.getType(object) +
  237. ' to type "' + type + '"');
  238. }
  239. };
  240. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  241. /**
  242. * Get the type of an object, for example util.getType([]) returns 'Array'
  243. * @param {*} object
  244. * @return {String} type
  245. */
  246. util.getType = function getType(object) {
  247. var type = typeof object;
  248. if (type == 'object') {
  249. if (object == null) {
  250. return 'null';
  251. }
  252. if (object instanceof Boolean) {
  253. return 'Boolean';
  254. }
  255. if (object instanceof Number) {
  256. return 'Number';
  257. }
  258. if (object instanceof String) {
  259. return 'String';
  260. }
  261. if (object instanceof Array) {
  262. return 'Array';
  263. }
  264. if (object instanceof Date) {
  265. return 'Date';
  266. }
  267. return 'Object';
  268. }
  269. else if (type == 'number') {
  270. return 'Number';
  271. }
  272. else if (type == 'boolean') {
  273. return 'Boolean';
  274. }
  275. else if (type == 'string') {
  276. return 'String';
  277. }
  278. return type;
  279. };
  280. /**
  281. * Retrieve the absolute left value of a DOM element
  282. * @param {Element} elem A dom element, for example a div
  283. * @return {number} left The absolute left position of this element
  284. * in the browser page.
  285. */
  286. util.getAbsoluteLeft = function getAbsoluteLeft (elem) {
  287. var doc = document.documentElement;
  288. var body = document.body;
  289. var left = elem.offsetLeft;
  290. var e = elem.offsetParent;
  291. while (e != null && e != body && e != doc) {
  292. left += e.offsetLeft;
  293. left -= e.scrollLeft;
  294. e = e.offsetParent;
  295. }
  296. return left;
  297. };
  298. /**
  299. * Retrieve the absolute top value of a DOM element
  300. * @param {Element} elem A dom element, for example a div
  301. * @return {number} top The absolute top position of this element
  302. * in the browser page.
  303. */
  304. util.getAbsoluteTop = function getAbsoluteTop (elem) {
  305. var doc = document.documentElement;
  306. var body = document.body;
  307. var top = elem.offsetTop;
  308. var e = elem.offsetParent;
  309. while (e != null && e != body && e != doc) {
  310. top += e.offsetTop;
  311. top -= e.scrollTop;
  312. e = e.offsetParent;
  313. }
  314. return top;
  315. };
  316. /**
  317. * Get the absolute, vertical mouse position from an event.
  318. * @param {Event} event
  319. * @return {Number} pageY
  320. */
  321. util.getPageY = function getPageY (event) {
  322. if ('pageY' in event) {
  323. return event.pageY;
  324. }
  325. else {
  326. var clientY;
  327. if (('targetTouches' in event) && event.targetTouches.length) {
  328. clientY = event.targetTouches[0].clientY;
  329. }
  330. else {
  331. clientY = event.clientY;
  332. }
  333. var doc = document.documentElement;
  334. var body = document.body;
  335. return clientY +
  336. ( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
  337. ( doc && doc.clientTop || body && body.clientTop || 0 );
  338. }
  339. };
  340. /**
  341. * Get the absolute, horizontal mouse position from an event.
  342. * @param {Event} event
  343. * @return {Number} pageX
  344. */
  345. util.getPageX = function getPageX (event) {
  346. if ('pageY' in event) {
  347. return event.pageX;
  348. }
  349. else {
  350. var clientX;
  351. if (('targetTouches' in event) && event.targetTouches.length) {
  352. clientX = event.targetTouches[0].clientX;
  353. }
  354. else {
  355. clientX = event.clientX;
  356. }
  357. var doc = document.documentElement;
  358. var body = document.body;
  359. return clientX +
  360. ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
  361. ( doc && doc.clientLeft || body && body.clientLeft || 0 );
  362. }
  363. };
  364. /**
  365. * add a className to the given elements style
  366. * @param {Element} elem
  367. * @param {String} className
  368. */
  369. util.addClassName = function addClassName(elem, className) {
  370. var classes = elem.className.split(' ');
  371. if (classes.indexOf(className) == -1) {
  372. classes.push(className); // add the class to the array
  373. elem.className = classes.join(' ');
  374. }
  375. };
  376. /**
  377. * add a className to the given elements style
  378. * @param {Element} elem
  379. * @param {String} className
  380. */
  381. util.removeClassName = function removeClassname(elem, className) {
  382. var classes = elem.className.split(' ');
  383. var index = classes.indexOf(className);
  384. if (index != -1) {
  385. classes.splice(index, 1); // remove the class from the array
  386. elem.className = classes.join(' ');
  387. }
  388. };
  389. /**
  390. * For each method for both arrays and objects.
  391. * In case of an array, the built-in Array.forEach() is applied.
  392. * In case of an Object, the method loops over all properties of the object.
  393. * @param {Object | Array} object An Object or Array
  394. * @param {function} callback Callback method, called for each item in
  395. * the object or array with three parameters:
  396. * callback(value, index, object)
  397. */
  398. util.forEach = function forEach (object, callback) {
  399. var i,
  400. len;
  401. if (object instanceof Array) {
  402. // array
  403. for (i = 0, len = object.length; i < len; i++) {
  404. callback(object[i], i, object);
  405. }
  406. }
  407. else {
  408. // object
  409. for (i in object) {
  410. if (object.hasOwnProperty(i)) {
  411. callback(object[i], i, object);
  412. }
  413. }
  414. }
  415. };
  416. /**
  417. * Update a property in an object
  418. * @param {Object} object
  419. * @param {String} key
  420. * @param {*} value
  421. * @return {Boolean} changed
  422. */
  423. util.updateProperty = function updateProp (object, key, value) {
  424. if (object[key] !== value) {
  425. object[key] = value;
  426. return true;
  427. }
  428. else {
  429. return false;
  430. }
  431. };
  432. /**
  433. * Add and event listener. Works for all browsers
  434. * @param {Element} element An html element
  435. * @param {string} action The action, for example "click",
  436. * without the prefix "on"
  437. * @param {function} listener The callback function to be executed
  438. * @param {boolean} [useCapture]
  439. */
  440. util.addEventListener = function addEventListener(element, action, listener, useCapture) {
  441. if (element.addEventListener) {
  442. if (useCapture === undefined)
  443. useCapture = false;
  444. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  445. action = "DOMMouseScroll"; // For Firefox
  446. }
  447. element.addEventListener(action, listener, useCapture);
  448. } else {
  449. element.attachEvent("on" + action, listener); // IE browsers
  450. }
  451. };
  452. /**
  453. * Remove an event listener from an element
  454. * @param {Element} element An html dom element
  455. * @param {string} action The name of the event, for example "mousedown"
  456. * @param {function} listener The listener function
  457. * @param {boolean} [useCapture]
  458. */
  459. util.removeEventListener = function removeEventListener(element, action, listener, useCapture) {
  460. if (element.removeEventListener) {
  461. // non-IE browsers
  462. if (useCapture === undefined)
  463. useCapture = false;
  464. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  465. action = "DOMMouseScroll"; // For Firefox
  466. }
  467. element.removeEventListener(action, listener, useCapture);
  468. } else {
  469. // IE browsers
  470. element.detachEvent("on" + action, listener);
  471. }
  472. };
  473. /**
  474. * Get HTML element which is the target of the event
  475. * @param {Event} event
  476. * @return {Element} target element
  477. */
  478. util.getTarget = function getTarget(event) {
  479. // code from http://www.quirksmode.org/js/events_properties.html
  480. if (!event) {
  481. event = window.event;
  482. }
  483. var target;
  484. if (event.target) {
  485. target = event.target;
  486. }
  487. else if (event.srcElement) {
  488. target = event.srcElement;
  489. }
  490. if (target.nodeType != undefined && target.nodeType == 3) {
  491. // defeat Safari bug
  492. target = target.parentNode;
  493. }
  494. return target;
  495. };
  496. /**
  497. * Stop event propagation
  498. */
  499. util.stopPropagation = function stopPropagation(event) {
  500. if (!event)
  501. event = window.event;
  502. if (event.stopPropagation) {
  503. event.stopPropagation(); // non-IE browsers
  504. }
  505. else {
  506. event.cancelBubble = true; // IE browsers
  507. }
  508. };
  509. /**
  510. * Cancels the event if it is cancelable, without stopping further propagation of the event.
  511. */
  512. util.preventDefault = function preventDefault (event) {
  513. if (!event)
  514. event = window.event;
  515. if (event.preventDefault) {
  516. event.preventDefault(); // non-IE browsers
  517. }
  518. else {
  519. event.returnValue = false; // IE browsers
  520. }
  521. };
  522. util.option = {};
  523. /**
  524. * Cast a value as boolean
  525. * @param {Boolean | function | undefined} value
  526. * @param {Boolean} [defaultValue]
  527. * @returns {Boolean} bool
  528. */
  529. util.option.asBoolean = function (value, defaultValue) {
  530. if (typeof value == 'function') {
  531. value = value();
  532. }
  533. if (value != null) {
  534. return (value != false);
  535. }
  536. return defaultValue || null;
  537. };
  538. /**
  539. * Cast a value as number
  540. * @param {Boolean | function | undefined} value
  541. * @param {Number} [defaultValue]
  542. * @returns {Number} number
  543. */
  544. util.option.asNumber = function (value, defaultValue) {
  545. if (typeof value == 'function') {
  546. value = value();
  547. }
  548. if (value != null) {
  549. return Number(value) || defaultValue || null;
  550. }
  551. return defaultValue || null;
  552. };
  553. /**
  554. * Cast a value as string
  555. * @param {String | function | undefined} value
  556. * @param {String} [defaultValue]
  557. * @returns {String} str
  558. */
  559. util.option.asString = function (value, defaultValue) {
  560. if (typeof value == 'function') {
  561. value = value();
  562. }
  563. if (value != null) {
  564. return String(value);
  565. }
  566. return defaultValue || null;
  567. };
  568. /**
  569. * Cast a size or location in pixels or a percentage
  570. * @param {String | Number | function | undefined} value
  571. * @param {String} [defaultValue]
  572. * @returns {String} size
  573. */
  574. util.option.asSize = function (value, defaultValue) {
  575. if (typeof value == 'function') {
  576. value = value();
  577. }
  578. if (util.isString(value)) {
  579. return value;
  580. }
  581. else if (util.isNumber(value)) {
  582. return value + 'px';
  583. }
  584. else {
  585. return defaultValue || null;
  586. }
  587. };
  588. /**
  589. * Cast a value as DOM element
  590. * @param {HTMLElement | function | undefined} value
  591. * @param {HTMLElement} [defaultValue]
  592. * @returns {HTMLElement | null} dom
  593. */
  594. util.option.asElement = function (value, defaultValue) {
  595. if (typeof value == 'function') {
  596. value = value();
  597. }
  598. return value || defaultValue || null;
  599. };
  600. /**
  601. * load css from text
  602. * @param {String} css Text containing css
  603. */
  604. util.loadCss = function (css) {
  605. if (typeof document === 'undefined') {
  606. return;
  607. }
  608. // get the script location, and built the css file name from the js file name
  609. // http://stackoverflow.com/a/2161748/1262753
  610. // var scripts = document.getElementsByTagName('script');
  611. // var jsFile = scripts[scripts.length-1].src.split('?')[0];
  612. // var cssFile = jsFile.substring(0, jsFile.length - 2) + 'css';
  613. // inject css
  614. // http://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript
  615. var style = document.createElement('style');
  616. style.type = 'text/css';
  617. if (style.styleSheet){
  618. style.styleSheet.cssText = css;
  619. } else {
  620. style.appendChild(document.createTextNode(css));
  621. }
  622. document.getElementsByTagName('head')[0].appendChild(style);
  623. };
  624. // Internet Explorer 8 and older does not support Array.indexOf, so we define
  625. // it here in that case.
  626. // http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
  627. if(!Array.prototype.indexOf) {
  628. Array.prototype.indexOf = function(obj){
  629. for(var i = 0; i < this.length; i++){
  630. if(this[i] == obj){
  631. return i;
  632. }
  633. }
  634. return -1;
  635. };
  636. try {
  637. console.log("Warning: Ancient browser detected. Please update your browser");
  638. }
  639. catch (err) {
  640. }
  641. }
  642. // Internet Explorer 8 and older does not support Array.forEach, so we define
  643. // it here in that case.
  644. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
  645. if (!Array.prototype.forEach) {
  646. Array.prototype.forEach = function(fn, scope) {
  647. for(var i = 0, len = this.length; i < len; ++i) {
  648. fn.call(scope || this, this[i], i, this);
  649. }
  650. }
  651. }
  652. // Internet Explorer 8 and older does not support Array.map, so we define it
  653. // here in that case.
  654. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
  655. // Production steps of ECMA-262, Edition 5, 15.4.4.19
  656. // Reference: http://es5.github.com/#x15.4.4.19
  657. if (!Array.prototype.map) {
  658. Array.prototype.map = function(callback, thisArg) {
  659. var T, A, k;
  660. if (this == null) {
  661. throw new TypeError(" this is null or not defined");
  662. }
  663. // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
  664. var O = Object(this);
  665. // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
  666. // 3. Let len be ToUint32(lenValue).
  667. var len = O.length >>> 0;
  668. // 4. If IsCallable(callback) is false, throw a TypeError exception.
  669. // See: http://es5.github.com/#x9.11
  670. if (typeof callback !== "function") {
  671. throw new TypeError(callback + " is not a function");
  672. }
  673. // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
  674. if (thisArg) {
  675. T = thisArg;
  676. }
  677. // 6. Let A be a new array created as if by the expression new Array(len) where Array is
  678. // the standard built-in constructor with that name and len is the value of len.
  679. A = new Array(len);
  680. // 7. Let k be 0
  681. k = 0;
  682. // 8. Repeat, while k < len
  683. while(k < len) {
  684. var kValue, mappedValue;
  685. // a. Let Pk be ToString(k).
  686. // This is implicit for LHS operands of the in operator
  687. // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
  688. // This step can be combined with c
  689. // c. If kPresent is true, then
  690. if (k in O) {
  691. // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
  692. kValue = O[ k ];
  693. // ii. Let mappedValue be the result of calling the Call internal method of callback
  694. // with T as the this value and argument list containing kValue, k, and O.
  695. mappedValue = callback.call(T, kValue, k, O);
  696. // iii. Call the DefineOwnProperty internal method of A with arguments
  697. // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
  698. // and false.
  699. // In browsers that support Object.defineProperty, use the following:
  700. // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });
  701. // For best browser support, use the following:
  702. A[ k ] = mappedValue;
  703. }
  704. // d. Increase k by 1.
  705. k++;
  706. }
  707. // 9. return A
  708. return A;
  709. };
  710. }
  711. // Internet Explorer 8 and older does not support Array.filter, so we define it
  712. // here in that case.
  713. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
  714. if (!Array.prototype.filter) {
  715. Array.prototype.filter = function(fun /*, thisp */) {
  716. "use strict";
  717. if (this == null) {
  718. throw new TypeError();
  719. }
  720. var t = Object(this);
  721. var len = t.length >>> 0;
  722. if (typeof fun != "function") {
  723. throw new TypeError();
  724. }
  725. var res = [];
  726. var thisp = arguments[1];
  727. for (var i = 0; i < len; i++) {
  728. if (i in t) {
  729. var val = t[i]; // in case fun mutates this
  730. if (fun.call(thisp, val, i, t))
  731. res.push(val);
  732. }
  733. }
  734. return res;
  735. };
  736. }
  737. // Internet Explorer 8 and older does not support Object.keys, so we define it
  738. // here in that case.
  739. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys
  740. if (!Object.keys) {
  741. Object.keys = (function () {
  742. var hasOwnProperty = Object.prototype.hasOwnProperty,
  743. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  744. dontEnums = [
  745. 'toString',
  746. 'toLocaleString',
  747. 'valueOf',
  748. 'hasOwnProperty',
  749. 'isPrototypeOf',
  750. 'propertyIsEnumerable',
  751. 'constructor'
  752. ],
  753. dontEnumsLength = dontEnums.length;
  754. return function (obj) {
  755. if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
  756. throw new TypeError('Object.keys called on non-object');
  757. }
  758. var result = [];
  759. for (var prop in obj) {
  760. if (hasOwnProperty.call(obj, prop)) result.push(prop);
  761. }
  762. if (hasDontEnumBug) {
  763. for (var i=0; i < dontEnumsLength; i++) {
  764. if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
  765. }
  766. }
  767. return result;
  768. }
  769. })()
  770. }
  771. // Internet Explorer 8 and older does not support Array.isArray,
  772. // so we define it here in that case.
  773. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray
  774. if(!Array.isArray) {
  775. Array.isArray = function (vArg) {
  776. return Object.prototype.toString.call(vArg) === "[object Array]";
  777. };
  778. }
  779. // Internet Explorer 8 and older does not support Function.bind,
  780. // so we define it here in that case.
  781. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
  782. if (!Function.prototype.bind) {
  783. Function.prototype.bind = function (oThis) {
  784. if (typeof this !== "function") {
  785. // closest thing possible to the ECMAScript 5 internal IsCallable function
  786. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  787. }
  788. var aArgs = Array.prototype.slice.call(arguments, 1),
  789. fToBind = this,
  790. fNOP = function () {},
  791. fBound = function () {
  792. return fToBind.apply(this instanceof fNOP && oThis
  793. ? this
  794. : oThis,
  795. aArgs.concat(Array.prototype.slice.call(arguments)));
  796. };
  797. fNOP.prototype = this.prototype;
  798. fBound.prototype = new fNOP();
  799. return fBound;
  800. };
  801. }
  802. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create
  803. if (!Object.create) {
  804. Object.create = function (o) {
  805. if (arguments.length > 1) {
  806. throw new Error('Object.create implementation only accepts the first parameter.');
  807. }
  808. function F() {}
  809. F.prototype = o;
  810. return new F();
  811. };
  812. }
  813. /**
  814. * Event listener (singleton)
  815. */
  816. // TODO: replace usage of the event listener for the EventBus
  817. var events = {
  818. 'listeners': [],
  819. /**
  820. * Find a single listener by its object
  821. * @param {Object} object
  822. * @return {Number} index -1 when not found
  823. */
  824. 'indexOf': function (object) {
  825. var listeners = this.listeners;
  826. for (var i = 0, iMax = this.listeners.length; i < iMax; i++) {
  827. var listener = listeners[i];
  828. if (listener && listener.object == object) {
  829. return i;
  830. }
  831. }
  832. return -1;
  833. },
  834. /**
  835. * Add an event listener
  836. * @param {Object} object
  837. * @param {String} event The name of an event, for example 'select'
  838. * @param {function} callback The callback method, called when the
  839. * event takes place
  840. */
  841. 'addListener': function (object, event, callback) {
  842. var index = this.indexOf(object);
  843. var listener = this.listeners[index];
  844. if (!listener) {
  845. listener = {
  846. 'object': object,
  847. 'events': {}
  848. };
  849. this.listeners.push(listener);
  850. }
  851. var callbacks = listener.events[event];
  852. if (!callbacks) {
  853. callbacks = [];
  854. listener.events[event] = callbacks;
  855. }
  856. // add the callback if it does not yet exist
  857. if (callbacks.indexOf(callback) == -1) {
  858. callbacks.push(callback);
  859. }
  860. },
  861. /**
  862. * Remove an event listener
  863. * @param {Object} object
  864. * @param {String} event The name of an event, for example 'select'
  865. * @param {function} callback The registered callback method
  866. */
  867. 'removeListener': function (object, event, callback) {
  868. var index = this.indexOf(object);
  869. var listener = this.listeners[index];
  870. if (listener) {
  871. var callbacks = listener.events[event];
  872. if (callbacks) {
  873. index = callbacks.indexOf(callback);
  874. if (index != -1) {
  875. callbacks.splice(index, 1);
  876. }
  877. // remove the array when empty
  878. if (callbacks.length == 0) {
  879. delete listener.events[event];
  880. }
  881. }
  882. // count the number of registered events. remove listener when empty
  883. var count = 0;
  884. var events = listener.events;
  885. for (var e in events) {
  886. if (events.hasOwnProperty(e)) {
  887. count++;
  888. }
  889. }
  890. if (count == 0) {
  891. delete this.listeners[index];
  892. }
  893. }
  894. },
  895. /**
  896. * Remove all registered event listeners
  897. */
  898. 'removeAllListeners': function () {
  899. this.listeners = [];
  900. },
  901. /**
  902. * Trigger an event. All registered event handlers will be called
  903. * @param {Object} object
  904. * @param {String} event
  905. * @param {Object} properties (optional)
  906. */
  907. 'trigger': function (object, event, properties) {
  908. var index = this.indexOf(object);
  909. var listener = this.listeners[index];
  910. if (listener) {
  911. var callbacks = listener.events[event];
  912. if (callbacks) {
  913. for (var i = 0, iMax = callbacks.length; i < iMax; i++) {
  914. callbacks[i](properties);
  915. }
  916. }
  917. }
  918. }
  919. };
  920. /**
  921. * An event bus can be used to emit events, and to subscribe to events
  922. * @constructor EventBus
  923. */
  924. function EventBus() {
  925. this.subscriptions = [];
  926. }
  927. /**
  928. * Subscribe to an event
  929. * @param {String | RegExp} event The event can be a regular expression, or
  930. * a string with wildcards, like 'server.*'.
  931. * @param {function} callback. Callback are called with three parameters:
  932. * {String} event, {*} [data], {*} [source]
  933. * @param {*} [target]
  934. * @returns {String} id A subscription id
  935. */
  936. EventBus.prototype.on = function (event, callback, target) {
  937. var regexp = (event instanceof RegExp) ?
  938. event :
  939. new RegExp(event.replace('*', '\\w+'));
  940. var subscription = {
  941. id: util.randomUUID(),
  942. event: event,
  943. regexp: regexp,
  944. callback: (typeof callback === 'function') ? callback : null,
  945. target: target
  946. };
  947. this.subscriptions.push(subscription);
  948. return subscription.id;
  949. };
  950. /**
  951. * Unsubscribe from an event
  952. * @param {String | Object} filter Filter for subscriptions to be removed
  953. * Filter can be a string containing a
  954. * subscription id, or an object containing
  955. * one or more of the fields id, event,
  956. * callback, and target.
  957. */
  958. EventBus.prototype.off = function (filter) {
  959. var i = 0;
  960. while (i < this.subscriptions.length) {
  961. var subscription = this.subscriptions[i];
  962. var match = true;
  963. if (filter instanceof Object) {
  964. // filter is an object. All fields must match
  965. for (var prop in filter) {
  966. if (filter.hasOwnProperty(prop)) {
  967. if (filter[prop] !== subscription[prop]) {
  968. match = false;
  969. }
  970. }
  971. }
  972. }
  973. else {
  974. // filter is a string, filter on id
  975. match = (subscription.id == filter);
  976. }
  977. if (match) {
  978. this.subscriptions.splice(i, 1);
  979. }
  980. else {
  981. i++;
  982. }
  983. }
  984. };
  985. /**
  986. * Emit an event
  987. * @param {String} event
  988. * @param {*} [data]
  989. * @param {*} [source]
  990. */
  991. EventBus.prototype.emit = function (event, data, source) {
  992. for (var i =0; i < this.subscriptions.length; i++) {
  993. var subscription = this.subscriptions[i];
  994. if (subscription.regexp.test(event)) {
  995. if (subscription.callback) {
  996. subscription.callback(event, data, source);
  997. }
  998. }
  999. }
  1000. };
  1001. /**
  1002. * DataSet
  1003. *
  1004. * Usage:
  1005. * var dataSet = new DataSet({
  1006. * fieldId: '_id',
  1007. * fieldTypes: {
  1008. * // ...
  1009. * }
  1010. * });
  1011. *
  1012. * dataSet.add(item);
  1013. * dataSet.add(data);
  1014. * dataSet.update(item);
  1015. * dataSet.update(data);
  1016. * dataSet.remove(id);
  1017. * dataSet.remove(ids);
  1018. * var data = dataSet.get();
  1019. * var data = dataSet.get(id);
  1020. * var data = dataSet.get(ids);
  1021. * var data = dataSet.get(ids, options, data);
  1022. * dataSet.clear();
  1023. *
  1024. * A data set can:
  1025. * - add/remove/update data
  1026. * - gives triggers upon changes in the data
  1027. * - can import/export data in various data formats
  1028. *
  1029. * @param {Object} [options] Available options:
  1030. * {String} fieldId Field name of the id in the
  1031. * items, 'id' by default.
  1032. * {Object.<String, String} fieldTypes
  1033. * A map with field names as key,
  1034. * and the field type as value.
  1035. * @constructor DataSet
  1036. */
  1037. // TODO: add a DataSet constructor DataSet(data, options)
  1038. function DataSet (options) {
  1039. this.id = util.randomUUID();
  1040. this.options = options || {};
  1041. this.data = {}; // map with data indexed by id
  1042. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  1043. this.fieldTypes = {}; // field types by field name
  1044. if (this.options.fieldTypes) {
  1045. for (var field in this.options.fieldTypes) {
  1046. if (this.options.fieldTypes.hasOwnProperty(field)) {
  1047. var value = this.options.fieldTypes[field];
  1048. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1049. this.fieldTypes[field] = 'Date';
  1050. }
  1051. else {
  1052. this.fieldTypes[field] = value;
  1053. }
  1054. }
  1055. }
  1056. }
  1057. // event subscribers
  1058. this.subscribers = {};
  1059. this.internalIds = {}; // internally generated id's
  1060. }
  1061. /**
  1062. * Subscribe to an event, add an event listener
  1063. * @param {String} event Event name. Available events: 'put', 'update',
  1064. * 'remove'
  1065. * @param {function} callback Callback method. Called with three parameters:
  1066. * {String} event
  1067. * {Object | null} params
  1068. * {String} senderId
  1069. * @param {String} [id] Optional id for the sender, used to filter
  1070. * events triggered by the sender itself.
  1071. */
  1072. DataSet.prototype.subscribe = function (event, callback, id) {
  1073. var subscribers = this.subscribers[event];
  1074. if (!subscribers) {
  1075. subscribers = [];
  1076. this.subscribers[event] = subscribers;
  1077. }
  1078. subscribers.push({
  1079. id: id ? String(id) : null,
  1080. callback: callback
  1081. });
  1082. };
  1083. /**
  1084. * Unsubscribe from an event, remove an event listener
  1085. * @param {String} event
  1086. * @param {function} callback
  1087. */
  1088. DataSet.prototype.unsubscribe = function (event, callback) {
  1089. var subscribers = this.subscribers[event];
  1090. if (subscribers) {
  1091. this.subscribers[event] = subscribers.filter(function (listener) {
  1092. return (listener.callback != callback);
  1093. });
  1094. }
  1095. };
  1096. /**
  1097. * Trigger an event
  1098. * @param {String} event
  1099. * @param {Object | null} params
  1100. * @param {String} [senderId] Optional id of the sender.
  1101. * @private
  1102. */
  1103. DataSet.prototype._trigger = function (event, params, senderId) {
  1104. if (event == '*') {
  1105. throw new Error('Cannot trigger event *');
  1106. }
  1107. var subscribers = [];
  1108. if (event in this.subscribers) {
  1109. subscribers = subscribers.concat(this.subscribers[event]);
  1110. }
  1111. if ('*' in this.subscribers) {
  1112. subscribers = subscribers.concat(this.subscribers['*']);
  1113. }
  1114. for (var i = 0; i < subscribers.length; i++) {
  1115. var subscriber = subscribers[i];
  1116. if (subscriber.callback) {
  1117. subscriber.callback(event, params, senderId || null);
  1118. }
  1119. }
  1120. };
  1121. /**
  1122. * Add data.
  1123. * Adding an item will fail when there already is an item with the same id.
  1124. * @param {Object | Array | DataTable} data
  1125. * @param {String} [senderId] Optional sender id
  1126. */
  1127. DataSet.prototype.add = function (data, senderId) {
  1128. var addedItems = [],
  1129. id,
  1130. me = this;
  1131. if (data instanceof Array) {
  1132. // Array
  1133. for (var i = 0, len = data.length; i < len; i++) {
  1134. id = me._addItem(data[i]);
  1135. addedItems.push(id);
  1136. }
  1137. }
  1138. else if (util.isDataTable(data)) {
  1139. // Google DataTable
  1140. var columns = this._getColumnNames(data);
  1141. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1142. var item = {};
  1143. for (var col = 0, cols = columns.length; col < cols; col++) {
  1144. var field = columns[col];
  1145. item[field] = data.getValue(row, col);
  1146. }
  1147. id = me._addItem(item);
  1148. addedItems.push(id);
  1149. }
  1150. }
  1151. else if (data instanceof Object) {
  1152. // Single item
  1153. id = me._addItem(data);
  1154. addedItems.push(id);
  1155. }
  1156. else {
  1157. throw new Error('Unknown dataType');
  1158. }
  1159. if (addedItems.length) {
  1160. this._trigger('add', {items: addedItems}, senderId);
  1161. }
  1162. };
  1163. /**
  1164. * Update existing items. When an item does not exist, it will be created
  1165. * @param {Object | Array | DataTable} data
  1166. * @param {String} [senderId] Optional sender id
  1167. */
  1168. DataSet.prototype.update = function (data, senderId) {
  1169. var addedItems = [],
  1170. updatedItems = [],
  1171. me = this,
  1172. fieldId = me.fieldId;
  1173. var addOrUpdate = function (item) {
  1174. var id = item[fieldId];
  1175. if (me.data[id]) {
  1176. // update item
  1177. id = me._updateItem(item);
  1178. updatedItems.push(id);
  1179. }
  1180. else {
  1181. // add new item
  1182. id = me._addItem(item);
  1183. addedItems.push(id);
  1184. }
  1185. };
  1186. if (data instanceof Array) {
  1187. // Array
  1188. for (var i = 0, len = data.length; i < len; i++) {
  1189. addOrUpdate(data[i]);
  1190. }
  1191. }
  1192. else if (util.isDataTable(data)) {
  1193. // Google DataTable
  1194. var columns = this._getColumnNames(data);
  1195. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1196. var item = {};
  1197. for (var col = 0, cols = columns.length; col < cols; col++) {
  1198. var field = columns[col];
  1199. item[field] = data.getValue(row, col);
  1200. }
  1201. addOrUpdate(item);
  1202. }
  1203. }
  1204. else if (data instanceof Object) {
  1205. // Single item
  1206. addOrUpdate(data);
  1207. }
  1208. else {
  1209. throw new Error('Unknown dataType');
  1210. }
  1211. if (addedItems.length) {
  1212. this._trigger('add', {items: addedItems}, senderId);
  1213. }
  1214. if (updatedItems.length) {
  1215. this._trigger('update', {items: updatedItems}, senderId);
  1216. }
  1217. };
  1218. /**
  1219. * Get a data item or multiple items.
  1220. *
  1221. * Usage:
  1222. *
  1223. * get()
  1224. * get(options: Object)
  1225. * get(options: Object, data: Array | DataTable)
  1226. *
  1227. * get(id: Number | String)
  1228. * get(id: Number | String, options: Object)
  1229. * get(id: Number | String, options: Object, data: Array | DataTable)
  1230. *
  1231. * get(ids: Number[] | String[])
  1232. * get(ids: Number[] | String[], options: Object)
  1233. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1234. *
  1235. * Where:
  1236. *
  1237. * {Number | String} id The id of an item
  1238. * {Number[] | String{}} ids An array with ids of items
  1239. * {Object} options An Object with options. Available options:
  1240. * {String} [type] Type of data to be returned. Can
  1241. * be 'DataTable' or 'Array' (default)
  1242. * {Object.<String, String>} [fieldTypes]
  1243. * {String[]} [fields] field names to be returned
  1244. * {function} [filter] filter items
  1245. * {String | function} [order] Order the items by
  1246. * a field name or custom sort function.
  1247. * {Array | DataTable} [data] If provided, items will be appended to this
  1248. * array or table. Required in case of Google
  1249. * DataTable.
  1250. *
  1251. * @throws Error
  1252. */
  1253. DataSet.prototype.get = function (args) {
  1254. var me = this;
  1255. // parse the arguments
  1256. var id, ids, options, data;
  1257. var firstType = util.getType(arguments[0]);
  1258. if (firstType == 'String' || firstType == 'Number') {
  1259. // get(id [, options] [, data])
  1260. id = arguments[0];
  1261. options = arguments[1];
  1262. data = arguments[2];
  1263. }
  1264. else if (firstType == 'Array') {
  1265. // get(ids [, options] [, data])
  1266. ids = arguments[0];
  1267. options = arguments[1];
  1268. data = arguments[2];
  1269. }
  1270. else {
  1271. // get([, options] [, data])
  1272. options = arguments[0];
  1273. data = arguments[1];
  1274. }
  1275. // determine the return type
  1276. var type;
  1277. if (options && options.type) {
  1278. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  1279. if (data && (type != util.getType(data))) {
  1280. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1281. 'does not correspond with specified options.type (' + options.type + ')');
  1282. }
  1283. if (type == 'DataTable' && !util.isDataTable(data)) {
  1284. throw new Error('Parameter "data" must be a DataTable ' +
  1285. 'when options.type is "DataTable"');
  1286. }
  1287. }
  1288. else if (data) {
  1289. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1290. }
  1291. else {
  1292. type = 'Array';
  1293. }
  1294. // build options
  1295. var fieldTypes = options && options.fieldTypes || this.options.fieldTypes;
  1296. var filter = options && options.filter;
  1297. var items = [], item, itemId, i, len;
  1298. // cast items
  1299. if (id != undefined) {
  1300. // return a single item
  1301. item = me._getItem(id, fieldTypes);
  1302. if (filter && !filter(item)) {
  1303. item = null;
  1304. }
  1305. }
  1306. else if (ids != undefined) {
  1307. // return a subset of items
  1308. for (i = 0, len = ids.length; i < len; i++) {
  1309. item = me._getItem(ids[i], fieldTypes);
  1310. if (!filter || filter(item)) {
  1311. items.push(item);
  1312. }
  1313. }
  1314. }
  1315. else {
  1316. // return all items
  1317. for (itemId in this.data) {
  1318. if (this.data.hasOwnProperty(itemId)) {
  1319. item = me._getItem(itemId, fieldTypes);
  1320. if (!filter || filter(item)) {
  1321. items.push(item);
  1322. }
  1323. }
  1324. }
  1325. }
  1326. // order the results
  1327. if (options && options.order && id == undefined) {
  1328. this._sort(items, options.order);
  1329. }
  1330. // filter fields of the items
  1331. if (options && options.fields) {
  1332. var fields = options.fields;
  1333. if (id != undefined) {
  1334. item = this._filterFields(item, fields);
  1335. }
  1336. else {
  1337. for (i = 0, len = items.length; i < len; i++) {
  1338. items[i] = this._filterFields(items[i], fields);
  1339. }
  1340. }
  1341. }
  1342. // return the results
  1343. if (type == 'DataTable') {
  1344. var columns = this._getColumnNames(data);
  1345. if (id != undefined) {
  1346. // append a single item to the data table
  1347. me._appendRow(data, columns, item);
  1348. }
  1349. else {
  1350. // copy the items to the provided data table
  1351. for (i = 0, len = items.length; i < len; i++) {
  1352. me._appendRow(data, columns, items[i]);
  1353. }
  1354. }
  1355. return data;
  1356. }
  1357. else {
  1358. // return an array
  1359. if (id != undefined) {
  1360. // a single item
  1361. return item;
  1362. }
  1363. else {
  1364. // multiple items
  1365. if (data) {
  1366. // copy the items to the provided array
  1367. for (i = 0, len = items.length; i < len; i++) {
  1368. data.push(items[i]);
  1369. }
  1370. return data;
  1371. }
  1372. else {
  1373. // just return our array
  1374. return items;
  1375. }
  1376. }
  1377. }
  1378. };
  1379. /**
  1380. * Get ids of all items or from a filtered set of items.
  1381. * @param {Object} [options] An Object with options. Available options:
  1382. * {function} [filter] filter items
  1383. * {String | function} [order] Order the items by
  1384. * a field name or custom sort function.
  1385. * @return {Array} ids
  1386. */
  1387. DataSet.prototype.getIds = function (options) {
  1388. var data = this.data,
  1389. filter = options && options.filter,
  1390. order = options && options.order,
  1391. fieldTypes = options && options.fieldTypes || this.options.fieldTypes,
  1392. i,
  1393. len,
  1394. id,
  1395. item,
  1396. items,
  1397. ids = [];
  1398. if (filter) {
  1399. // get filtered items
  1400. if (order) {
  1401. // create ordered list
  1402. items = [];
  1403. for (id in data) {
  1404. if (data.hasOwnProperty(id)) {
  1405. item = this._getItem(id, fieldTypes);
  1406. if (filter(item)) {
  1407. items.push(item);
  1408. }
  1409. }
  1410. }
  1411. this._sort(items, order);
  1412. for (i = 0, len = items.length; i < len; i++) {
  1413. ids[i] = items[i][this.fieldId];
  1414. }
  1415. }
  1416. else {
  1417. // create unordered list
  1418. for (id in data) {
  1419. if (data.hasOwnProperty(id)) {
  1420. item = this._getItem(id, fieldTypes);
  1421. if (filter(item)) {
  1422. ids.push(item[this.fieldId]);
  1423. }
  1424. }
  1425. }
  1426. }
  1427. }
  1428. else {
  1429. // get all items
  1430. if (order) {
  1431. // create an ordered list
  1432. items = [];
  1433. for (id in data) {
  1434. if (data.hasOwnProperty(id)) {
  1435. items.push(data[id]);
  1436. }
  1437. }
  1438. this._sort(items, order);
  1439. for (i = 0, len = items.length; i < len; i++) {
  1440. ids[i] = items[i][this.fieldId];
  1441. }
  1442. }
  1443. else {
  1444. // create unordered list
  1445. for (id in data) {
  1446. if (data.hasOwnProperty(id)) {
  1447. item = data[id];
  1448. ids.push(item[this.fieldId]);
  1449. }
  1450. }
  1451. }
  1452. }
  1453. return ids;
  1454. };
  1455. /**
  1456. * Execute a callback function for every item in the dataset.
  1457. * The order of the items is not determined.
  1458. * @param {function} callback
  1459. * @param {Object} [options] Available options:
  1460. * {Object.<String, String>} [fieldTypes]
  1461. * {String[]} [fields] filter fields
  1462. * {function} [filter] filter items
  1463. * {String | function} [order] Order the items by
  1464. * a field name or custom sort function.
  1465. */
  1466. DataSet.prototype.forEach = function (callback, options) {
  1467. var filter = options && options.filter,
  1468. fieldTypes = options && options.fieldTypes || this.options.fieldTypes,
  1469. data = this.data,
  1470. item,
  1471. id;
  1472. if (options && options.order) {
  1473. // execute forEach on ordered list
  1474. var items = this.get(options);
  1475. for (var i = 0, len = items.length; i < len; i++) {
  1476. item = items[i];
  1477. id = item[this.fieldId];
  1478. callback(item, id);
  1479. }
  1480. }
  1481. else {
  1482. // unordered
  1483. for (id in data) {
  1484. if (data.hasOwnProperty(id)) {
  1485. item = this._getItem(id, fieldTypes);
  1486. if (!filter || filter(item)) {
  1487. callback(item, id);
  1488. }
  1489. }
  1490. }
  1491. }
  1492. };
  1493. /**
  1494. * Map every item in the dataset.
  1495. * @param {function} callback
  1496. * @param {Object} [options] Available options:
  1497. * {Object.<String, String>} [fieldTypes]
  1498. * {String[]} [fields] filter fields
  1499. * {function} [filter] filter items
  1500. * {String | function} [order] Order the items by
  1501. * a field name or custom sort function.
  1502. * @return {Object[]} mappedItems
  1503. */
  1504. DataSet.prototype.map = function (callback, options) {
  1505. var filter = options && options.filter,
  1506. fieldTypes = options && options.fieldTypes || this.options.fieldTypes,
  1507. mappedItems = [],
  1508. data = this.data,
  1509. item;
  1510. // cast and filter items
  1511. for (var id in data) {
  1512. if (data.hasOwnProperty(id)) {
  1513. item = this._getItem(id, fieldTypes);
  1514. if (!filter || filter(item)) {
  1515. mappedItems.push(callback(item, id));
  1516. }
  1517. }
  1518. }
  1519. // order items
  1520. if (options && options.order) {
  1521. this._sort(mappedItems, options.order);
  1522. }
  1523. return mappedItems;
  1524. };
  1525. /**
  1526. * Filter the fields of an item
  1527. * @param {Object} item
  1528. * @param {String[]} fields Field names
  1529. * @return {Object} filteredItem
  1530. * @private
  1531. */
  1532. DataSet.prototype._filterFields = function (item, fields) {
  1533. var filteredItem = {};
  1534. for (var field in item) {
  1535. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  1536. filteredItem[field] = item[field];
  1537. }
  1538. }
  1539. return filteredItem;
  1540. };
  1541. /**
  1542. * Sort the provided array with items
  1543. * @param {Object[]} items
  1544. * @param {String | function} order A field name or custom sort function.
  1545. * @private
  1546. */
  1547. DataSet.prototype._sort = function (items, order) {
  1548. if (util.isString(order)) {
  1549. // order by provided field name
  1550. var name = order; // field name
  1551. items.sort(function (a, b) {
  1552. var av = a[name];
  1553. var bv = b[name];
  1554. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  1555. });
  1556. }
  1557. else if (typeof order === 'function') {
  1558. // order by sort function
  1559. items.sort(order);
  1560. }
  1561. // TODO: extend order by an Object {field:String, direction:String}
  1562. // where direction can be 'asc' or 'desc'
  1563. else {
  1564. throw new TypeError('Order must be a function or a string');
  1565. }
  1566. };
  1567. /**
  1568. * Remove an object by pointer or by id
  1569. * @param {String | Number | Object | Array} id Object or id, or an array with
  1570. * objects or ids to be removed
  1571. * @param {String} [senderId] Optional sender id
  1572. */
  1573. DataSet.prototype.remove = function (id, senderId) {
  1574. var removedItems = [],
  1575. i, len;
  1576. if (util.isNumber(id) || util.isString(id)) {
  1577. delete this.data[id];
  1578. delete this.internalIds[id];
  1579. removedItems.push(id);
  1580. }
  1581. else if (id instanceof Array) {
  1582. for (i = 0, len = id.length; i < len; i++) {
  1583. this.remove(id[i]);
  1584. }
  1585. removedItems = items.concat(id);
  1586. }
  1587. else if (id instanceof Object) {
  1588. // search for the object
  1589. for (i in this.data) {
  1590. if (this.data.hasOwnProperty(i)) {
  1591. if (this.data[i] == id) {
  1592. delete this.data[i];
  1593. delete this.internalIds[i];
  1594. removedItems.push(i);
  1595. }
  1596. }
  1597. }
  1598. }
  1599. if (removedItems.length) {
  1600. this._trigger('remove', {items: removedItems}, senderId);
  1601. }
  1602. };
  1603. /**
  1604. * Clear the data
  1605. * @param {String} [senderId] Optional sender id
  1606. */
  1607. DataSet.prototype.clear = function (senderId) {
  1608. var ids = Object.keys(this.data);
  1609. this.data = {};
  1610. this.internalIds = {};
  1611. this._trigger('remove', {items: ids}, senderId);
  1612. };
  1613. /**
  1614. * Find the item with maximum value of a specified field
  1615. * @param {String} field
  1616. * @return {Object | null} item Item containing max value, or null if no items
  1617. */
  1618. DataSet.prototype.max = function (field) {
  1619. var data = this.data,
  1620. max = null,
  1621. maxField = null;
  1622. for (var id in data) {
  1623. if (data.hasOwnProperty(id)) {
  1624. var item = data[id];
  1625. var itemField = item[field];
  1626. if (itemField != null && (!max || itemField > maxField)) {
  1627. max = item;
  1628. maxField = itemField;
  1629. }
  1630. }
  1631. }
  1632. return max;
  1633. };
  1634. /**
  1635. * Find the item with minimum value of a specified field
  1636. * @param {String} field
  1637. * @return {Object | null} item Item containing max value, or null if no items
  1638. */
  1639. DataSet.prototype.min = function (field) {
  1640. var data = this.data,
  1641. min = null,
  1642. minField = null;
  1643. for (var id in data) {
  1644. if (data.hasOwnProperty(id)) {
  1645. var item = data[id];
  1646. var itemField = item[field];
  1647. if (itemField != null && (!min || itemField < minField)) {
  1648. min = item;
  1649. minField = itemField;
  1650. }
  1651. }
  1652. }
  1653. return min;
  1654. };
  1655. /**
  1656. * Find all distinct values of a specified field
  1657. * @param {String} field
  1658. * @return {Array} values Array containing all distinct values. If the data
  1659. * items do not contain the specified field, an array
  1660. * containing a single value undefined is returned.
  1661. * The returned array is unordered.
  1662. */
  1663. DataSet.prototype.distinct = function (field) {
  1664. var data = this.data,
  1665. values = [],
  1666. fieldType = this.options.fieldTypes[field],
  1667. count = 0;
  1668. for (var prop in data) {
  1669. if (data.hasOwnProperty(prop)) {
  1670. var item = data[prop];
  1671. var value = util.cast(item[field], fieldType);
  1672. var exists = false;
  1673. for (var i = 0; i < count; i++) {
  1674. if (values[i] == value) {
  1675. exists = true;
  1676. break;
  1677. }
  1678. }
  1679. if (!exists) {
  1680. values[count] = value;
  1681. count++;
  1682. }
  1683. }
  1684. }
  1685. return values;
  1686. };
  1687. /**
  1688. * Add a single item. Will fail when an item with the same id already exists.
  1689. * @param {Object} item
  1690. * @return {String} id
  1691. * @private
  1692. */
  1693. DataSet.prototype._addItem = function (item) {
  1694. var id = item[this.fieldId];
  1695. if (id != undefined) {
  1696. // check whether this id is already taken
  1697. if (this.data[id]) {
  1698. // item already exists
  1699. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  1700. }
  1701. }
  1702. else {
  1703. // generate an id
  1704. id = util.randomUUID();
  1705. item[this.fieldId] = id;
  1706. this.internalIds[id] = item;
  1707. }
  1708. var d = {};
  1709. for (var field in item) {
  1710. if (item.hasOwnProperty(field)) {
  1711. var type = this.fieldTypes[field]; // type may be undefined
  1712. d[field] = util.cast(item[field], type);
  1713. }
  1714. }
  1715. this.data[id] = d;
  1716. return id;
  1717. };
  1718. /**
  1719. * Get an item. Fields can be casted to a specific type
  1720. * @param {String} id
  1721. * @param {Object.<String, String>} [fieldTypes] Cast field types
  1722. * @return {Object | null} item
  1723. * @private
  1724. */
  1725. DataSet.prototype._getItem = function (id, fieldTypes) {
  1726. var field, value;
  1727. // get the item from the dataset
  1728. var raw = this.data[id];
  1729. if (!raw) {
  1730. return null;
  1731. }
  1732. // cast the items field types
  1733. var casted = {},
  1734. fieldId = this.fieldId,
  1735. internalIds = this.internalIds;
  1736. if (fieldTypes) {
  1737. for (field in raw) {
  1738. if (raw.hasOwnProperty(field)) {
  1739. value = raw[field];
  1740. // output all fields, except internal ids
  1741. if ((field != fieldId) || !(value in internalIds)) {
  1742. casted[field] = util.cast(value, fieldTypes[field]);
  1743. }
  1744. }
  1745. }
  1746. }
  1747. else {
  1748. // no field types specified, no casting needed
  1749. for (field in raw) {
  1750. if (raw.hasOwnProperty(field)) {
  1751. value = raw[field];
  1752. // output all fields, except internal ids
  1753. if ((field != fieldId) || !(value in internalIds)) {
  1754. casted[field] = value;
  1755. }
  1756. }
  1757. }
  1758. }
  1759. return casted;
  1760. };
  1761. /**
  1762. * Update a single item: merge with existing item.
  1763. * Will fail when the item has no id, or when there does not exist an item
  1764. * with the same id.
  1765. * @param {Object} item
  1766. * @return {String} id
  1767. * @private
  1768. */
  1769. DataSet.prototype._updateItem = function (item) {
  1770. var id = item[this.fieldId];
  1771. if (id == undefined) {
  1772. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  1773. }
  1774. var d = this.data[id];
  1775. if (!d) {
  1776. // item doesn't exist
  1777. throw new Error('Cannot update item: no item with id ' + id + ' found');
  1778. }
  1779. // merge with current item
  1780. for (var field in item) {
  1781. if (item.hasOwnProperty(field)) {
  1782. var type = this.fieldTypes[field]; // type may be undefined
  1783. d[field] = util.cast(item[field], type);
  1784. }
  1785. }
  1786. return id;
  1787. };
  1788. /**
  1789. * Get an array with the column names of a Google DataTable
  1790. * @param {DataTable} dataTable
  1791. * @return {String[]} columnNames
  1792. * @private
  1793. */
  1794. DataSet.prototype._getColumnNames = function (dataTable) {
  1795. var columns = [];
  1796. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  1797. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  1798. }
  1799. return columns;
  1800. };
  1801. /**
  1802. * Append an item as a row to the dataTable
  1803. * @param dataTable
  1804. * @param columns
  1805. * @param item
  1806. * @private
  1807. */
  1808. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  1809. var row = dataTable.addRow();
  1810. for (var col = 0, cols = columns.length; col < cols; col++) {
  1811. var field = columns[col];
  1812. dataTable.setValue(row, col, item[field]);
  1813. }
  1814. };
  1815. /**
  1816. * DataView
  1817. *
  1818. * a dataview offers a filtered view on a dataset or an other dataview.
  1819. *
  1820. * @param {DataSet | DataView} data
  1821. * @param {Object} [options] Available options: see method get
  1822. *
  1823. * @constructor DataView
  1824. */
  1825. function DataView (data, options) {
  1826. this.id = util.randomUUID();
  1827. this.data = null;
  1828. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  1829. this.options = options || {};
  1830. this.fieldId = 'id'; // name of the field containing id
  1831. this.subscribers = {}; // event subscribers
  1832. var me = this;
  1833. this.listener = function () {
  1834. me._onEvent.apply(me, arguments);
  1835. };
  1836. this.setData(data);
  1837. }
  1838. /**
  1839. * Set a data source for the view
  1840. * @param {DataSet | DataView} data
  1841. */
  1842. DataView.prototype.setData = function (data) {
  1843. var ids, dataItems, i, len;
  1844. if (this.data) {
  1845. // unsubscribe from current dataset
  1846. if (this.data.unsubscribe) {
  1847. this.data.unsubscribe('*', this.listener);
  1848. }
  1849. // trigger a remove of all items in memory
  1850. ids = [];
  1851. for (var id in this.ids) {
  1852. if (this.ids.hasOwnProperty(id)) {
  1853. ids.push(id);
  1854. }
  1855. }
  1856. this.ids = {};
  1857. this._trigger('remove', {items: ids});
  1858. }
  1859. this.data = data;
  1860. if (this.data) {
  1861. // update fieldId
  1862. this.fieldId = this.options.fieldId ||
  1863. (this.data && this.data.options && this.data.options.fieldId) ||
  1864. 'id';
  1865. // trigger an add of all added items
  1866. ids = this.data.getIds({filter: this.options && this.options.filter});
  1867. for (i = 0, len = ids.length; i < len; i++) {
  1868. id = ids[i];
  1869. this.ids[id] = true;
  1870. }
  1871. this._trigger('add', {items: ids});
  1872. // subscribe to new dataset
  1873. if (this.data.subscribe) {
  1874. this.data.subscribe('*', this.listener);
  1875. }
  1876. }
  1877. };
  1878. /**
  1879. * Get data from the data view
  1880. *
  1881. * Usage:
  1882. *
  1883. * get()
  1884. * get(options: Object)
  1885. * get(options: Object, data: Array | DataTable)
  1886. *
  1887. * get(id: Number)
  1888. * get(id: Number, options: Object)
  1889. * get(id: Number, options: Object, data: Array | DataTable)
  1890. *
  1891. * get(ids: Number[])
  1892. * get(ids: Number[], options: Object)
  1893. * get(ids: Number[], options: Object, data: Array | DataTable)
  1894. *
  1895. * Where:
  1896. *
  1897. * {Number | String} id The id of an item
  1898. * {Number[] | String{}} ids An array with ids of items
  1899. * {Object} options An Object with options. Available options:
  1900. * {String} [type] Type of data to be returned. Can
  1901. * be 'DataTable' or 'Array' (default)
  1902. * {Object.<String, String>} [fieldTypes]
  1903. * {String[]} [fields] field names to be returned
  1904. * {function} [filter] filter items
  1905. * {String | function} [order] Order the items by
  1906. * a field name or custom sort function.
  1907. * {Array | DataTable} [data] If provided, items will be appended to this
  1908. * array or table. Required in case of Google
  1909. * DataTable.
  1910. * @param args
  1911. */
  1912. DataView.prototype.get = function (args) {
  1913. var me = this;
  1914. // parse the arguments
  1915. var ids, options, data;
  1916. var firstType = util.getType(arguments[0]);
  1917. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  1918. // get(id(s) [, options] [, data])
  1919. ids = arguments[0]; // can be a single id or an array with ids
  1920. options = arguments[1];
  1921. data = arguments[2];
  1922. }
  1923. else {
  1924. // get([, options] [, data])
  1925. options = arguments[0];
  1926. data = arguments[1];
  1927. }
  1928. // extend the options with the default options and provided options
  1929. var viewOptions = util.extend({}, this.options, options);
  1930. // create a combined filter method when needed
  1931. if (this.options.filter && options && options.filter) {
  1932. viewOptions.filter = function (item) {
  1933. return me.options.filter(item) && options.filter(item);
  1934. }
  1935. }
  1936. // build up the call to the linked data set
  1937. var getArguments = [];
  1938. if (ids != undefined) {
  1939. getArguments.push(ids);
  1940. }
  1941. getArguments.push(viewOptions);
  1942. getArguments.push(data);
  1943. return this.data && this.data.get.apply(this.data, getArguments);
  1944. };
  1945. /**
  1946. * Get ids of all items or from a filtered set of items.
  1947. * @param {Object} [options] An Object with options. Available options:
  1948. * {function} [filter] filter items
  1949. * {String | function} [order] Order the items by
  1950. * a field name or custom sort function.
  1951. * @return {Array} ids
  1952. */
  1953. DataView.prototype.getIds = function (options) {
  1954. var ids;
  1955. if (this.data) {
  1956. var defaultFilter = this.options.filter;
  1957. var filter;
  1958. if (options && options.filter) {
  1959. if (defaultFilter) {
  1960. filter = function (item) {
  1961. return defaultFilter(item) && options.filter(item);
  1962. }
  1963. }
  1964. else {
  1965. filter = options.filter;
  1966. }
  1967. }
  1968. else {
  1969. filter = defaultFilter;
  1970. }
  1971. ids = this.data.getIds({
  1972. filter: filter,
  1973. order: options && options.order
  1974. });
  1975. }
  1976. else {
  1977. ids = [];
  1978. }
  1979. return ids;
  1980. };
  1981. /**
  1982. * Event listener. Will propagate all events from the connected data set to
  1983. * the subscribers of the DataView, but will filter the items and only trigger
  1984. * when there are changes in the filtered data set.
  1985. * @param {String} event
  1986. * @param {Object | null} params
  1987. * @param {String} senderId
  1988. * @private
  1989. */
  1990. DataView.prototype._onEvent = function (event, params, senderId) {
  1991. var i, len, id, item,
  1992. ids = params && params.items,
  1993. data = this.data,
  1994. added = [],
  1995. updated = [],
  1996. removed = [];
  1997. if (ids && data) {
  1998. switch (event) {
  1999. case 'add':
  2000. // filter the ids of the added items
  2001. for (i = 0, len = ids.length; i < len; i++) {
  2002. id = ids[i];
  2003. item = this.get(id);
  2004. if (item) {
  2005. this.ids[id] = true;
  2006. added.push(id);
  2007. }
  2008. }
  2009. break;
  2010. case 'update':
  2011. // determine the event from the views viewpoint: an updated
  2012. // item can be added, updated, or removed from this view.
  2013. for (i = 0, len = ids.length; i < len; i++) {
  2014. id = ids[i];
  2015. item = this.get(id);
  2016. if (item) {
  2017. if (this.ids[id]) {
  2018. updated.push(id);
  2019. }
  2020. else {
  2021. this.ids[id] = true;
  2022. added.push(id);
  2023. }
  2024. }
  2025. else {
  2026. if (this.ids[id]) {
  2027. delete this.ids[id];
  2028. removed.push(id);
  2029. }
  2030. else {
  2031. // nothing interesting for me :-(
  2032. }
  2033. }
  2034. }
  2035. break;
  2036. case 'remove':
  2037. // filter the ids of the removed items
  2038. for (i = 0, len = ids.length; i < len; i++) {
  2039. id = ids[i];
  2040. if (this.ids[id]) {
  2041. delete this.ids[id];
  2042. removed.push(id);
  2043. }
  2044. }
  2045. break;
  2046. }
  2047. if (added.length) {
  2048. this._trigger('add', {items: added}, senderId);
  2049. }
  2050. if (updated.length) {
  2051. this._trigger('update', {items: updated}, senderId);
  2052. }
  2053. if (removed.length) {
  2054. this._trigger('remove', {items: removed}, senderId);
  2055. }
  2056. }
  2057. };
  2058. // copy subscription functionality from DataSet
  2059. DataView.prototype.subscribe = DataSet.prototype.subscribe;
  2060. DataView.prototype.unsubscribe = DataSet.prototype.unsubscribe;
  2061. DataView.prototype._trigger = DataSet.prototype._trigger;
  2062. /**
  2063. * @constructor TimeStep
  2064. * The class TimeStep is an iterator for dates. You provide a start date and an
  2065. * end date. The class itself determines the best scale (step size) based on the
  2066. * provided start Date, end Date, and minimumStep.
  2067. *
  2068. * If minimumStep is provided, the step size is chosen as close as possible
  2069. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2070. * provided, the scale is set to 1 DAY.
  2071. * The minimumStep should correspond with the onscreen size of about 6 characters
  2072. *
  2073. * Alternatively, you can set a scale by hand.
  2074. * After creation, you can initialize the class by executing first(). Then you
  2075. * can iterate from the start date to the end date via next(). You can check if
  2076. * the end date is reached with the function hasNext(). After each step, you can
  2077. * retrieve the current date via getCurrent().
  2078. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  2079. * days, to years.
  2080. *
  2081. * Version: 1.2
  2082. *
  2083. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  2084. * or new Date(2010, 9, 21, 23, 45, 00)
  2085. * @param {Date} [end] The end date
  2086. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2087. */
  2088. TimeStep = function(start, end, minimumStep) {
  2089. // variables
  2090. this.current = new Date();
  2091. this._start = new Date();
  2092. this._end = new Date();
  2093. this.autoScale = true;
  2094. this.scale = TimeStep.SCALE.DAY;
  2095. this.step = 1;
  2096. // initialize the range
  2097. this.setRange(start, end, minimumStep);
  2098. };
  2099. /// enum scale
  2100. TimeStep.SCALE = {
  2101. MILLISECOND: 1,
  2102. SECOND: 2,
  2103. MINUTE: 3,
  2104. HOUR: 4,
  2105. DAY: 5,
  2106. WEEKDAY: 6,
  2107. MONTH: 7,
  2108. YEAR: 8
  2109. };
  2110. /**
  2111. * Set a new range
  2112. * If minimumStep is provided, the step size is chosen as close as possible
  2113. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2114. * provided, the scale is set to 1 DAY.
  2115. * The minimumStep should correspond with the onscreen size of about 6 characters
  2116. * @param {Date} [start] The start date and time.
  2117. * @param {Date} [end] The end date and time.
  2118. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  2119. */
  2120. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  2121. if (!(start instanceof Date) || !(end instanceof Date)) {
  2122. //throw "No legal start or end date in method setRange";
  2123. return;
  2124. }
  2125. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  2126. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  2127. if (this.autoScale) {
  2128. this.setMinimumStep(minimumStep);
  2129. }
  2130. };
  2131. /**
  2132. * Set the range iterator to the start date.
  2133. */
  2134. TimeStep.prototype.first = function() {
  2135. this.current = new Date(this._start.valueOf());
  2136. this.roundToMinor();
  2137. };
  2138. /**
  2139. * Round the current date to the first minor date value
  2140. * This must be executed once when the current date is set to start Date
  2141. */
  2142. TimeStep.prototype.roundToMinor = function() {
  2143. // round to floor
  2144. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  2145. //noinspection FallthroughInSwitchStatementJS
  2146. switch (this.scale) {
  2147. case TimeStep.SCALE.YEAR:
  2148. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  2149. this.current.setMonth(0);
  2150. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  2151. case TimeStep.SCALE.DAY: // intentional fall through
  2152. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  2153. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  2154. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  2155. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  2156. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  2157. }
  2158. if (this.step != 1) {
  2159. // round down to the first minor value that is a multiple of the current step size
  2160. switch (this.scale) {
  2161. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  2162. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  2163. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  2164. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  2165. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2166. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  2167. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  2168. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  2169. default: break;
  2170. }
  2171. }
  2172. };
  2173. /**
  2174. * Check if the there is a next step
  2175. * @return {boolean} true if the current date has not passed the end date
  2176. */
  2177. TimeStep.prototype.hasNext = function () {
  2178. return (this.current.valueOf() <= this._end.valueOf());
  2179. };
  2180. /**
  2181. * Do the next step
  2182. */
  2183. TimeStep.prototype.next = function() {
  2184. var prev = this.current.valueOf();
  2185. // Two cases, needed to prevent issues with switching daylight savings
  2186. // (end of March and end of October)
  2187. if (this.current.getMonth() < 6) {
  2188. switch (this.scale) {
  2189. case TimeStep.SCALE.MILLISECOND:
  2190. this.current = new Date(this.current.valueOf() + this.step); break;
  2191. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  2192. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  2193. case TimeStep.SCALE.HOUR:
  2194. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  2195. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  2196. var h = this.current.getHours();
  2197. this.current.setHours(h - (h % this.step));
  2198. break;
  2199. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2200. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2201. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2202. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2203. default: break;
  2204. }
  2205. }
  2206. else {
  2207. switch (this.scale) {
  2208. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  2209. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  2210. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  2211. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  2212. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2213. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2214. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2215. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2216. default: break;
  2217. }
  2218. }
  2219. if (this.step != 1) {
  2220. // round down to the correct major value
  2221. switch (this.scale) {
  2222. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  2223. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  2224. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  2225. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  2226. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2227. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  2228. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  2229. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  2230. default: break;
  2231. }
  2232. }
  2233. // safety mechanism: if current time is still unchanged, move to the end
  2234. if (this.current.valueOf() == prev) {
  2235. this.current = new Date(this._end.valueOf());
  2236. }
  2237. };
  2238. /**
  2239. * Get the current datetime
  2240. * @return {Date} current The current date
  2241. */
  2242. TimeStep.prototype.getCurrent = function() {
  2243. return this.current;
  2244. };
  2245. /**
  2246. * Set a custom scale. Autoscaling will be disabled.
  2247. * For example setScale(SCALE.MINUTES, 5) will result
  2248. * in minor steps of 5 minutes, and major steps of an hour.
  2249. *
  2250. * @param {TimeStep.SCALE} newScale
  2251. * A scale. Choose from SCALE.MILLISECOND,
  2252. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  2253. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  2254. * SCALE.YEAR.
  2255. * @param {Number} newStep A step size, by default 1. Choose for
  2256. * example 1, 2, 5, or 10.
  2257. */
  2258. TimeStep.prototype.setScale = function(newScale, newStep) {
  2259. this.scale = newScale;
  2260. if (newStep > 0) {
  2261. this.step = newStep;
  2262. }
  2263. this.autoScale = false;
  2264. };
  2265. /**
  2266. * Enable or disable autoscaling
  2267. * @param {boolean} enable If true, autoascaling is set true
  2268. */
  2269. TimeStep.prototype.setAutoScale = function (enable) {
  2270. this.autoScale = enable;
  2271. };
  2272. /**
  2273. * Automatically determine the scale that bests fits the provided minimum step
  2274. * @param {Number} [minimumStep] The minimum step size in milliseconds
  2275. */
  2276. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  2277. if (minimumStep == undefined) {
  2278. return;
  2279. }
  2280. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  2281. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  2282. var stepDay = (1000 * 60 * 60 * 24);
  2283. var stepHour = (1000 * 60 * 60);
  2284. var stepMinute = (1000 * 60);
  2285. var stepSecond = (1000);
  2286. var stepMillisecond= (1);
  2287. // find the smallest step that is larger than the provided minimumStep
  2288. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  2289. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  2290. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  2291. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  2292. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  2293. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  2294. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  2295. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  2296. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  2297. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  2298. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  2299. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  2300. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  2301. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  2302. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  2303. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  2304. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  2305. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  2306. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  2307. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  2308. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  2309. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  2310. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  2311. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  2312. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  2313. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  2314. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  2315. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  2316. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  2317. };
  2318. /**
  2319. * Snap a date to a rounded value. The snap intervals are dependent on the
  2320. * current scale and step.
  2321. * @param {Date} date the date to be snapped
  2322. */
  2323. TimeStep.prototype.snap = function(date) {
  2324. if (this.scale == TimeStep.SCALE.YEAR) {
  2325. var year = date.getFullYear() + Math.round(date.getMonth() / 12);
  2326. date.setFullYear(Math.round(year / this.step) * this.step);
  2327. date.setMonth(0);
  2328. date.setDate(0);
  2329. date.setHours(0);
  2330. date.setMinutes(0);
  2331. date.setSeconds(0);
  2332. date.setMilliseconds(0);
  2333. }
  2334. else if (this.scale == TimeStep.SCALE.MONTH) {
  2335. if (date.getDate() > 15) {
  2336. date.setDate(1);
  2337. date.setMonth(date.getMonth() + 1);
  2338. // important: first set Date to 1, after that change the month.
  2339. }
  2340. else {
  2341. date.setDate(1);
  2342. }
  2343. date.setHours(0);
  2344. date.setMinutes(0);
  2345. date.setSeconds(0);
  2346. date.setMilliseconds(0);
  2347. }
  2348. else if (this.scale == TimeStep.SCALE.DAY ||
  2349. this.scale == TimeStep.SCALE.WEEKDAY) {
  2350. //noinspection FallthroughInSwitchStatementJS
  2351. switch (this.step) {
  2352. case 5:
  2353. case 2:
  2354. date.setHours(Math.round(date.getHours() / 24) * 24); break;
  2355. default:
  2356. date.setHours(Math.round(date.getHours() / 12) * 12); break;
  2357. }
  2358. date.setMinutes(0);
  2359. date.setSeconds(0);
  2360. date.setMilliseconds(0);
  2361. }
  2362. else if (this.scale == TimeStep.SCALE.HOUR) {
  2363. switch (this.step) {
  2364. case 4:
  2365. date.setMinutes(Math.round(date.getMinutes() / 60) * 60); break;
  2366. default:
  2367. date.setMinutes(Math.round(date.getMinutes() / 30) * 30); break;
  2368. }
  2369. date.setSeconds(0);
  2370. date.setMilliseconds(0);
  2371. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  2372. //noinspection FallthroughInSwitchStatementJS
  2373. switch (this.step) {
  2374. case 15:
  2375. case 10:
  2376. date.setMinutes(Math.round(date.getMinutes() / 5) * 5);
  2377. date.setSeconds(0);
  2378. break;
  2379. case 5:
  2380. date.setSeconds(Math.round(date.getSeconds() / 60) * 60); break;
  2381. default:
  2382. date.setSeconds(Math.round(date.getSeconds() / 30) * 30); break;
  2383. }
  2384. date.setMilliseconds(0);
  2385. }
  2386. else if (this.scale == TimeStep.SCALE.SECOND) {
  2387. //noinspection FallthroughInSwitchStatementJS
  2388. switch (this.step) {
  2389. case 15:
  2390. case 10:
  2391. date.setSeconds(Math.round(date.getSeconds() / 5) * 5);
  2392. date.setMilliseconds(0);
  2393. break;
  2394. case 5:
  2395. date.setMilliseconds(Math.round(date.getMilliseconds() / 1000) * 1000); break;
  2396. default:
  2397. date.setMilliseconds(Math.round(date.getMilliseconds() / 500) * 500); break;
  2398. }
  2399. }
  2400. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  2401. var step = this.step > 5 ? this.step / 2 : 1;
  2402. date.setMilliseconds(Math.round(date.getMilliseconds() / step) * step);
  2403. }
  2404. };
  2405. /**
  2406. * Check if the current value is a major value (for example when the step
  2407. * is DAY, a major value is each first day of the MONTH)
  2408. * @return {boolean} true if current date is major, else false.
  2409. */
  2410. TimeStep.prototype.isMajor = function() {
  2411. switch (this.scale) {
  2412. case TimeStep.SCALE.MILLISECOND:
  2413. return (this.current.getMilliseconds() == 0);
  2414. case TimeStep.SCALE.SECOND:
  2415. return (this.current.getSeconds() == 0);
  2416. case TimeStep.SCALE.MINUTE:
  2417. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  2418. // Note: this is no bug. Major label is equal for both minute and hour scale
  2419. case TimeStep.SCALE.HOUR:
  2420. return (this.current.getHours() == 0);
  2421. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2422. case TimeStep.SCALE.DAY:
  2423. return (this.current.getDate() == 1);
  2424. case TimeStep.SCALE.MONTH:
  2425. return (this.current.getMonth() == 0);
  2426. case TimeStep.SCALE.YEAR:
  2427. return false;
  2428. default:
  2429. return false;
  2430. }
  2431. };
  2432. /**
  2433. * Returns formatted text for the minor axislabel, depending on the current
  2434. * date and the scale. For example when scale is MINUTE, the current time is
  2435. * formatted as "hh:mm".
  2436. * @param {Date} [date] custom date. if not provided, current date is taken
  2437. */
  2438. TimeStep.prototype.getLabelMinor = function(date) {
  2439. if (date == undefined) {
  2440. date = this.current;
  2441. }
  2442. switch (this.scale) {
  2443. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  2444. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  2445. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  2446. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  2447. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  2448. case TimeStep.SCALE.DAY: return moment(date).format('D');
  2449. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  2450. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  2451. default: return '';
  2452. }
  2453. };
  2454. /**
  2455. * Returns formatted text for the major axis label, depending on the current
  2456. * date and the scale. For example when scale is MINUTE, the major scale is
  2457. * hours, and the hour will be formatted as "hh".
  2458. * @param {Date} [date] custom date. if not provided, current date is taken
  2459. */
  2460. TimeStep.prototype.getLabelMajor = function(date) {
  2461. if (date == undefined) {
  2462. date = this.current;
  2463. }
  2464. //noinspection FallthroughInSwitchStatementJS
  2465. switch (this.scale) {
  2466. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  2467. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  2468. case TimeStep.SCALE.MINUTE:
  2469. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  2470. case TimeStep.SCALE.WEEKDAY:
  2471. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  2472. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  2473. case TimeStep.SCALE.YEAR: return '';
  2474. default: return '';
  2475. }
  2476. };
  2477. /**
  2478. * @constructor Stack
  2479. * Stacks items on top of each other.
  2480. * @param {ItemSet} parent
  2481. * @param {Object} [options]
  2482. */
  2483. function Stack (parent, options) {
  2484. this.parent = parent;
  2485. this.options = options || {};
  2486. this.defaultOptions = {
  2487. order: function (a, b) {
  2488. //return (b.width - a.width) || (a.left - b.left); // TODO: cleanup
  2489. // Order: ranges over non-ranges, ranged ordered by width, and
  2490. // lastly ordered by start.
  2491. if (a instanceof ItemRange) {
  2492. if (b instanceof ItemRange) {
  2493. var aInt = (a.data.end - a.data.start);
  2494. var bInt = (b.data.end - b.data.start);
  2495. return (aInt - bInt) || (a.data.start - b.data.start);
  2496. }
  2497. else {
  2498. return -1;
  2499. }
  2500. }
  2501. else {
  2502. if (b instanceof ItemRange) {
  2503. return 1;
  2504. }
  2505. else {
  2506. return (a.data.start - b.data.start);
  2507. }
  2508. }
  2509. },
  2510. margin: {
  2511. item: 10
  2512. }
  2513. };
  2514. this.ordered = []; // ordered items
  2515. }
  2516. /**
  2517. * Set options for the stack
  2518. * @param {Object} options Available options:
  2519. * {ItemSet} parent
  2520. * {Number} margin
  2521. * {function} order Stacking order
  2522. */
  2523. Stack.prototype.setOptions = function setOptions (options) {
  2524. util.extend(this.options, options);
  2525. // TODO: register on data changes at the connected parent itemset, and update the changed part only and immediately
  2526. };
  2527. /**
  2528. * Stack the items such that they don't overlap. The items will have a minimal
  2529. * distance equal to options.margin.item.
  2530. */
  2531. Stack.prototype.update = function update() {
  2532. this._order();
  2533. this._stack();
  2534. };
  2535. /**
  2536. * Order the items. The items are ordered by width first, and by left position
  2537. * second.
  2538. * If a custom order function has been provided via the options, then this will
  2539. * be used.
  2540. * @private
  2541. */
  2542. Stack.prototype._order = function _order () {
  2543. var items = this.parent.items;
  2544. if (!items) {
  2545. throw new Error('Cannot stack items: parent does not contain items');
  2546. }
  2547. // TODO: store the sorted items, to have less work later on
  2548. var ordered = [];
  2549. var index = 0;
  2550. // items is a map (no array)
  2551. util.forEach(items, function (item) {
  2552. if (item.visible) {
  2553. ordered[index] = item;
  2554. index++;
  2555. }
  2556. });
  2557. //if a customer stack order function exists, use it.
  2558. var order = this.options.order || this.defaultOptions.order;
  2559. if (!(typeof order === 'function')) {
  2560. throw new Error('Option order must be a function');
  2561. }
  2562. ordered.sort(order);
  2563. this.ordered = ordered;
  2564. };
  2565. /**
  2566. * Adjust vertical positions of the events such that they don't overlap each
  2567. * other.
  2568. * @private
  2569. */
  2570. Stack.prototype._stack = function _stack () {
  2571. var i,
  2572. iMax,
  2573. ordered = this.ordered,
  2574. options = this.options,
  2575. orientation = options.orientation || this.defaultOptions.orientation,
  2576. axisOnTop = (orientation == 'top'),
  2577. margin;
  2578. if (options.margin && options.margin.item !== undefined) {
  2579. margin = options.margin.item;
  2580. }
  2581. else {
  2582. margin = this.defaultOptions.margin.item
  2583. }
  2584. // calculate new, non-overlapping positions
  2585. for (i = 0, iMax = ordered.length; i < iMax; i++) {
  2586. var item = ordered[i];
  2587. var collidingItem = null;
  2588. do {
  2589. // TODO: optimize checking for overlap. when there is a gap without items,
  2590. // you only need to check for items from the next item on, not from zero
  2591. collidingItem = this.checkOverlap(ordered, i, 0, i - 1, margin);
  2592. if (collidingItem != null) {
  2593. // There is a collision. Reposition the event above the colliding element
  2594. if (axisOnTop) {
  2595. item.top = collidingItem.top + collidingItem.height + margin;
  2596. }
  2597. else {
  2598. item.top = collidingItem.top - item.height - margin;
  2599. }
  2600. }
  2601. } while (collidingItem);
  2602. }
  2603. };
  2604. /**
  2605. * Check if the destiny position of given item overlaps with any
  2606. * of the other items from index itemStart to itemEnd.
  2607. * @param {Array} items Array with items
  2608. * @param {int} itemIndex Number of the item to be checked for overlap
  2609. * @param {int} itemStart First item to be checked.
  2610. * @param {int} itemEnd Last item to be checked.
  2611. * @return {Object | null} colliding item, or undefined when no collisions
  2612. * @param {Number} margin A minimum required margin.
  2613. * If margin is provided, the two items will be
  2614. * marked colliding when they overlap or
  2615. * when the margin between the two is smaller than
  2616. * the requested margin.
  2617. */
  2618. Stack.prototype.checkOverlap = function checkOverlap (items, itemIndex,
  2619. itemStart, itemEnd, margin) {
  2620. var collision = this.collision;
  2621. // we loop from end to start, as we suppose that the chance of a
  2622. // collision is larger for items at the end, so check these first.
  2623. var a = items[itemIndex];
  2624. for (var i = itemEnd; i >= itemStart; i--) {
  2625. var b = items[i];
  2626. if (collision(a, b, margin)) {
  2627. if (i != itemIndex) {
  2628. return b;
  2629. }
  2630. }
  2631. }
  2632. return null;
  2633. };
  2634. /**
  2635. * Test if the two provided items collide
  2636. * The items must have parameters left, width, top, and height.
  2637. * @param {Component} a The first item
  2638. * @param {Component} b The second item
  2639. * @param {Number} margin A minimum required margin.
  2640. * If margin is provided, the two items will be
  2641. * marked colliding when they overlap or
  2642. * when the margin between the two is smaller than
  2643. * the requested margin.
  2644. * @return {boolean} true if a and b collide, else false
  2645. */
  2646. Stack.prototype.collision = function collision (a, b, margin) {
  2647. return ((a.left - margin) < (b.left + b.width) &&
  2648. (a.left + a.width + margin) > b.left &&
  2649. (a.top - margin) < (b.top + b.height) &&
  2650. (a.top + a.height + margin) > b.top);
  2651. };
  2652. /**
  2653. * @constructor Range
  2654. * A Range controls a numeric range with a start and end value.
  2655. * The Range adjusts the range based on mouse events or programmatic changes,
  2656. * and triggers events when the range is changing or has been changed.
  2657. * @param {Object} [options] See description at Range.setOptions
  2658. * @extends Controller
  2659. */
  2660. function Range(options) {
  2661. this.id = util.randomUUID();
  2662. this.start = 0; // Number
  2663. this.end = 0; // Number
  2664. this.options = {
  2665. min: null,
  2666. max: null,
  2667. zoomMin: null,
  2668. zoomMax: null
  2669. };
  2670. this.listeners = [];
  2671. this.setOptions(options);
  2672. }
  2673. /**
  2674. * Set options for the range controller
  2675. * @param {Object} options Available options:
  2676. * {Number} start Set start value of the range
  2677. * {Number} end Set end value of the range
  2678. * {Number} min Minimum value for start
  2679. * {Number} max Maximum value for end
  2680. * {Number} zoomMin Set a minimum value for
  2681. * (end - start).
  2682. * {Number} zoomMax Set a maximum value for
  2683. * (end - start).
  2684. */
  2685. Range.prototype.setOptions = function (options) {
  2686. util.extend(this.options, options);
  2687. if (options.start != null || options.end != null) {
  2688. this.setRange(options.start, options.end);
  2689. }
  2690. };
  2691. /**
  2692. * Add listeners for mouse and touch events to the component
  2693. * @param {Component} component
  2694. * @param {String} event Available events: 'move', 'zoom'
  2695. * @param {String} direction Available directions: 'horizontal', 'vertical'
  2696. */
  2697. Range.prototype.subscribe = function (component, event, direction) {
  2698. var me = this;
  2699. var listener;
  2700. if (direction != 'horizontal' && direction != 'vertical') {
  2701. throw new TypeError('Unknown direction "' + direction + '". ' +
  2702. 'Choose "horizontal" or "vertical".');
  2703. }
  2704. //noinspection FallthroughInSwitchStatementJS
  2705. if (event == 'move') {
  2706. listener = {
  2707. component: component,
  2708. event: event,
  2709. direction: direction,
  2710. callback: function (event) {
  2711. me._onMouseDown(event, listener);
  2712. },
  2713. params: {}
  2714. };
  2715. component.on('mousedown', listener.callback);
  2716. me.listeners.push(listener);
  2717. }
  2718. else if (event == 'zoom') {
  2719. listener = {
  2720. component: component,
  2721. event: event,
  2722. direction: direction,
  2723. callback: function (event) {
  2724. me._onMouseWheel(event, listener);
  2725. },
  2726. params: {}
  2727. };
  2728. component.on('mousewheel', listener.callback);
  2729. me.listeners.push(listener);
  2730. }
  2731. else {
  2732. throw new TypeError('Unknown event "' + event + '". ' +
  2733. 'Choose "move" or "zoom".');
  2734. }
  2735. };
  2736. /**
  2737. * Event handler
  2738. * @param {String} event name of the event, for example 'click', 'mousemove'
  2739. * @param {function} callback callback handler, invoked with the raw HTML Event
  2740. * as parameter.
  2741. */
  2742. Range.prototype.on = function (event, callback) {
  2743. events.addListener(this, event, callback);
  2744. };
  2745. /**
  2746. * Trigger an event
  2747. * @param {String} event name of the event, available events: 'rangechange',
  2748. * 'rangechanged'
  2749. * @private
  2750. */
  2751. Range.prototype._trigger = function (event) {
  2752. events.trigger(this, event, {
  2753. start: this.start,
  2754. end: this.end
  2755. });
  2756. };
  2757. /**
  2758. * Set a new start and end range
  2759. * @param {Number} start
  2760. * @param {Number} end
  2761. */
  2762. Range.prototype.setRange = function(start, end) {
  2763. var changed = this._applyRange(start, end);
  2764. if (changed) {
  2765. this._trigger('rangechange');
  2766. this._trigger('rangechanged');
  2767. }
  2768. };
  2769. /**
  2770. * Set a new start and end range. This method is the same as setRange, but
  2771. * does not trigger a range change and range changed event, and it returns
  2772. * true when the range is changed
  2773. * @param {Number} start
  2774. * @param {Number} end
  2775. * @return {Boolean} changed
  2776. * @private
  2777. */
  2778. Range.prototype._applyRange = function(start, end) {
  2779. var newStart = (start != null) ? util.cast(start, 'Number') : this.start;
  2780. var newEnd = (end != null) ? util.cast(end, 'Number') : this.end;
  2781. var diff;
  2782. // check for valid number
  2783. if (isNaN(newStart)) {
  2784. throw new Error('Invalid start "' + start + '"');
  2785. }
  2786. if (isNaN(newEnd)) {
  2787. throw new Error('Invalid end "' + end + '"');
  2788. }
  2789. // prevent start < end
  2790. if (newEnd < newStart) {
  2791. newEnd = newStart;
  2792. }
  2793. // prevent start < min
  2794. if (this.options.min != null) {
  2795. var min = this.options.min.valueOf();
  2796. if (newStart < min) {
  2797. diff = (min - newStart);
  2798. newStart += diff;
  2799. newEnd += diff;
  2800. }
  2801. }
  2802. // prevent end > max
  2803. if (this.options.max != null) {
  2804. var max = this.options.max.valueOf();
  2805. if (newEnd > max) {
  2806. diff = (newEnd - max);
  2807. newStart -= diff;
  2808. newEnd -= diff;
  2809. }
  2810. }
  2811. // prevent (end-start) > zoomMin
  2812. if (this.options.zoomMin != null) {
  2813. var zoomMin = this.options.zoomMin.valueOf();
  2814. if (zoomMin < 0) {
  2815. zoomMin = 0;
  2816. }
  2817. if ((newEnd - newStart) < zoomMin) {
  2818. if ((this.end - this.start) > zoomMin) {
  2819. // zoom to the minimum
  2820. diff = (zoomMin - (newEnd - newStart));
  2821. newStart -= diff / 2;
  2822. newEnd += diff / 2;
  2823. }
  2824. else {
  2825. // ingore this action, we are already zoomed to the minimum
  2826. newStart = this.start;
  2827. newEnd = this.end;
  2828. }
  2829. }
  2830. }
  2831. // prevent (end-start) > zoomMin
  2832. if (this.options.zoomMax != null) {
  2833. var zoomMax = this.options.zoomMax.valueOf();
  2834. if (zoomMax < 0) {
  2835. zoomMax = 0;
  2836. }
  2837. if ((newEnd - newStart) > zoomMax) {
  2838. if ((this.end - this.start) < zoomMax) {
  2839. // zoom to the maximum
  2840. diff = ((newEnd - newStart) - zoomMax);
  2841. newStart += diff / 2;
  2842. newEnd -= diff / 2;
  2843. }
  2844. else {
  2845. // ingore this action, we are already zoomed to the maximum
  2846. newStart = this.start;
  2847. newEnd = this.end;
  2848. }
  2849. }
  2850. }
  2851. var changed = (this.start != newStart || this.end != newEnd);
  2852. this.start = newStart;
  2853. this.end = newEnd;
  2854. return changed;
  2855. };
  2856. /**
  2857. * Retrieve the current range.
  2858. * @return {Object} An object with start and end properties
  2859. */
  2860. Range.prototype.getRange = function() {
  2861. return {
  2862. start: this.start,
  2863. end: this.end
  2864. };
  2865. };
  2866. /**
  2867. * Calculate the conversion offset and factor for current range, based on
  2868. * the provided width
  2869. * @param {Number} width
  2870. * @returns {{offset: number, factor: number}} conversion
  2871. */
  2872. Range.prototype.conversion = function (width) {
  2873. var start = this.start;
  2874. var end = this.end;
  2875. return Range.conversion(this.start, this.end, width);
  2876. };
  2877. /**
  2878. * Static method to calculate the conversion offset and factor for a range,
  2879. * based on the provided start, end, and width
  2880. * @param {Number} start
  2881. * @param {Number} end
  2882. * @param {Number} width
  2883. * @returns {{offset: number, factor: number}} conversion
  2884. */
  2885. Range.conversion = function (start, end, width) {
  2886. if (width != 0 && (end - start != 0)) {
  2887. return {
  2888. offset: start,
  2889. factor: width / (end - start)
  2890. }
  2891. }
  2892. else {
  2893. return {
  2894. offset: 0,
  2895. factor: 1
  2896. };
  2897. }
  2898. };
  2899. /**
  2900. * Start moving horizontally or vertically
  2901. * @param {Event} event
  2902. * @param {Object} listener Listener containing the component and params
  2903. * @private
  2904. */
  2905. Range.prototype._onMouseDown = function(event, listener) {
  2906. event = event || window.event;
  2907. var params = listener.params;
  2908. // only react on left mouse button down
  2909. var leftButtonDown = event.which ? (event.which == 1) : (event.button == 1);
  2910. if (!leftButtonDown) {
  2911. return;
  2912. }
  2913. // get mouse position
  2914. params.mouseX = util.getPageX(event);
  2915. params.mouseY = util.getPageY(event);
  2916. params.previousLeft = 0;
  2917. params.previousOffset = 0;
  2918. params.moved = false;
  2919. params.start = this.start;
  2920. params.end = this.end;
  2921. var frame = listener.component.frame;
  2922. if (frame) {
  2923. frame.style.cursor = 'move';
  2924. }
  2925. // add event listeners to handle moving the contents
  2926. // we store the function onmousemove and onmouseup in the timeaxis,
  2927. // so we can remove the eventlisteners lateron in the function onmouseup
  2928. var me = this;
  2929. if (!params.onMouseMove) {
  2930. params.onMouseMove = function (event) {
  2931. me._onMouseMove(event, listener);
  2932. };
  2933. util.addEventListener(document, "mousemove", params.onMouseMove);
  2934. }
  2935. if (!params.onMouseUp) {
  2936. params.onMouseUp = function (event) {
  2937. me._onMouseUp(event, listener);
  2938. };
  2939. util.addEventListener(document, "mouseup", params.onMouseUp);
  2940. }
  2941. util.preventDefault(event);
  2942. };
  2943. /**
  2944. * Perform moving operating.
  2945. * This function activated from within the funcion TimeAxis._onMouseDown().
  2946. * @param {Event} event
  2947. * @param {Object} listener
  2948. * @private
  2949. */
  2950. Range.prototype._onMouseMove = function (event, listener) {
  2951. event = event || window.event;
  2952. var params = listener.params;
  2953. // calculate change in mouse position
  2954. var mouseX = util.getPageX(event);
  2955. var mouseY = util.getPageY(event);
  2956. if (params.mouseX == undefined) {
  2957. params.mouseX = mouseX;
  2958. }
  2959. if (params.mouseY == undefined) {
  2960. params.mouseY = mouseY;
  2961. }
  2962. var diffX = mouseX - params.mouseX;
  2963. var diffY = mouseY - params.mouseY;
  2964. var diff = (listener.direction == 'horizontal') ? diffX : diffY;
  2965. // if mouse movement is big enough, register it as a "moved" event
  2966. if (Math.abs(diff) >= 1) {
  2967. params.moved = true;
  2968. }
  2969. var interval = (params.end - params.start);
  2970. var width = (listener.direction == 'horizontal') ?
  2971. listener.component.width : listener.component.height;
  2972. var diffRange = -diff / width * interval;
  2973. this._applyRange(params.start + diffRange, params.end + diffRange);
  2974. // fire a rangechange event
  2975. this._trigger('rangechange');
  2976. util.preventDefault(event);
  2977. };
  2978. /**
  2979. * Stop moving operating.
  2980. * This function activated from within the function Range._onMouseDown().
  2981. * @param {event} event
  2982. * @param {Object} listener
  2983. * @private
  2984. */
  2985. Range.prototype._onMouseUp = function (event, listener) {
  2986. event = event || window.event;
  2987. var params = listener.params;
  2988. if (listener.component.frame) {
  2989. listener.component.frame.style.cursor = 'auto';
  2990. }
  2991. // remove event listeners here, important for Safari
  2992. if (params.onMouseMove) {
  2993. util.removeEventListener(document, "mousemove", params.onMouseMove);
  2994. params.onMouseMove = null;
  2995. }
  2996. if (params.onMouseUp) {
  2997. util.removeEventListener(document, "mouseup", params.onMouseUp);
  2998. params.onMouseUp = null;
  2999. }
  3000. //util.preventDefault(event);
  3001. if (params.moved) {
  3002. // fire a rangechanged event
  3003. this._trigger('rangechanged');
  3004. }
  3005. };
  3006. /**
  3007. * Event handler for mouse wheel event, used to zoom
  3008. * Code from http://adomas.org/javascript-mouse-wheel/
  3009. * @param {Event} event
  3010. * @param {Object} listener
  3011. * @private
  3012. */
  3013. Range.prototype._onMouseWheel = function(event, listener) {
  3014. event = event || window.event;
  3015. // retrieve delta
  3016. var delta = 0;
  3017. if (event.wheelDelta) { /* IE/Opera. */
  3018. delta = event.wheelDelta / 120;
  3019. } else if (event.detail) { /* Mozilla case. */
  3020. // In Mozilla, sign of delta is different than in IE.
  3021. // Also, delta is multiple of 3.
  3022. delta = -event.detail / 3;
  3023. }
  3024. // If delta is nonzero, handle it.
  3025. // Basically, delta is now positive if wheel was scrolled up,
  3026. // and negative, if wheel was scrolled down.
  3027. if (delta) {
  3028. var me = this;
  3029. var zoom = function () {
  3030. // perform the zoom action. Delta is normally 1 or -1
  3031. var zoomFactor = delta / 5.0;
  3032. var zoomAround = null;
  3033. var frame = listener.component.frame;
  3034. if (frame) {
  3035. var size, conversion;
  3036. if (listener.direction == 'horizontal') {
  3037. size = listener.component.width;
  3038. conversion = me.conversion(size);
  3039. var frameLeft = util.getAbsoluteLeft(frame);
  3040. var mouseX = util.getPageX(event);
  3041. zoomAround = (mouseX - frameLeft) / conversion.factor + conversion.offset;
  3042. }
  3043. else {
  3044. size = listener.component.height;
  3045. conversion = me.conversion(size);
  3046. var frameTop = util.getAbsoluteTop(frame);
  3047. var mouseY = util.getPageY(event);
  3048. zoomAround = ((frameTop + size - mouseY) - frameTop) / conversion.factor + conversion.offset;
  3049. }
  3050. }
  3051. me.zoom(zoomFactor, zoomAround);
  3052. };
  3053. zoom();
  3054. }
  3055. // Prevent default actions caused by mouse wheel.
  3056. // That might be ugly, but we handle scrolls somehow
  3057. // anyway, so don't bother here...
  3058. util.preventDefault(event);
  3059. };
  3060. /**
  3061. * Zoom the range the given zoomfactor in or out. Start and end date will
  3062. * be adjusted, and the timeline will be redrawn. You can optionally give a
  3063. * date around which to zoom.
  3064. * For example, try zoomfactor = 0.1 or -0.1
  3065. * @param {Number} zoomFactor Zooming amount. Positive value will zoom in,
  3066. * negative value will zoom out
  3067. * @param {Number} zoomAround Value around which will be zoomed. Optional
  3068. */
  3069. Range.prototype.zoom = function(zoomFactor, zoomAround) {
  3070. // if zoomAroundDate is not provided, take it half between start Date and end Date
  3071. if (zoomAround == null) {
  3072. zoomAround = (this.start + this.end) / 2;
  3073. }
  3074. // prevent zoom factor larger than 1 or smaller than -1 (larger than 1 will
  3075. // result in a start>=end )
  3076. if (zoomFactor >= 1) {
  3077. zoomFactor = 0.9;
  3078. }
  3079. if (zoomFactor <= -1) {
  3080. zoomFactor = -0.9;
  3081. }
  3082. // adjust a negative factor such that zooming in with 0.1 equals zooming
  3083. // out with a factor -0.1
  3084. if (zoomFactor < 0) {
  3085. zoomFactor = zoomFactor / (1 + zoomFactor);
  3086. }
  3087. // zoom start and end relative to the zoomAround value
  3088. var startDiff = (this.start - zoomAround);
  3089. var endDiff = (this.end - zoomAround);
  3090. // calculate new start and end
  3091. var newStart = this.start - startDiff * zoomFactor;
  3092. var newEnd = this.end - endDiff * zoomFactor;
  3093. this.setRange(newStart, newEnd);
  3094. };
  3095. /**
  3096. * Move the range with a given factor to the left or right. Start and end
  3097. * value will be adjusted. For example, try moveFactor = 0.1 or -0.1
  3098. * @param {Number} moveFactor Moving amount. Positive value will move right,
  3099. * negative value will move left
  3100. */
  3101. Range.prototype.move = function(moveFactor) {
  3102. // zoom start Date and end Date relative to the zoomAroundDate
  3103. var diff = (this.end - this.start);
  3104. // apply new values
  3105. var newStart = this.start + diff * moveFactor;
  3106. var newEnd = this.end + diff * moveFactor;
  3107. // TODO: reckon with min and max range
  3108. this.start = newStart;
  3109. this.end = newEnd;
  3110. };
  3111. /**
  3112. * @constructor Controller
  3113. *
  3114. * A Controller controls the reflows and repaints of all visual components
  3115. */
  3116. function Controller () {
  3117. this.id = util.randomUUID();
  3118. this.components = {};
  3119. this.repaintTimer = undefined;
  3120. this.reflowTimer = undefined;
  3121. }
  3122. /**
  3123. * Add a component to the controller
  3124. * @param {Component} component
  3125. */
  3126. Controller.prototype.add = function add(component) {
  3127. // validate the component
  3128. if (component.id == undefined) {
  3129. throw new Error('Component has no field id');
  3130. }
  3131. if (!(component instanceof Component) && !(component instanceof Controller)) {
  3132. throw new TypeError('Component must be an instance of ' +
  3133. 'prototype Component or Controller');
  3134. }
  3135. // add the component
  3136. component.controller = this;
  3137. this.components[component.id] = component;
  3138. };
  3139. /**
  3140. * Remove a component from the controller
  3141. * @param {Component | String} component
  3142. */
  3143. Controller.prototype.remove = function remove(component) {
  3144. var id;
  3145. for (id in this.components) {
  3146. if (this.components.hasOwnProperty(id)) {
  3147. if (id == component || this.components[id] == component) {
  3148. break;
  3149. }
  3150. }
  3151. }
  3152. if (id) {
  3153. delete this.components[id];
  3154. }
  3155. };
  3156. /**
  3157. * Request a reflow. The controller will schedule a reflow
  3158. * @param {Boolean} [force] If true, an immediate reflow is forced. Default
  3159. * is false.
  3160. */
  3161. Controller.prototype.requestReflow = function requestReflow(force) {
  3162. if (force) {
  3163. this.reflow();
  3164. }
  3165. else {
  3166. if (!this.reflowTimer) {
  3167. var me = this;
  3168. this.reflowTimer = setTimeout(function () {
  3169. me.reflowTimer = undefined;
  3170. me.reflow();
  3171. }, 0);
  3172. }
  3173. }
  3174. };
  3175. /**
  3176. * Request a repaint. The controller will schedule a repaint
  3177. * @param {Boolean} [force] If true, an immediate repaint is forced. Default
  3178. * is false.
  3179. */
  3180. Controller.prototype.requestRepaint = function requestRepaint(force) {
  3181. if (force) {
  3182. this.repaint();
  3183. }
  3184. else {
  3185. if (!this.repaintTimer) {
  3186. var me = this;
  3187. this.repaintTimer = setTimeout(function () {
  3188. me.repaintTimer = undefined;
  3189. me.repaint();
  3190. }, 0);
  3191. }
  3192. }
  3193. };
  3194. /**
  3195. * Repaint all components
  3196. */
  3197. Controller.prototype.repaint = function repaint() {
  3198. var changed = false;
  3199. // cancel any running repaint request
  3200. if (this.repaintTimer) {
  3201. clearTimeout(this.repaintTimer);
  3202. this.repaintTimer = undefined;
  3203. }
  3204. var done = {};
  3205. function repaint(component, id) {
  3206. if (!(id in done)) {
  3207. // first repaint the components on which this component is dependent
  3208. if (component.depends) {
  3209. component.depends.forEach(function (dep) {
  3210. repaint(dep, dep.id);
  3211. });
  3212. }
  3213. if (component.parent) {
  3214. repaint(component.parent, component.parent.id);
  3215. }
  3216. // repaint the component itself and mark as done
  3217. changed = component.repaint() || changed;
  3218. done[id] = true;
  3219. }
  3220. }
  3221. util.forEach(this.components, repaint);
  3222. // immediately reflow when needed
  3223. if (changed) {
  3224. this.reflow();
  3225. }
  3226. // TODO: limit the number of nested reflows/repaints, prevent loop
  3227. };
  3228. /**
  3229. * Reflow all components
  3230. */
  3231. Controller.prototype.reflow = function reflow() {
  3232. var resized = false;
  3233. // cancel any running repaint request
  3234. if (this.reflowTimer) {
  3235. clearTimeout(this.reflowTimer);
  3236. this.reflowTimer = undefined;
  3237. }
  3238. var done = {};
  3239. function reflow(component, id) {
  3240. if (!(id in done)) {
  3241. // first reflow the components on which this component is dependent
  3242. if (component.depends) {
  3243. component.depends.forEach(function (dep) {
  3244. reflow(dep, dep.id);
  3245. });
  3246. }
  3247. if (component.parent) {
  3248. reflow(component.parent, component.parent.id);
  3249. }
  3250. // reflow the component itself and mark as done
  3251. resized = component.reflow() || resized;
  3252. done[id] = true;
  3253. }
  3254. }
  3255. util.forEach(this.components, reflow);
  3256. // immediately repaint when needed
  3257. if (resized) {
  3258. this.repaint();
  3259. }
  3260. // TODO: limit the number of nested reflows/repaints, prevent loop
  3261. };
  3262. /**
  3263. * Prototype for visual components
  3264. */
  3265. function Component () {
  3266. this.id = null;
  3267. this.parent = null;
  3268. this.depends = null;
  3269. this.controller = null;
  3270. this.options = null;
  3271. this.frame = null; // main DOM element
  3272. this.top = 0;
  3273. this.left = 0;
  3274. this.width = 0;
  3275. this.height = 0;
  3276. }
  3277. /**
  3278. * Set parameters for the frame. Parameters will be merged in current parameter
  3279. * set.
  3280. * @param {Object} options Available parameters:
  3281. * {String | function} [className]
  3282. * {EventBus} [eventBus]
  3283. * {String | Number | function} [left]
  3284. * {String | Number | function} [top]
  3285. * {String | Number | function} [width]
  3286. * {String | Number | function} [height]
  3287. */
  3288. Component.prototype.setOptions = function setOptions(options) {
  3289. if (options) {
  3290. util.extend(this.options, options);
  3291. if (this.controller) {
  3292. this.requestRepaint();
  3293. this.requestReflow();
  3294. }
  3295. }
  3296. };
  3297. /**
  3298. * Get an option value by name
  3299. * The function will first check this.options object, and else will check
  3300. * this.defaultOptions.
  3301. * @param {String} name
  3302. * @return {*} value
  3303. */
  3304. Component.prototype.getOption = function getOption(name) {
  3305. var value;
  3306. if (this.options) {
  3307. value = this.options[name];
  3308. }
  3309. if (value === undefined && this.defaultOptions) {
  3310. value = this.defaultOptions[name];
  3311. }
  3312. return value;
  3313. };
  3314. /**
  3315. * Get the container element of the component, which can be used by a child to
  3316. * add its own widgets. Not all components do have a container for childs, in
  3317. * that case null is returned.
  3318. * @returns {HTMLElement | null} container
  3319. */
  3320. // TODO: get rid of the getContainer and getFrame methods, provide these via the options
  3321. Component.prototype.getContainer = function getContainer() {
  3322. // should be implemented by the component
  3323. return null;
  3324. };
  3325. /**
  3326. * Get the frame element of the component, the outer HTML DOM element.
  3327. * @returns {HTMLElement | null} frame
  3328. */
  3329. Component.prototype.getFrame = function getFrame() {
  3330. return this.frame;
  3331. };
  3332. /**
  3333. * Repaint the component
  3334. * @return {Boolean} changed
  3335. */
  3336. Component.prototype.repaint = function repaint() {
  3337. // should be implemented by the component
  3338. return false;
  3339. };
  3340. /**
  3341. * Reflow the component
  3342. * @return {Boolean} resized
  3343. */
  3344. Component.prototype.reflow = function reflow() {
  3345. // should be implemented by the component
  3346. return false;
  3347. };
  3348. /**
  3349. * Hide the component from the DOM
  3350. * @return {Boolean} changed
  3351. */
  3352. Component.prototype.hide = function hide() {
  3353. if (this.frame && this.frame.parentNode) {
  3354. this.frame.parentNode.removeChild(this.frame);
  3355. return true;
  3356. }
  3357. else {
  3358. return false;
  3359. }
  3360. };
  3361. /**
  3362. * Show the component in the DOM (when not already visible).
  3363. * A repaint will be executed when the component is not visible
  3364. * @return {Boolean} changed
  3365. */
  3366. Component.prototype.show = function show() {
  3367. if (!this.frame || !this.frame.parentNode) {
  3368. return this.repaint();
  3369. }
  3370. else {
  3371. return false;
  3372. }
  3373. };
  3374. /**
  3375. * Request a repaint. The controller will schedule a repaint
  3376. */
  3377. Component.prototype.requestRepaint = function requestRepaint() {
  3378. if (this.controller) {
  3379. this.controller.requestRepaint();
  3380. }
  3381. else {
  3382. throw new Error('Cannot request a repaint: no controller configured');
  3383. // TODO: just do a repaint when no parent is configured?
  3384. }
  3385. };
  3386. /**
  3387. * Request a reflow. The controller will schedule a reflow
  3388. */
  3389. Component.prototype.requestReflow = function requestReflow() {
  3390. if (this.controller) {
  3391. this.controller.requestReflow();
  3392. }
  3393. else {
  3394. throw new Error('Cannot request a reflow: no controller configured');
  3395. // TODO: just do a reflow when no parent is configured?
  3396. }
  3397. };
  3398. /**
  3399. * A panel can contain components
  3400. * @param {Component} [parent]
  3401. * @param {Component[]} [depends] Components on which this components depends
  3402. * (except for the parent)
  3403. * @param {Object} [options] Available parameters:
  3404. * {String | Number | function} [left]
  3405. * {String | Number | function} [top]
  3406. * {String | Number | function} [width]
  3407. * {String | Number | function} [height]
  3408. * {String | function} [className]
  3409. * @constructor Panel
  3410. * @extends Component
  3411. */
  3412. function Panel(parent, depends, options) {
  3413. this.id = util.randomUUID();
  3414. this.parent = parent;
  3415. this.depends = depends;
  3416. this.options = options || {};
  3417. }
  3418. Panel.prototype = new Component();
  3419. /**
  3420. * Set options. Will extend the current options.
  3421. * @param {Object} [options] Available parameters:
  3422. * {String | function} [className]
  3423. * {String | Number | function} [left]
  3424. * {String | Number | function} [top]
  3425. * {String | Number | function} [width]
  3426. * {String | Number | function} [height]
  3427. */
  3428. Panel.prototype.setOptions = Component.prototype.setOptions;
  3429. /**
  3430. * Get the container element of the panel, which can be used by a child to
  3431. * add its own widgets.
  3432. * @returns {HTMLElement} container
  3433. */
  3434. Panel.prototype.getContainer = function () {
  3435. return this.frame;
  3436. };
  3437. /**
  3438. * Repaint the component
  3439. * @return {Boolean} changed
  3440. */
  3441. Panel.prototype.repaint = function () {
  3442. var changed = 0,
  3443. update = util.updateProperty,
  3444. asSize = util.option.asSize,
  3445. options = this.options,
  3446. frame = this.frame;
  3447. if (!frame) {
  3448. frame = document.createElement('div');
  3449. frame.className = 'panel';
  3450. var className = options.className;
  3451. if (className) {
  3452. if (typeof className == 'function') {
  3453. util.addClassName(frame, String(className()));
  3454. }
  3455. else {
  3456. util.addClassName(frame, String(className));
  3457. }
  3458. }
  3459. this.frame = frame;
  3460. changed += 1;
  3461. }
  3462. if (!frame.parentNode) {
  3463. if (!this.parent) {
  3464. throw new Error('Cannot repaint panel: no parent attached');
  3465. }
  3466. var parentContainer = this.parent.getContainer();
  3467. if (!parentContainer) {
  3468. throw new Error('Cannot repaint panel: parent has no container element');
  3469. }
  3470. parentContainer.appendChild(frame);
  3471. changed += 1;
  3472. }
  3473. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3474. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3475. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3476. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3477. return (changed > 0);
  3478. };
  3479. /**
  3480. * Reflow the component
  3481. * @return {Boolean} resized
  3482. */
  3483. Panel.prototype.reflow = function () {
  3484. var changed = 0,
  3485. update = util.updateProperty,
  3486. frame = this.frame;
  3487. if (frame) {
  3488. changed += update(this, 'top', frame.offsetTop);
  3489. changed += update(this, 'left', frame.offsetLeft);
  3490. changed += update(this, 'width', frame.offsetWidth);
  3491. changed += update(this, 'height', frame.offsetHeight);
  3492. }
  3493. else {
  3494. changed += 1;
  3495. }
  3496. return (changed > 0);
  3497. };
  3498. /**
  3499. * A root panel can hold components. The root panel must be initialized with
  3500. * a DOM element as container.
  3501. * @param {HTMLElement} container
  3502. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  3503. * @constructor RootPanel
  3504. * @extends Panel
  3505. */
  3506. function RootPanel(container, options) {
  3507. this.id = util.randomUUID();
  3508. this.container = container;
  3509. this.options = options || {};
  3510. this.defaultOptions = {
  3511. autoResize: true
  3512. };
  3513. this.listeners = {}; // event listeners
  3514. }
  3515. RootPanel.prototype = new Panel();
  3516. /**
  3517. * Set options. Will extend the current options.
  3518. * @param {Object} [options] Available parameters:
  3519. * {String | function} [className]
  3520. * {String | Number | function} [left]
  3521. * {String | Number | function} [top]
  3522. * {String | Number | function} [width]
  3523. * {String | Number | function} [height]
  3524. * {Boolean | function} [autoResize]
  3525. */
  3526. RootPanel.prototype.setOptions = Component.prototype.setOptions;
  3527. /**
  3528. * Repaint the component
  3529. * @return {Boolean} changed
  3530. */
  3531. RootPanel.prototype.repaint = function () {
  3532. var changed = 0,
  3533. update = util.updateProperty,
  3534. asSize = util.option.asSize,
  3535. options = this.options,
  3536. frame = this.frame;
  3537. if (!frame) {
  3538. frame = document.createElement('div');
  3539. frame.className = 'vis timeline rootpanel';
  3540. var className = options.className;
  3541. if (className) {
  3542. util.addClassName(frame, util.option.asString(className));
  3543. }
  3544. this.frame = frame;
  3545. changed += 1;
  3546. }
  3547. if (!frame.parentNode) {
  3548. if (!this.container) {
  3549. throw new Error('Cannot repaint root panel: no container attached');
  3550. }
  3551. this.container.appendChild(frame);
  3552. changed += 1;
  3553. }
  3554. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3555. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3556. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3557. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3558. this._updateEventEmitters();
  3559. this._updateWatch();
  3560. return (changed > 0);
  3561. };
  3562. /**
  3563. * Reflow the component
  3564. * @return {Boolean} resized
  3565. */
  3566. RootPanel.prototype.reflow = function () {
  3567. var changed = 0,
  3568. update = util.updateProperty,
  3569. frame = this.frame;
  3570. if (frame) {
  3571. changed += update(this, 'top', frame.offsetTop);
  3572. changed += update(this, 'left', frame.offsetLeft);
  3573. changed += update(this, 'width', frame.offsetWidth);
  3574. changed += update(this, 'height', frame.offsetHeight);
  3575. }
  3576. else {
  3577. changed += 1;
  3578. }
  3579. return (changed > 0);
  3580. };
  3581. /**
  3582. * Update watching for resize, depending on the current option
  3583. * @private
  3584. */
  3585. RootPanel.prototype._updateWatch = function () {
  3586. var autoResize = this.getOption('autoResize');
  3587. if (autoResize) {
  3588. this._watch();
  3589. }
  3590. else {
  3591. this._unwatch();
  3592. }
  3593. };
  3594. /**
  3595. * Watch for changes in the size of the frame. On resize, the Panel will
  3596. * automatically redraw itself.
  3597. * @private
  3598. */
  3599. RootPanel.prototype._watch = function () {
  3600. var me = this;
  3601. this._unwatch();
  3602. var checkSize = function () {
  3603. var autoResize = me.getOption('autoResize');
  3604. if (!autoResize) {
  3605. // stop watching when the option autoResize is changed to false
  3606. me._unwatch();
  3607. return;
  3608. }
  3609. if (me.frame) {
  3610. // check whether the frame is resized
  3611. if ((me.frame.clientWidth != me.width) ||
  3612. (me.frame.clientHeight != me.height)) {
  3613. me.requestReflow();
  3614. }
  3615. }
  3616. };
  3617. // TODO: automatically cleanup the event listener when the frame is deleted
  3618. util.addEventListener(window, 'resize', checkSize);
  3619. this.watchTimer = setInterval(checkSize, 1000);
  3620. };
  3621. /**
  3622. * Stop watching for a resize of the frame.
  3623. * @private
  3624. */
  3625. RootPanel.prototype._unwatch = function () {
  3626. if (this.watchTimer) {
  3627. clearInterval(this.watchTimer);
  3628. this.watchTimer = undefined;
  3629. }
  3630. // TODO: remove event listener on window.resize
  3631. };
  3632. /**
  3633. * Event handler
  3634. * @param {String} event name of the event, for example 'click', 'mousemove'
  3635. * @param {function} callback callback handler, invoked with the raw HTML Event
  3636. * as parameter.
  3637. */
  3638. RootPanel.prototype.on = function (event, callback) {
  3639. // register the listener at this component
  3640. var arr = this.listeners[event];
  3641. if (!arr) {
  3642. arr = [];
  3643. this.listeners[event] = arr;
  3644. }
  3645. arr.push(callback);
  3646. this._updateEventEmitters();
  3647. };
  3648. /**
  3649. * Update the event listeners for all event emitters
  3650. * @private
  3651. */
  3652. RootPanel.prototype._updateEventEmitters = function () {
  3653. if (this.listeners) {
  3654. var me = this;
  3655. util.forEach(this.listeners, function (listeners, event) {
  3656. if (!me.emitters) {
  3657. me.emitters = {};
  3658. }
  3659. if (!(event in me.emitters)) {
  3660. // create event
  3661. var frame = me.frame;
  3662. if (frame) {
  3663. //console.log('Created a listener for event ' + event + ' on component ' + me.id); // TODO: cleanup logging
  3664. var callback = function(event) {
  3665. listeners.forEach(function (listener) {
  3666. // TODO: filter on event target!
  3667. listener(event);
  3668. });
  3669. };
  3670. me.emitters[event] = callback;
  3671. util.addEventListener(frame, event, callback);
  3672. }
  3673. }
  3674. });
  3675. // TODO: be able to delete event listeners
  3676. // TODO: be able to move event listeners to a parent when available
  3677. }
  3678. };
  3679. /**
  3680. * A horizontal time axis
  3681. * @param {Component} parent
  3682. * @param {Component[]} [depends] Components on which this components depends
  3683. * (except for the parent)
  3684. * @param {Object} [options] See TimeAxis.setOptions for the available
  3685. * options.
  3686. * @constructor TimeAxis
  3687. * @extends Component
  3688. */
  3689. function TimeAxis (parent, depends, options) {
  3690. this.id = util.randomUUID();
  3691. this.parent = parent;
  3692. this.depends = depends;
  3693. this.dom = {
  3694. majorLines: [],
  3695. majorTexts: [],
  3696. minorLines: [],
  3697. minorTexts: [],
  3698. redundant: {
  3699. majorLines: [],
  3700. majorTexts: [],
  3701. minorLines: [],
  3702. minorTexts: []
  3703. }
  3704. };
  3705. this.props = {
  3706. range: {
  3707. start: 0,
  3708. end: 0,
  3709. minimumStep: 0
  3710. },
  3711. lineTop: 0
  3712. };
  3713. this.options = options || {};
  3714. this.defaultOptions = {
  3715. orientation: 'bottom', // supported: 'top', 'bottom'
  3716. // TODO: implement timeaxis orientations 'left' and 'right'
  3717. showMinorLabels: true,
  3718. showMajorLabels: true
  3719. };
  3720. this.conversion = null;
  3721. this.range = null;
  3722. }
  3723. TimeAxis.prototype = new Component();
  3724. // TODO: comment options
  3725. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  3726. /**
  3727. * Set a range (start and end)
  3728. * @param {Range | Object} range A Range or an object containing start and end.
  3729. */
  3730. TimeAxis.prototype.setRange = function (range) {
  3731. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  3732. throw new TypeError('Range must be an instance of Range, ' +
  3733. 'or an object containing start and end.');
  3734. }
  3735. this.range = range;
  3736. };
  3737. /**
  3738. * Convert a position on screen (pixels) to a datetime
  3739. * @param {int} x Position on the screen in pixels
  3740. * @return {Date} time The datetime the corresponds with given position x
  3741. */
  3742. TimeAxis.prototype.toTime = function(x) {
  3743. var conversion = this.conversion;
  3744. return new Date(x / conversion.factor + conversion.offset);
  3745. };
  3746. /**
  3747. * Convert a datetime (Date object) into a position on the screen
  3748. * @param {Date} time A date
  3749. * @return {int} x The position on the screen in pixels which corresponds
  3750. * with the given date.
  3751. * @private
  3752. */
  3753. TimeAxis.prototype.toScreen = function(time) {
  3754. var conversion = this.conversion;
  3755. return (time.valueOf() - conversion.offset) * conversion.factor;
  3756. };
  3757. /**
  3758. * Repaint the component
  3759. * @return {Boolean} changed
  3760. */
  3761. TimeAxis.prototype.repaint = function () {
  3762. var changed = 0,
  3763. update = util.updateProperty,
  3764. asSize = util.option.asSize,
  3765. options = this.options,
  3766. orientation = this.getOption('orientation'),
  3767. props = this.props,
  3768. step = this.step;
  3769. var frame = this.frame;
  3770. if (!frame) {
  3771. frame = document.createElement('div');
  3772. this.frame = frame;
  3773. changed += 1;
  3774. }
  3775. frame.className = 'axis ' + orientation;
  3776. // TODO: custom className?
  3777. if (!frame.parentNode) {
  3778. if (!this.parent) {
  3779. throw new Error('Cannot repaint time axis: no parent attached');
  3780. }
  3781. var parentContainer = this.parent.getContainer();
  3782. if (!parentContainer) {
  3783. throw new Error('Cannot repaint time axis: parent has no container element');
  3784. }
  3785. parentContainer.appendChild(frame);
  3786. changed += 1;
  3787. }
  3788. var parent = frame.parentNode;
  3789. if (parent) {
  3790. var beforeChild = frame.nextSibling;
  3791. parent.removeChild(frame); // take frame offline while updating (is almost twice as fast)
  3792. var defaultTop = (orientation == 'bottom' && this.props.parentHeight && this.height) ?
  3793. (this.props.parentHeight - this.height) + 'px' :
  3794. '0px';
  3795. changed += update(frame.style, 'top', asSize(options.top, defaultTop));
  3796. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3797. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3798. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  3799. // get characters width and height
  3800. this._repaintMeasureChars();
  3801. if (this.step) {
  3802. this._repaintStart();
  3803. step.first();
  3804. var xFirstMajorLabel = undefined;
  3805. var max = 0;
  3806. while (step.hasNext() && max < 1000) {
  3807. max++;
  3808. var cur = step.getCurrent(),
  3809. x = this.toScreen(cur),
  3810. isMajor = step.isMajor();
  3811. // TODO: lines must have a width, such that we can create css backgrounds
  3812. if (this.getOption('showMinorLabels')) {
  3813. this._repaintMinorText(x, step.getLabelMinor());
  3814. }
  3815. if (isMajor && this.getOption('showMajorLabels')) {
  3816. if (x > 0) {
  3817. if (xFirstMajorLabel == undefined) {
  3818. xFirstMajorLabel = x;
  3819. }
  3820. this._repaintMajorText(x, step.getLabelMajor());
  3821. }
  3822. this._repaintMajorLine(x);
  3823. }
  3824. else {
  3825. this._repaintMinorLine(x);
  3826. }
  3827. step.next();
  3828. }
  3829. // create a major label on the left when needed
  3830. if (this.getOption('showMajorLabels')) {
  3831. var leftTime = this.toTime(0),
  3832. leftText = step.getLabelMajor(leftTime),
  3833. widthText = leftText.length * (props.majorCharWidth || 10) + 10; // upper bound estimation
  3834. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3835. this._repaintMajorText(0, leftText);
  3836. }
  3837. }
  3838. this._repaintEnd();
  3839. }
  3840. this._repaintLine();
  3841. // put frame online again
  3842. if (beforeChild) {
  3843. parent.insertBefore(frame, beforeChild);
  3844. }
  3845. else {
  3846. parent.appendChild(frame)
  3847. }
  3848. }
  3849. return (changed > 0);
  3850. };
  3851. /**
  3852. * Start a repaint. Move all DOM elements to a redundant list, where they
  3853. * can be picked for re-use, or can be cleaned up in the end
  3854. * @private
  3855. */
  3856. TimeAxis.prototype._repaintStart = function () {
  3857. var dom = this.dom,
  3858. redundant = dom.redundant;
  3859. redundant.majorLines = dom.majorLines;
  3860. redundant.majorTexts = dom.majorTexts;
  3861. redundant.minorLines = dom.minorLines;
  3862. redundant.minorTexts = dom.minorTexts;
  3863. dom.majorLines = [];
  3864. dom.majorTexts = [];
  3865. dom.minorLines = [];
  3866. dom.minorTexts = [];
  3867. };
  3868. /**
  3869. * End a repaint. Cleanup leftover DOM elements in the redundant list
  3870. * @private
  3871. */
  3872. TimeAxis.prototype._repaintEnd = function () {
  3873. util.forEach(this.dom.redundant, function (arr) {
  3874. while (arr.length) {
  3875. var elem = arr.pop();
  3876. if (elem && elem.parentNode) {
  3877. elem.parentNode.removeChild(elem);
  3878. }
  3879. }
  3880. });
  3881. };
  3882. /**
  3883. * Create a minor label for the axis at position x
  3884. * @param {Number} x
  3885. * @param {String} text
  3886. * @private
  3887. */
  3888. TimeAxis.prototype._repaintMinorText = function (x, text) {
  3889. // reuse redundant label
  3890. var label = this.dom.redundant.minorTexts.shift();
  3891. if (!label) {
  3892. // create new label
  3893. var content = document.createTextNode('');
  3894. label = document.createElement('div');
  3895. label.appendChild(content);
  3896. label.className = 'text minor';
  3897. this.frame.appendChild(label);
  3898. }
  3899. this.dom.minorTexts.push(label);
  3900. label.childNodes[0].nodeValue = text;
  3901. label.style.left = x + 'px';
  3902. label.style.top = this.props.minorLabelTop + 'px';
  3903. //label.title = title; // TODO: this is a heavy operation
  3904. };
  3905. /**
  3906. * Create a Major label for the axis at position x
  3907. * @param {Number} x
  3908. * @param {String} text
  3909. * @private
  3910. */
  3911. TimeAxis.prototype._repaintMajorText = function (x, text) {
  3912. // reuse redundant label
  3913. var label = this.dom.redundant.majorTexts.shift();
  3914. if (!label) {
  3915. // create label
  3916. var content = document.createTextNode(text);
  3917. label = document.createElement('div');
  3918. label.className = 'text major';
  3919. label.appendChild(content);
  3920. this.frame.appendChild(label);
  3921. }
  3922. this.dom.majorTexts.push(label);
  3923. label.childNodes[0].nodeValue = text;
  3924. label.style.top = this.props.majorLabelTop + 'px';
  3925. label.style.left = x + 'px';
  3926. //label.title = title; // TODO: this is a heavy operation
  3927. };
  3928. /**
  3929. * Create a minor line for the axis at position x
  3930. * @param {Number} x
  3931. * @private
  3932. */
  3933. TimeAxis.prototype._repaintMinorLine = function (x) {
  3934. // reuse redundant line
  3935. var line = this.dom.redundant.minorLines.shift();
  3936. if (!line) {
  3937. // create vertical line
  3938. line = document.createElement('div');
  3939. line.className = 'grid vertical minor';
  3940. this.frame.appendChild(line);
  3941. }
  3942. this.dom.minorLines.push(line);
  3943. var props = this.props;
  3944. line.style.top = props.minorLineTop + 'px';
  3945. line.style.height = props.minorLineHeight + 'px';
  3946. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  3947. };
  3948. /**
  3949. * Create a Major line for the axis at position x
  3950. * @param {Number} x
  3951. * @private
  3952. */
  3953. TimeAxis.prototype._repaintMajorLine = function (x) {
  3954. // reuse redundant line
  3955. var line = this.dom.redundant.majorLines.shift();
  3956. if (!line) {
  3957. // create vertical line
  3958. line = document.createElement('DIV');
  3959. line.className = 'grid vertical major';
  3960. this.frame.appendChild(line);
  3961. }
  3962. this.dom.majorLines.push(line);
  3963. var props = this.props;
  3964. line.style.top = props.majorLineTop + 'px';
  3965. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  3966. line.style.height = props.majorLineHeight + 'px';
  3967. };
  3968. /**
  3969. * Repaint the horizontal line for the axis
  3970. * @private
  3971. */
  3972. TimeAxis.prototype._repaintLine = function() {
  3973. var line = this.dom.line,
  3974. frame = this.frame,
  3975. options = this.options;
  3976. // line before all axis elements
  3977. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  3978. if (line) {
  3979. // put this line at the end of all childs
  3980. frame.removeChild(line);
  3981. frame.appendChild(line);
  3982. }
  3983. else {
  3984. // create the axis line
  3985. line = document.createElement('div');
  3986. line.className = 'grid horizontal major';
  3987. frame.appendChild(line);
  3988. this.dom.line = line;
  3989. }
  3990. line.style.top = this.props.lineTop + 'px';
  3991. }
  3992. else {
  3993. if (line && axis.parentElement) {
  3994. frame.removeChild(axis.line);
  3995. delete this.dom.line;
  3996. }
  3997. }
  3998. };
  3999. /**
  4000. * Create characters used to determine the size of text on the axis
  4001. * @private
  4002. */
  4003. TimeAxis.prototype._repaintMeasureChars = function () {
  4004. // calculate the width and height of a single character
  4005. // this is used to calculate the step size, and also the positioning of the
  4006. // axis
  4007. var dom = this.dom,
  4008. text;
  4009. if (!dom.measureCharMinor) {
  4010. text = document.createTextNode('0');
  4011. var measureCharMinor = document.createElement('DIV');
  4012. measureCharMinor.className = 'text minor measure';
  4013. measureCharMinor.appendChild(text);
  4014. this.frame.appendChild(measureCharMinor);
  4015. dom.measureCharMinor = measureCharMinor;
  4016. }
  4017. if (!dom.measureCharMajor) {
  4018. text = document.createTextNode('0');
  4019. var measureCharMajor = document.createElement('DIV');
  4020. measureCharMajor.className = 'text major measure';
  4021. measureCharMajor.appendChild(text);
  4022. this.frame.appendChild(measureCharMajor);
  4023. dom.measureCharMajor = measureCharMajor;
  4024. }
  4025. };
  4026. /**
  4027. * Reflow the component
  4028. * @return {Boolean} resized
  4029. */
  4030. TimeAxis.prototype.reflow = function () {
  4031. var changed = 0,
  4032. update = util.updateProperty,
  4033. frame = this.frame,
  4034. range = this.range;
  4035. if (!range) {
  4036. throw new Error('Cannot repaint time axis: no range configured');
  4037. }
  4038. if (frame) {
  4039. changed += update(this, 'top', frame.offsetTop);
  4040. changed += update(this, 'left', frame.offsetLeft);
  4041. // calculate size of a character
  4042. var props = this.props,
  4043. showMinorLabels = this.getOption('showMinorLabels'),
  4044. showMajorLabels = this.getOption('showMajorLabels'),
  4045. measureCharMinor = this.dom.measureCharMinor,
  4046. measureCharMajor = this.dom.measureCharMajor;
  4047. if (measureCharMinor) {
  4048. props.minorCharHeight = measureCharMinor.clientHeight;
  4049. props.minorCharWidth = measureCharMinor.clientWidth;
  4050. }
  4051. if (measureCharMajor) {
  4052. props.majorCharHeight = measureCharMajor.clientHeight;
  4053. props.majorCharWidth = measureCharMajor.clientWidth;
  4054. }
  4055. var parentHeight = frame.parentNode ? frame.parentNode.offsetHeight : 0;
  4056. if (parentHeight != props.parentHeight) {
  4057. props.parentHeight = parentHeight;
  4058. changed += 1;
  4059. }
  4060. switch (this.getOption('orientation')) {
  4061. case 'bottom':
  4062. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4063. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4064. props.minorLabelTop = 0;
  4065. props.majorLabelTop = props.minorLabelTop + props.minorLabelHeight;
  4066. props.minorLineTop = -this.top;
  4067. props.minorLineHeight = Math.max(this.top + props.majorLabelHeight, 0);
  4068. props.minorLineWidth = 1; // TODO: really calculate width
  4069. props.majorLineTop = -this.top;
  4070. props.majorLineHeight = Math.max(this.top + props.minorLabelHeight + props.majorLabelHeight, 0);
  4071. props.majorLineWidth = 1; // TODO: really calculate width
  4072. props.lineTop = 0;
  4073. break;
  4074. case 'top':
  4075. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4076. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4077. props.majorLabelTop = 0;
  4078. props.minorLabelTop = props.majorLabelTop + props.majorLabelHeight;
  4079. props.minorLineTop = props.minorLabelTop;
  4080. props.minorLineHeight = Math.max(parentHeight - props.majorLabelHeight - this.top);
  4081. props.minorLineWidth = 1; // TODO: really calculate width
  4082. props.majorLineTop = 0;
  4083. props.majorLineHeight = Math.max(parentHeight - this.top);
  4084. props.majorLineWidth = 1; // TODO: really calculate width
  4085. props.lineTop = props.majorLabelHeight + props.minorLabelHeight;
  4086. break;
  4087. default:
  4088. throw new Error('Unkown orientation "' + this.getOption('orientation') + '"');
  4089. }
  4090. var height = props.minorLabelHeight + props.majorLabelHeight;
  4091. changed += update(this, 'width', frame.offsetWidth);
  4092. changed += update(this, 'height', height);
  4093. // calculate range and step
  4094. this._updateConversion();
  4095. var start = util.cast(range.start, 'Date'),
  4096. end = util.cast(range.end, 'Date'),
  4097. minimumStep = this.toTime((props.minorCharWidth || 10) * 5) - this.toTime(0);
  4098. this.step = new TimeStep(start, end, minimumStep);
  4099. changed += update(props.range, 'start', start.valueOf());
  4100. changed += update(props.range, 'end', end.valueOf());
  4101. changed += update(props.range, 'minimumStep', minimumStep.valueOf());
  4102. }
  4103. return (changed > 0);
  4104. };
  4105. /**
  4106. * Calculate the factor and offset to convert a position on screen to the
  4107. * corresponding date and vice versa.
  4108. * After the method _updateConversion is executed once, the methods toTime
  4109. * and toScreen can be used.
  4110. * @private
  4111. */
  4112. TimeAxis.prototype._updateConversion = function() {
  4113. var range = this.range;
  4114. if (!range) {
  4115. throw new Error('No range configured');
  4116. }
  4117. if (range.conversion) {
  4118. this.conversion = range.conversion(this.width);
  4119. }
  4120. else {
  4121. this.conversion = Range.conversion(range.start, range.end, this.width);
  4122. }
  4123. };
  4124. /**
  4125. * An ItemSet holds a set of items and ranges which can be displayed in a
  4126. * range. The width is determined by the parent of the ItemSet, and the height
  4127. * is determined by the size of the items.
  4128. * @param {Component} parent
  4129. * @param {Component[]} [depends] Components on which this components depends
  4130. * (except for the parent)
  4131. * @param {Object} [options] See ItemSet.setOptions for the available
  4132. * options.
  4133. * @constructor ItemSet
  4134. * @extends Panel
  4135. */
  4136. // TODO: improve performance by replacing all Array.forEach with a for loop
  4137. function ItemSet(parent, depends, options) {
  4138. this.id = util.randomUUID();
  4139. this.parent = parent;
  4140. this.depends = depends;
  4141. // one options object is shared by this itemset and all its items
  4142. this.options = options || {};
  4143. this.defaultOptions = {
  4144. type: 'box',
  4145. align: 'center',
  4146. orientation: 'bottom',
  4147. margin: {
  4148. axis: 20,
  4149. item: 10
  4150. },
  4151. padding: 5
  4152. };
  4153. this.dom = {};
  4154. var me = this;
  4155. this.itemsData = null; // DataSet
  4156. this.range = null; // Range or Object {start: number, end: number}
  4157. this.listeners = {
  4158. 'add': function (event, params, senderId) {
  4159. if (senderId != me.id) {
  4160. me._onAdd(params.items);
  4161. }
  4162. },
  4163. 'update': function (event, params, senderId) {
  4164. if (senderId != me.id) {
  4165. me._onUpdate(params.items);
  4166. }
  4167. },
  4168. 'remove': function (event, params, senderId) {
  4169. if (senderId != me.id) {
  4170. me._onRemove(params.items);
  4171. }
  4172. }
  4173. };
  4174. this.items = {}; // object with an Item for every data item
  4175. this.queue = {}; // queue with id/actions: 'add', 'update', 'delete'
  4176. this.stack = new Stack(this, Object.create(this.options));
  4177. this.conversion = null;
  4178. // TODO: ItemSet should also attach event listeners for rangechange and rangechanged, like timeaxis
  4179. }
  4180. ItemSet.prototype = new Panel();
  4181. // available item types will be registered here
  4182. ItemSet.types = {
  4183. box: ItemBox,
  4184. range: ItemRange,
  4185. point: ItemPoint
  4186. };
  4187. /**
  4188. * Set options for the ItemSet. Existing options will be extended/overwritten.
  4189. * @param {Object} [options] The following options are available:
  4190. * {String | function} [className]
  4191. * class name for the itemset
  4192. * {String} [type]
  4193. * Default type for the items. Choose from 'box'
  4194. * (default), 'point', or 'range'. The default
  4195. * Style can be overwritten by individual items.
  4196. * {String} align
  4197. * Alignment for the items, only applicable for
  4198. * ItemBox. Choose 'center' (default), 'left', or
  4199. * 'right'.
  4200. * {String} orientation
  4201. * Orientation of the item set. Choose 'top' or
  4202. * 'bottom' (default).
  4203. * {Number} margin.axis
  4204. * Margin between the axis and the items in pixels.
  4205. * Default is 20.
  4206. * {Number} margin.item
  4207. * Margin between items in pixels. Default is 10.
  4208. * {Number} padding
  4209. * Padding of the contents of an item in pixels.
  4210. * Must correspond with the items css. Default is 5.
  4211. */
  4212. ItemSet.prototype.setOptions = Component.prototype.setOptions;
  4213. /**
  4214. * Set range (start and end).
  4215. * @param {Range | Object} range A Range or an object containing start and end.
  4216. */
  4217. ItemSet.prototype.setRange = function setRange(range) {
  4218. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4219. throw new TypeError('Range must be an instance of Range, ' +
  4220. 'or an object containing start and end.');
  4221. }
  4222. this.range = range;
  4223. };
  4224. /**
  4225. * Repaint the component
  4226. * @return {Boolean} changed
  4227. */
  4228. ItemSet.prototype.repaint = function repaint() {
  4229. var changed = 0,
  4230. update = util.updateProperty,
  4231. asSize = util.option.asSize,
  4232. options = this.options,
  4233. orientation = this.getOption('orientation'),
  4234. defaultOptions = this.defaultOptions,
  4235. frame = this.frame;
  4236. if (!frame) {
  4237. frame = document.createElement('div');
  4238. frame.className = 'itemset';
  4239. var className = options.className;
  4240. if (className) {
  4241. util.addClassName(frame, util.option.asString(className));
  4242. }
  4243. // create background panel
  4244. var background = document.createElement('div');
  4245. background.className = 'background';
  4246. frame.appendChild(background);
  4247. this.dom.background = background;
  4248. // create foreground panel
  4249. var foreground = document.createElement('div');
  4250. foreground.className = 'foreground';
  4251. frame.appendChild(foreground);
  4252. this.dom.foreground = foreground;
  4253. // create axis panel
  4254. var axis = document.createElement('div');
  4255. axis.className = 'itemset-axis';
  4256. //frame.appendChild(axis);
  4257. this.dom.axis = axis;
  4258. this.frame = frame;
  4259. changed += 1;
  4260. }
  4261. if (!this.parent) {
  4262. throw new Error('Cannot repaint itemset: no parent attached');
  4263. }
  4264. var parentContainer = this.parent.getContainer();
  4265. if (!parentContainer) {
  4266. throw new Error('Cannot repaint itemset: parent has no container element');
  4267. }
  4268. if (!frame.parentNode) {
  4269. parentContainer.appendChild(frame);
  4270. changed += 1;
  4271. }
  4272. if (!this.dom.axis.parentNode) {
  4273. parentContainer.appendChild(this.dom.axis);
  4274. changed += 1;
  4275. }
  4276. // reposition frame
  4277. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  4278. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  4279. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  4280. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  4281. // reposition axis
  4282. changed += update(this.dom.axis.style, 'left', asSize(options.left, '0px'));
  4283. changed += update(this.dom.axis.style, 'width', asSize(options.width, '100%'));
  4284. if (orientation == 'bottom') {
  4285. changed += update(this.dom.axis.style, 'top', (this.height + this.top) + 'px');
  4286. }
  4287. else { // orientation == 'top'
  4288. changed += update(this.dom.axis.style, 'top', this.top + 'px');
  4289. }
  4290. this._updateConversion();
  4291. var me = this,
  4292. queue = this.queue,
  4293. itemsData = this.itemsData,
  4294. items = this.items,
  4295. dataOptions = {
  4296. fields: [(itemsData && itemsData.fieldId || 'id'), 'start', 'end', 'content', 'type']
  4297. };
  4298. // TODO: copy options from the itemset itself?
  4299. // show/hide added/changed/removed items
  4300. Object.keys(queue).forEach(function (id) {
  4301. //var entry = queue[id];
  4302. var action = queue[id];
  4303. var item = items[id];
  4304. //var item = entry.item;
  4305. //noinspection FallthroughInSwitchStatementJS
  4306. switch (action) {
  4307. case 'add':
  4308. case 'update':
  4309. var itemData = itemsData && itemsData.get(id, dataOptions);
  4310. if (itemData) {
  4311. var type = itemData.type ||
  4312. (itemData.start && itemData.end && 'range') ||
  4313. options.type ||
  4314. 'box';
  4315. var constructor = ItemSet.types[type];
  4316. // TODO: how to handle items with invalid data? hide them and give a warning? or throw an error?
  4317. if (item) {
  4318. // update item
  4319. if (!constructor || !(item instanceof constructor)) {
  4320. // item type has changed, hide and delete the item
  4321. changed += item.hide();
  4322. item = null;
  4323. }
  4324. else {
  4325. item.data = itemData; // TODO: create a method item.setData ?
  4326. changed++;
  4327. }
  4328. }
  4329. if (!item) {
  4330. // create item
  4331. if (constructor) {
  4332. item = new constructor(me, itemData, options, defaultOptions);
  4333. changed++;
  4334. }
  4335. else {
  4336. throw new TypeError('Unknown item type "' + type + '"');
  4337. }
  4338. }
  4339. // force a repaint (not only a reposition)
  4340. item.repaint();
  4341. items[id] = item;
  4342. }
  4343. // update queue
  4344. delete queue[id];
  4345. break;
  4346. case 'remove':
  4347. if (item) {
  4348. // remove DOM of the item
  4349. changed += item.hide();
  4350. }
  4351. // update lists
  4352. delete items[id];
  4353. delete queue[id];
  4354. break;
  4355. default:
  4356. console.log('Error: unknown action "' + action + '"');
  4357. }
  4358. });
  4359. // reposition all items. Show items only when in the visible area
  4360. util.forEach(this.items, function (item) {
  4361. if (item.visible) {
  4362. changed += item.show();
  4363. item.reposition();
  4364. }
  4365. else {
  4366. changed += item.hide();
  4367. }
  4368. });
  4369. return (changed > 0);
  4370. };
  4371. /**
  4372. * Get the foreground container element
  4373. * @return {HTMLElement} foreground
  4374. */
  4375. ItemSet.prototype.getForeground = function getForeground() {
  4376. return this.dom.foreground;
  4377. };
  4378. /**
  4379. * Get the background container element
  4380. * @return {HTMLElement} background
  4381. */
  4382. ItemSet.prototype.getBackground = function getBackground() {
  4383. return this.dom.background;
  4384. };
  4385. /**
  4386. * Get the axis container element
  4387. * @return {HTMLElement} axis
  4388. */
  4389. ItemSet.prototype.getAxis = function getAxis() {
  4390. return this.dom.axis;
  4391. };
  4392. /**
  4393. * Reflow the component
  4394. * @return {Boolean} resized
  4395. */
  4396. ItemSet.prototype.reflow = function reflow () {
  4397. var changed = 0,
  4398. options = this.options,
  4399. marginAxis = options.margin && options.margin.axis || this.defaultOptions.margin.axis,
  4400. marginItem = options.margin && options.margin.item || this.defaultOptions.margin.item,
  4401. update = util.updateProperty,
  4402. asNumber = util.option.asNumber,
  4403. asSize = util.option.asSize,
  4404. frame = this.frame;
  4405. if (frame) {
  4406. this._updateConversion();
  4407. util.forEach(this.items, function (item) {
  4408. changed += item.reflow();
  4409. });
  4410. // TODO: stack.update should be triggered via an event, in stack itself
  4411. // TODO: only update the stack when there are changed items
  4412. this.stack.update();
  4413. var maxHeight = asNumber(options.maxHeight);
  4414. var fixedHeight = (asSize(options.height) != null);
  4415. var height;
  4416. if (fixedHeight) {
  4417. height = frame.offsetHeight;
  4418. }
  4419. else {
  4420. // height is not specified, determine the height from the height and positioned items
  4421. var visibleItems = this.stack.ordered; // TODO: not so nice way to get the filtered items
  4422. if (visibleItems.length) {
  4423. var min = visibleItems[0].top;
  4424. var max = visibleItems[0].top + visibleItems[0].height;
  4425. util.forEach(visibleItems, function (item) {
  4426. min = Math.min(min, item.top);
  4427. max = Math.max(max, (item.top + item.height));
  4428. });
  4429. height = (max - min) + marginAxis + marginItem;
  4430. }
  4431. else {
  4432. height = marginAxis + marginItem;
  4433. }
  4434. }
  4435. if (maxHeight != null) {
  4436. height = Math.min(height, maxHeight);
  4437. }
  4438. changed += update(this, 'height', height);
  4439. // calculate height from items
  4440. changed += update(this, 'top', frame.offsetTop);
  4441. changed += update(this, 'left', frame.offsetLeft);
  4442. changed += update(this, 'width', frame.offsetWidth);
  4443. }
  4444. else {
  4445. changed += 1;
  4446. }
  4447. return (changed > 0);
  4448. };
  4449. /**
  4450. * Hide this component from the DOM
  4451. * @return {Boolean} changed
  4452. */
  4453. ItemSet.prototype.hide = function hide() {
  4454. var changed = false;
  4455. // remove the DOM
  4456. if (this.frame && this.frame.parentNode) {
  4457. this.frame.parentNode.removeChild(this.frame);
  4458. changed = true;
  4459. }
  4460. if (this.dom.axis && this.dom.axis.parentNode) {
  4461. this.dom.axis.parentNode.removeChild(this.dom.axis);
  4462. changed = true;
  4463. }
  4464. return changed;
  4465. };
  4466. /**
  4467. * Set items
  4468. * @param {vis.DataSet | null} items
  4469. */
  4470. ItemSet.prototype.setItems = function setItems(items) {
  4471. var me = this,
  4472. ids,
  4473. oldItemsData = this.itemsData;
  4474. // replace the dataset
  4475. if (!items) {
  4476. this.itemsData = null;
  4477. }
  4478. else if (items instanceof DataSet || items instanceof DataView) {
  4479. this.itemsData = items;
  4480. }
  4481. else {
  4482. throw new TypeError('Data must be an instance of DataSet');
  4483. }
  4484. if (oldItemsData) {
  4485. // unsubscribe from old dataset
  4486. util.forEach(this.listeners, function (callback, event) {
  4487. oldItemsData.unsubscribe(event, callback);
  4488. });
  4489. // remove all drawn items
  4490. ids = oldItemsData.getIds();
  4491. this._onRemove(ids);
  4492. }
  4493. if (this.itemsData) {
  4494. // subscribe to new dataset
  4495. var id = this.id;
  4496. util.forEach(this.listeners, function (callback, event) {
  4497. me.itemsData.subscribe(event, callback, id);
  4498. });
  4499. // draw all new items
  4500. ids = this.itemsData.getIds();
  4501. this._onAdd(ids);
  4502. }
  4503. };
  4504. /**
  4505. * Get the current items items
  4506. * @returns {vis.DataSet | null}
  4507. */
  4508. ItemSet.prototype.getItems = function getItems() {
  4509. return this.itemsData;
  4510. };
  4511. /**
  4512. * Handle updated items
  4513. * @param {Number[]} ids
  4514. * @private
  4515. */
  4516. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  4517. this._toQueue('update', ids);
  4518. };
  4519. /**
  4520. * Handle changed items
  4521. * @param {Number[]} ids
  4522. * @private
  4523. */
  4524. ItemSet.prototype._onAdd = function _onAdd(ids) {
  4525. this._toQueue('add', ids);
  4526. };
  4527. /**
  4528. * Handle removed items
  4529. * @param {Number[]} ids
  4530. * @private
  4531. */
  4532. ItemSet.prototype._onRemove = function _onRemove(ids) {
  4533. this._toQueue('remove', ids);
  4534. };
  4535. /**
  4536. * Put items in the queue to be added/updated/remove
  4537. * @param {String} action can be 'add', 'update', 'remove'
  4538. * @param {Number[]} ids
  4539. */
  4540. ItemSet.prototype._toQueue = function _toQueue(action, ids) {
  4541. var queue = this.queue;
  4542. ids.forEach(function (id) {
  4543. queue[id] = action;
  4544. });
  4545. if (this.controller) {
  4546. //this.requestReflow();
  4547. this.requestRepaint();
  4548. }
  4549. };
  4550. /**
  4551. * Calculate the factor and offset to convert a position on screen to the
  4552. * corresponding date and vice versa.
  4553. * After the method _updateConversion is executed once, the methods toTime
  4554. * and toScreen can be used.
  4555. * @private
  4556. */
  4557. ItemSet.prototype._updateConversion = function _updateConversion() {
  4558. var range = this.range;
  4559. if (!range) {
  4560. throw new Error('No range configured');
  4561. }
  4562. if (range.conversion) {
  4563. this.conversion = range.conversion(this.width);
  4564. }
  4565. else {
  4566. this.conversion = Range.conversion(range.start, range.end, this.width);
  4567. }
  4568. };
  4569. /**
  4570. * Convert a position on screen (pixels) to a datetime
  4571. * Before this method can be used, the method _updateConversion must be
  4572. * executed once.
  4573. * @param {int} x Position on the screen in pixels
  4574. * @return {Date} time The datetime the corresponds with given position x
  4575. */
  4576. ItemSet.prototype.toTime = function toTime(x) {
  4577. var conversion = this.conversion;
  4578. return new Date(x / conversion.factor + conversion.offset);
  4579. };
  4580. /**
  4581. * Convert a datetime (Date object) into a position on the screen
  4582. * Before this method can be used, the method _updateConversion must be
  4583. * executed once.
  4584. * @param {Date} time A date
  4585. * @return {int} x The position on the screen in pixels which corresponds
  4586. * with the given date.
  4587. */
  4588. ItemSet.prototype.toScreen = function toScreen(time) {
  4589. var conversion = this.conversion;
  4590. return (time.valueOf() - conversion.offset) * conversion.factor;
  4591. };
  4592. /**
  4593. * @constructor Item
  4594. * @param {ItemSet} parent
  4595. * @param {Object} data Object containing (optional) parameters type,
  4596. * start, end, content, group, className.
  4597. * @param {Object} [options] Options to set initial property values
  4598. * @param {Object} [defaultOptions] default options
  4599. * // TODO: describe available options
  4600. */
  4601. function Item (parent, data, options, defaultOptions) {
  4602. this.parent = parent;
  4603. this.data = data;
  4604. this.dom = null;
  4605. this.options = options || {};
  4606. this.defaultOptions = defaultOptions || {};
  4607. this.selected = false;
  4608. this.visible = false;
  4609. this.top = 0;
  4610. this.left = 0;
  4611. this.width = 0;
  4612. this.height = 0;
  4613. }
  4614. /**
  4615. * Select current item
  4616. */
  4617. Item.prototype.select = function select() {
  4618. this.selected = true;
  4619. };
  4620. /**
  4621. * Unselect current item
  4622. */
  4623. Item.prototype.unselect = function unselect() {
  4624. this.selected = false;
  4625. };
  4626. /**
  4627. * Show the Item in the DOM (when not already visible)
  4628. * @return {Boolean} changed
  4629. */
  4630. Item.prototype.show = function show() {
  4631. return false;
  4632. };
  4633. /**
  4634. * Hide the Item from the DOM (when visible)
  4635. * @return {Boolean} changed
  4636. */
  4637. Item.prototype.hide = function hide() {
  4638. return false;
  4639. };
  4640. /**
  4641. * Repaint the item
  4642. * @return {Boolean} changed
  4643. */
  4644. Item.prototype.repaint = function repaint() {
  4645. // should be implemented by the item
  4646. return false;
  4647. };
  4648. /**
  4649. * Reflow the item
  4650. * @return {Boolean} resized
  4651. */
  4652. Item.prototype.reflow = function reflow() {
  4653. // should be implemented by the item
  4654. return false;
  4655. };
  4656. /**
  4657. * @constructor ItemBox
  4658. * @extends Item
  4659. * @param {ItemSet} parent
  4660. * @param {Object} data Object containing parameters start
  4661. * content, className.
  4662. * @param {Object} [options] Options to set initial property values
  4663. * @param {Object} [defaultOptions] default options
  4664. * // TODO: describe available options
  4665. */
  4666. function ItemBox (parent, data, options, defaultOptions) {
  4667. this.props = {
  4668. dot: {
  4669. left: 0,
  4670. top: 0,
  4671. width: 0,
  4672. height: 0
  4673. },
  4674. line: {
  4675. top: 0,
  4676. left: 0,
  4677. width: 0,
  4678. height: 0
  4679. }
  4680. };
  4681. Item.call(this, parent, data, options, defaultOptions);
  4682. }
  4683. ItemBox.prototype = new Item (null, null);
  4684. /**
  4685. * Select the item
  4686. * @override
  4687. */
  4688. ItemBox.prototype.select = function select() {
  4689. this.selected = true;
  4690. // TODO: select and unselect
  4691. };
  4692. /**
  4693. * Unselect the item
  4694. * @override
  4695. */
  4696. ItemBox.prototype.unselect = function unselect() {
  4697. this.selected = false;
  4698. // TODO: select and unselect
  4699. };
  4700. /**
  4701. * Repaint the item
  4702. * @return {Boolean} changed
  4703. */
  4704. ItemBox.prototype.repaint = function repaint() {
  4705. // TODO: make an efficient repaint
  4706. var changed = false;
  4707. var dom = this.dom;
  4708. if (!dom) {
  4709. this._create();
  4710. dom = this.dom;
  4711. changed = true;
  4712. }
  4713. if (dom) {
  4714. if (!this.parent) {
  4715. throw new Error('Cannot repaint item: no parent attached');
  4716. }
  4717. var foreground = this.parent.getForeground();
  4718. if (!foreground) {
  4719. throw new Error('Cannot repaint time axis: ' +
  4720. 'parent has no foreground container element');
  4721. }
  4722. var background = this.parent.getBackground();
  4723. if (!background) {
  4724. throw new Error('Cannot repaint time axis: ' +
  4725. 'parent has no background container element');
  4726. }
  4727. var axis = this.parent.getAxis();
  4728. if (!background) {
  4729. throw new Error('Cannot repaint time axis: ' +
  4730. 'parent has no axis container element');
  4731. }
  4732. if (!dom.box.parentNode) {
  4733. foreground.appendChild(dom.box);
  4734. changed = true;
  4735. }
  4736. if (!dom.line.parentNode) {
  4737. background.appendChild(dom.line);
  4738. changed = true;
  4739. }
  4740. if (!dom.dot.parentNode) {
  4741. axis.appendChild(dom.dot);
  4742. changed = true;
  4743. }
  4744. // update contents
  4745. if (this.data.content != this.content) {
  4746. this.content = this.data.content;
  4747. if (this.content instanceof Element) {
  4748. dom.content.innerHTML = '';
  4749. dom.content.appendChild(this.content);
  4750. }
  4751. else if (this.data.content != undefined) {
  4752. dom.content.innerHTML = this.content;
  4753. }
  4754. else {
  4755. throw new Error('Property "content" missing in item ' + this.data.id);
  4756. }
  4757. changed = true;
  4758. }
  4759. // update class
  4760. var className = (this.data.className? ' ' + this.data.className : '') +
  4761. (this.selected ? ' selected' : '');
  4762. if (this.className != className) {
  4763. this.className = className;
  4764. dom.box.className = 'item box' + className;
  4765. dom.line.className = 'item line' + className;
  4766. dom.dot.className = 'item dot' + className;
  4767. changed = true;
  4768. }
  4769. }
  4770. return changed;
  4771. };
  4772. /**
  4773. * Show the item in the DOM (when not already visible). The items DOM will
  4774. * be created when needed.
  4775. * @return {Boolean} changed
  4776. */
  4777. ItemBox.prototype.show = function show() {
  4778. if (!this.dom || !this.dom.box.parentNode) {
  4779. return this.repaint();
  4780. }
  4781. else {
  4782. return false;
  4783. }
  4784. };
  4785. /**
  4786. * Hide the item from the DOM (when visible)
  4787. * @return {Boolean} changed
  4788. */
  4789. ItemBox.prototype.hide = function hide() {
  4790. var changed = false,
  4791. dom = this.dom;
  4792. if (dom) {
  4793. if (dom.box.parentNode) {
  4794. dom.box.parentNode.removeChild(dom.box);
  4795. changed = true;
  4796. }
  4797. if (dom.line.parentNode) {
  4798. dom.line.parentNode.removeChild(dom.line);
  4799. }
  4800. if (dom.dot.parentNode) {
  4801. dom.dot.parentNode.removeChild(dom.dot);
  4802. }
  4803. }
  4804. return changed;
  4805. };
  4806. /**
  4807. * Reflow the item: calculate its actual size and position from the DOM
  4808. * @return {boolean} resized returns true if the axis is resized
  4809. * @override
  4810. */
  4811. ItemBox.prototype.reflow = function reflow() {
  4812. var changed = 0,
  4813. update,
  4814. dom,
  4815. props,
  4816. options,
  4817. margin,
  4818. start,
  4819. align,
  4820. orientation,
  4821. top,
  4822. left,
  4823. data,
  4824. range;
  4825. if (this.data.start == undefined) {
  4826. throw new Error('Property "start" missing in item ' + this.data.id);
  4827. }
  4828. data = this.data;
  4829. range = this.parent && this.parent.range;
  4830. if (data && range) {
  4831. // TODO: account for the width of the item
  4832. var interval = (range.end - range.start);
  4833. this.visible = (data.start > range.start - interval) && (data.start < range.end + interval);
  4834. }
  4835. else {
  4836. this.visible = false;
  4837. }
  4838. if (this.visible) {
  4839. dom = this.dom;
  4840. if (dom) {
  4841. update = util.updateProperty;
  4842. props = this.props;
  4843. options = this.options;
  4844. start = this.parent.toScreen(this.data.start);
  4845. align = options.align || this.defaultOptions.align;
  4846. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  4847. orientation = options.orientation || this.defaultOptions.orientation;
  4848. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  4849. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  4850. changed += update(props.line, 'width', dom.line.offsetWidth);
  4851. changed += update(props.line, 'height', dom.line.offsetHeight);
  4852. changed += update(props.line, 'top', dom.line.offsetTop);
  4853. changed += update(this, 'width', dom.box.offsetWidth);
  4854. changed += update(this, 'height', dom.box.offsetHeight);
  4855. if (align == 'right') {
  4856. left = start - this.width;
  4857. }
  4858. else if (align == 'left') {
  4859. left = start;
  4860. }
  4861. else {
  4862. // default or 'center'
  4863. left = start - this.width / 2;
  4864. }
  4865. changed += update(this, 'left', left);
  4866. changed += update(props.line, 'left', start - props.line.width / 2);
  4867. changed += update(props.dot, 'left', start - props.dot.width / 2);
  4868. changed += update(props.dot, 'top', -props.dot.height / 2);
  4869. if (orientation == 'top') {
  4870. top = margin;
  4871. changed += update(this, 'top', top);
  4872. }
  4873. else {
  4874. // default or 'bottom'
  4875. var parentHeight = this.parent.height;
  4876. top = parentHeight - this.height - margin;
  4877. changed += update(this, 'top', top);
  4878. }
  4879. }
  4880. else {
  4881. changed += 1;
  4882. }
  4883. }
  4884. return (changed > 0);
  4885. };
  4886. /**
  4887. * Create an items DOM
  4888. * @private
  4889. */
  4890. ItemBox.prototype._create = function _create() {
  4891. var dom = this.dom;
  4892. if (!dom) {
  4893. this.dom = dom = {};
  4894. // create the box
  4895. dom.box = document.createElement('DIV');
  4896. // className is updated in repaint()
  4897. // contents box (inside the background box). used for making margins
  4898. dom.content = document.createElement('DIV');
  4899. dom.content.className = 'content';
  4900. dom.box.appendChild(dom.content);
  4901. // line to axis
  4902. dom.line = document.createElement('DIV');
  4903. dom.line.className = 'line';
  4904. // dot on axis
  4905. dom.dot = document.createElement('DIV');
  4906. dom.dot.className = 'dot';
  4907. }
  4908. };
  4909. /**
  4910. * Reposition the item, recalculate its left, top, and width, using the current
  4911. * range and size of the items itemset
  4912. * @override
  4913. */
  4914. ItemBox.prototype.reposition = function reposition() {
  4915. var dom = this.dom,
  4916. props = this.props,
  4917. orientation = this.options.orientation || this.defaultOptions.orientation;
  4918. if (dom) {
  4919. var box = dom.box,
  4920. line = dom.line,
  4921. dot = dom.dot;
  4922. box.style.left = this.left + 'px';
  4923. box.style.top = this.top + 'px';
  4924. line.style.left = props.line.left + 'px';
  4925. if (orientation == 'top') {
  4926. line.style.top = 0 + 'px';
  4927. line.style.height = this.top + 'px';
  4928. }
  4929. else {
  4930. // orientation 'bottom'
  4931. line.style.top = (this.top + this.height) + 'px';
  4932. line.style.height = Math.max(this.parent.height - this.top - this.height +
  4933. this.props.dot.height / 2, 0) + 'px';
  4934. }
  4935. dot.style.left = props.dot.left + 'px';
  4936. dot.style.top = props.dot.top + 'px';
  4937. }
  4938. };
  4939. /**
  4940. * @constructor ItemPoint
  4941. * @extends Item
  4942. * @param {ItemSet} parent
  4943. * @param {Object} data Object containing parameters start
  4944. * content, className.
  4945. * @param {Object} [options] Options to set initial property values
  4946. * @param {Object} [defaultOptions] default options
  4947. * // TODO: describe available options
  4948. */
  4949. function ItemPoint (parent, data, options, defaultOptions) {
  4950. this.props = {
  4951. dot: {
  4952. top: 0,
  4953. width: 0,
  4954. height: 0
  4955. },
  4956. content: {
  4957. height: 0,
  4958. marginLeft: 0
  4959. }
  4960. };
  4961. Item.call(this, parent, data, options, defaultOptions);
  4962. }
  4963. ItemPoint.prototype = new Item (null, null);
  4964. /**
  4965. * Select the item
  4966. * @override
  4967. */
  4968. ItemPoint.prototype.select = function select() {
  4969. this.selected = true;
  4970. // TODO: select and unselect
  4971. };
  4972. /**
  4973. * Unselect the item
  4974. * @override
  4975. */
  4976. ItemPoint.prototype.unselect = function unselect() {
  4977. this.selected = false;
  4978. // TODO: select and unselect
  4979. };
  4980. /**
  4981. * Repaint the item
  4982. * @return {Boolean} changed
  4983. */
  4984. ItemPoint.prototype.repaint = function repaint() {
  4985. // TODO: make an efficient repaint
  4986. var changed = false;
  4987. var dom = this.dom;
  4988. if (!dom) {
  4989. this._create();
  4990. dom = this.dom;
  4991. changed = true;
  4992. }
  4993. if (dom) {
  4994. if (!this.parent) {
  4995. throw new Error('Cannot repaint item: no parent attached');
  4996. }
  4997. var foreground = this.parent.getForeground();
  4998. if (!foreground) {
  4999. throw new Error('Cannot repaint time axis: ' +
  5000. 'parent has no foreground container element');
  5001. }
  5002. if (!dom.point.parentNode) {
  5003. foreground.appendChild(dom.point);
  5004. foreground.appendChild(dom.point);
  5005. changed = true;
  5006. }
  5007. // update contents
  5008. if (this.data.content != this.content) {
  5009. this.content = this.data.content;
  5010. if (this.content instanceof Element) {
  5011. dom.content.innerHTML = '';
  5012. dom.content.appendChild(this.content);
  5013. }
  5014. else if (this.data.content != undefined) {
  5015. dom.content.innerHTML = this.content;
  5016. }
  5017. else {
  5018. throw new Error('Property "content" missing in item ' + this.data.id);
  5019. }
  5020. changed = true;
  5021. }
  5022. // update class
  5023. var className = (this.data.className? ' ' + this.data.className : '') +
  5024. (this.selected ? ' selected' : '');
  5025. if (this.className != className) {
  5026. this.className = className;
  5027. dom.point.className = 'item point' + className;
  5028. changed = true;
  5029. }
  5030. }
  5031. return changed;
  5032. };
  5033. /**
  5034. * Show the item in the DOM (when not already visible). The items DOM will
  5035. * be created when needed.
  5036. * @return {Boolean} changed
  5037. */
  5038. ItemPoint.prototype.show = function show() {
  5039. if (!this.dom || !this.dom.point.parentNode) {
  5040. return this.repaint();
  5041. }
  5042. else {
  5043. return false;
  5044. }
  5045. };
  5046. /**
  5047. * Hide the item from the DOM (when visible)
  5048. * @return {Boolean} changed
  5049. */
  5050. ItemPoint.prototype.hide = function hide() {
  5051. var changed = false,
  5052. dom = this.dom;
  5053. if (dom) {
  5054. if (dom.point.parentNode) {
  5055. dom.point.parentNode.removeChild(dom.point);
  5056. changed = true;
  5057. }
  5058. }
  5059. return changed;
  5060. };
  5061. /**
  5062. * Reflow the item: calculate its actual size from the DOM
  5063. * @return {boolean} resized returns true if the axis is resized
  5064. * @override
  5065. */
  5066. ItemPoint.prototype.reflow = function reflow() {
  5067. var changed = 0,
  5068. update,
  5069. dom,
  5070. props,
  5071. options,
  5072. margin,
  5073. orientation,
  5074. start,
  5075. top,
  5076. data,
  5077. range;
  5078. if (this.data.start == undefined) {
  5079. throw new Error('Property "start" missing in item ' + this.data.id);
  5080. }
  5081. data = this.data;
  5082. range = this.parent && this.parent.range;
  5083. if (data && range) {
  5084. // TODO: account for the width of the item
  5085. var interval = (range.end - range.start);
  5086. this.visible = (data.start > range.start - interval) && (data.start < range.end);
  5087. }
  5088. else {
  5089. this.visible = false;
  5090. }
  5091. if (this.visible) {
  5092. dom = this.dom;
  5093. if (dom) {
  5094. update = util.updateProperty;
  5095. props = this.props;
  5096. options = this.options;
  5097. orientation = options.orientation || this.defaultOptions.orientation;
  5098. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5099. start = this.parent.toScreen(this.data.start);
  5100. changed += update(this, 'width', dom.point.offsetWidth);
  5101. changed += update(this, 'height', dom.point.offsetHeight);
  5102. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5103. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5104. changed += update(props.content, 'height', dom.content.offsetHeight);
  5105. if (orientation == 'top') {
  5106. top = margin;
  5107. }
  5108. else {
  5109. // default or 'bottom'
  5110. var parentHeight = this.parent.height;
  5111. top = Math.max(parentHeight - this.height - margin, 0);
  5112. }
  5113. changed += update(this, 'top', top);
  5114. changed += update(this, 'left', start - props.dot.width / 2);
  5115. changed += update(props.content, 'marginLeft', 1.5 * props.dot.width);
  5116. //changed += update(props.content, 'marginRight', 0.5 * props.dot.width); // TODO
  5117. changed += update(props.dot, 'top', (this.height - props.dot.height) / 2);
  5118. }
  5119. else {
  5120. changed += 1;
  5121. }
  5122. }
  5123. return (changed > 0);
  5124. };
  5125. /**
  5126. * Create an items DOM
  5127. * @private
  5128. */
  5129. ItemPoint.prototype._create = function _create() {
  5130. var dom = this.dom;
  5131. if (!dom) {
  5132. this.dom = dom = {};
  5133. // background box
  5134. dom.point = document.createElement('div');
  5135. // className is updated in repaint()
  5136. // contents box, right from the dot
  5137. dom.content = document.createElement('div');
  5138. dom.content.className = 'content';
  5139. dom.point.appendChild(dom.content);
  5140. // dot at start
  5141. dom.dot = document.createElement('div');
  5142. dom.dot.className = 'dot';
  5143. dom.point.appendChild(dom.dot);
  5144. }
  5145. };
  5146. /**
  5147. * Reposition the item, recalculate its left, top, and width, using the current
  5148. * range and size of the items itemset
  5149. * @override
  5150. */
  5151. ItemPoint.prototype.reposition = function reposition() {
  5152. var dom = this.dom,
  5153. props = this.props;
  5154. if (dom) {
  5155. dom.point.style.top = this.top + 'px';
  5156. dom.point.style.left = this.left + 'px';
  5157. dom.content.style.marginLeft = props.content.marginLeft + 'px';
  5158. //dom.content.style.marginRight = props.content.marginRight + 'px'; // TODO
  5159. dom.dot.style.top = props.dot.top + 'px';
  5160. }
  5161. };
  5162. /**
  5163. * @constructor ItemRange
  5164. * @extends Item
  5165. * @param {ItemSet} parent
  5166. * @param {Object} data Object containing parameters start, end
  5167. * content, className.
  5168. * @param {Object} [options] Options to set initial property values
  5169. * @param {Object} [defaultOptions] default options
  5170. * // TODO: describe available options
  5171. */
  5172. function ItemRange (parent, data, options, defaultOptions) {
  5173. this.props = {
  5174. content: {
  5175. left: 0,
  5176. width: 0
  5177. }
  5178. };
  5179. Item.call(this, parent, data, options, defaultOptions);
  5180. }
  5181. ItemRange.prototype = new Item (null, null);
  5182. /**
  5183. * Select the item
  5184. * @override
  5185. */
  5186. ItemRange.prototype.select = function select() {
  5187. this.selected = true;
  5188. // TODO: select and unselect
  5189. };
  5190. /**
  5191. * Unselect the item
  5192. * @override
  5193. */
  5194. ItemRange.prototype.unselect = function unselect() {
  5195. this.selected = false;
  5196. // TODO: select and unselect
  5197. };
  5198. /**
  5199. * Repaint the item
  5200. * @return {Boolean} changed
  5201. */
  5202. ItemRange.prototype.repaint = function repaint() {
  5203. // TODO: make an efficient repaint
  5204. var changed = false;
  5205. var dom = this.dom;
  5206. if (!dom) {
  5207. this._create();
  5208. dom = this.dom;
  5209. changed = true;
  5210. }
  5211. if (dom) {
  5212. if (!this.parent) {
  5213. throw new Error('Cannot repaint item: no parent attached');
  5214. }
  5215. var foreground = this.parent.getForeground();
  5216. if (!foreground) {
  5217. throw new Error('Cannot repaint time axis: ' +
  5218. 'parent has no foreground container element');
  5219. }
  5220. if (!dom.box.parentNode) {
  5221. foreground.appendChild(dom.box);
  5222. changed = true;
  5223. }
  5224. // update content
  5225. if (this.data.content != this.content) {
  5226. this.content = this.data.content;
  5227. if (this.content instanceof Element) {
  5228. dom.content.innerHTML = '';
  5229. dom.content.appendChild(this.content);
  5230. }
  5231. else if (this.data.content != undefined) {
  5232. dom.content.innerHTML = this.content;
  5233. }
  5234. else {
  5235. throw new Error('Property "content" missing in item ' + this.data.id);
  5236. }
  5237. changed = true;
  5238. }
  5239. // update class
  5240. var className = this.data.className ? ('' + this.data.className) : '';
  5241. if (this.className != className) {
  5242. this.className = className;
  5243. dom.box.className = 'item range' + className;
  5244. changed = true;
  5245. }
  5246. }
  5247. return changed;
  5248. };
  5249. /**
  5250. * Show the item in the DOM (when not already visible). The items DOM will
  5251. * be created when needed.
  5252. * @return {Boolean} changed
  5253. */
  5254. ItemRange.prototype.show = function show() {
  5255. if (!this.dom || !this.dom.box.parentNode) {
  5256. return this.repaint();
  5257. }
  5258. else {
  5259. return false;
  5260. }
  5261. };
  5262. /**
  5263. * Hide the item from the DOM (when visible)
  5264. * @return {Boolean} changed
  5265. */
  5266. ItemRange.prototype.hide = function hide() {
  5267. var changed = false,
  5268. dom = this.dom;
  5269. if (dom) {
  5270. if (dom.box.parentNode) {
  5271. dom.box.parentNode.removeChild(dom.box);
  5272. changed = true;
  5273. }
  5274. }
  5275. return changed;
  5276. };
  5277. /**
  5278. * Reflow the item: calculate its actual size from the DOM
  5279. * @return {boolean} resized returns true if the axis is resized
  5280. * @override
  5281. */
  5282. ItemRange.prototype.reflow = function reflow() {
  5283. var changed = 0,
  5284. dom,
  5285. props,
  5286. options,
  5287. margin,
  5288. padding,
  5289. parent,
  5290. start,
  5291. end,
  5292. data,
  5293. range,
  5294. update,
  5295. box,
  5296. parentWidth,
  5297. contentLeft,
  5298. orientation,
  5299. top;
  5300. if (this.data.start == undefined) {
  5301. throw new Error('Property "start" missing in item ' + this.data.id);
  5302. }
  5303. if (this.data.end == undefined) {
  5304. throw new Error('Property "end" missing in item ' + this.data.id);
  5305. }
  5306. data = this.data;
  5307. range = this.parent && this.parent.range;
  5308. if (data && range) {
  5309. // TODO: account for the width of the item. Take some margin
  5310. this.visible = (data.start < range.end) && (data.end > range.start);
  5311. }
  5312. else {
  5313. this.visible = false;
  5314. }
  5315. if (this.visible) {
  5316. dom = this.dom;
  5317. if (dom) {
  5318. props = this.props;
  5319. options = this.options;
  5320. parent = this.parent;
  5321. start = parent.toScreen(this.data.start);
  5322. end = parent.toScreen(this.data.end);
  5323. update = util.updateProperty;
  5324. box = dom.box;
  5325. parentWidth = parent.width;
  5326. orientation = options.orientation || this.defaultOptions.orientation;
  5327. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5328. padding = options.padding || this.defaultOptions.padding;
  5329. changed += update(props.content, 'width', dom.content.offsetWidth);
  5330. changed += update(this, 'height', box.offsetHeight);
  5331. // limit the width of the this, as browsers cannot draw very wide divs
  5332. if (start < -parentWidth) {
  5333. start = -parentWidth;
  5334. }
  5335. if (end > 2 * parentWidth) {
  5336. end = 2 * parentWidth;
  5337. }
  5338. // when range exceeds left of the window, position the contents at the left of the visible area
  5339. if (start < 0) {
  5340. contentLeft = Math.min(-start,
  5341. (end - start - props.content.width - 2 * padding));
  5342. // TODO: remove the need for options.padding. it's terrible.
  5343. }
  5344. else {
  5345. contentLeft = 0;
  5346. }
  5347. changed += update(props.content, 'left', contentLeft);
  5348. if (orientation == 'top') {
  5349. top = margin;
  5350. changed += update(this, 'top', top);
  5351. }
  5352. else {
  5353. // default or 'bottom'
  5354. top = parent.height - this.height - margin;
  5355. changed += update(this, 'top', top);
  5356. }
  5357. changed += update(this, 'left', start);
  5358. changed += update(this, 'width', Math.max(end - start, 1)); // TODO: reckon with border width;
  5359. }
  5360. else {
  5361. changed += 1;
  5362. }
  5363. }
  5364. return (changed > 0);
  5365. };
  5366. /**
  5367. * Create an items DOM
  5368. * @private
  5369. */
  5370. ItemRange.prototype._create = function _create() {
  5371. var dom = this.dom;
  5372. if (!dom) {
  5373. this.dom = dom = {};
  5374. // background box
  5375. dom.box = document.createElement('div');
  5376. // className is updated in repaint()
  5377. // contents box
  5378. dom.content = document.createElement('div');
  5379. dom.content.className = 'content';
  5380. dom.box.appendChild(dom.content);
  5381. }
  5382. };
  5383. /**
  5384. * Reposition the item, recalculate its left, top, and width, using the current
  5385. * range and size of the items itemset
  5386. * @override
  5387. */
  5388. ItemRange.prototype.reposition = function reposition() {
  5389. var dom = this.dom,
  5390. props = this.props;
  5391. if (dom) {
  5392. dom.box.style.top = this.top + 'px';
  5393. dom.box.style.left = this.left + 'px';
  5394. dom.box.style.width = this.width + 'px';
  5395. dom.content.style.left = props.content.left + 'px';
  5396. }
  5397. };
  5398. /**
  5399. * @constructor Group
  5400. * @param {GroupSet} parent
  5401. * @param {Number | String} groupId
  5402. * @param {Object} [options] Options to set initial property values
  5403. * // TODO: describe available options
  5404. * @extends Component
  5405. */
  5406. function Group (parent, groupId, options) {
  5407. this.id = util.randomUUID();
  5408. this.parent = parent;
  5409. this.groupId = groupId;
  5410. this.itemsData = null; // DataSet
  5411. this.itemset = null; // ItemSet
  5412. this.options = options || {};
  5413. this.options.top = 0;
  5414. this.props = {
  5415. label: {
  5416. width: 0,
  5417. height: 0
  5418. }
  5419. };
  5420. this.top = 0;
  5421. this.left = 0;
  5422. this.width = 0;
  5423. this.height = 0;
  5424. }
  5425. Group.prototype = new Component();
  5426. // TODO: comment
  5427. Group.prototype.setOptions = Component.prototype.setOptions;
  5428. /**
  5429. * Get the container element of the panel, which can be used by a child to
  5430. * add its own widgets.
  5431. * @returns {HTMLElement} container
  5432. */
  5433. Group.prototype.getContainer = function () {
  5434. return this.parent.getContainer();
  5435. };
  5436. /**
  5437. * Set item set for the group. The group will create a view on the itemset,
  5438. * filtered by the groups id.
  5439. * @param {DataSet | DataView} items
  5440. */
  5441. Group.prototype.setItems = function setItems(items) {
  5442. if (this.itemset) {
  5443. // remove current item set
  5444. this.itemset.hide();
  5445. this.itemset.setItems();
  5446. this.parent.controller.remove(this.itemset);
  5447. this.itemset = null;
  5448. }
  5449. if (items) {
  5450. var groupId = this.groupId;
  5451. var itemsetOptions = Object.create(this.options);
  5452. this.itemset = new ItemSet(this, null, itemsetOptions);
  5453. this.itemset.setRange(this.parent.range);
  5454. this.view = new DataView(items, {
  5455. filter: function (item) {
  5456. return item.group == groupId;
  5457. }
  5458. });
  5459. this.itemset.setItems(this.view);
  5460. this.parent.controller.add(this.itemset);
  5461. }
  5462. };
  5463. /**
  5464. * Repaint the item
  5465. * @return {Boolean} changed
  5466. */
  5467. Group.prototype.repaint = function repaint() {
  5468. return false;
  5469. };
  5470. /**
  5471. * Reflow the item
  5472. * @return {Boolean} resized
  5473. */
  5474. Group.prototype.reflow = function reflow() {
  5475. var changed = 0,
  5476. update = util.updateProperty;
  5477. changed += update(this, 'top', this.itemset ? this.itemset.top : 0);
  5478. changed += update(this, 'height', this.itemset ? this.itemset.height : 0);
  5479. // TODO: reckon with the height of the group label
  5480. if (this.label) {
  5481. var inner = this.label.firstChild;
  5482. changed += update(this.props.label, 'width', inner.clientWidth);
  5483. changed += update(this.props.label, 'height', inner.clientHeight);
  5484. }
  5485. else {
  5486. changed += update(this.props.label, 'width', 0);
  5487. changed += update(this.props.label, 'height', 0);
  5488. }
  5489. return (changed > 0);
  5490. };
  5491. /**
  5492. * An GroupSet holds a set of groups
  5493. * @param {Component} parent
  5494. * @param {Component[]} [depends] Components on which this components depends
  5495. * (except for the parent)
  5496. * @param {Object} [options] See GroupSet.setOptions for the available
  5497. * options.
  5498. * @constructor GroupSet
  5499. * @extends Panel
  5500. */
  5501. function GroupSet(parent, depends, options) {
  5502. this.id = util.randomUUID();
  5503. this.parent = parent;
  5504. this.depends = depends;
  5505. this.options = options || {};
  5506. this.range = null; // Range or Object {start: number, end: number}
  5507. this.itemsData = null; // DataSet with items
  5508. this.groupsData = null; // DataSet with groups
  5509. this.groups = {}; // map with groups
  5510. this.dom = {};
  5511. this.props = {
  5512. labels: {
  5513. width: 0
  5514. }
  5515. };
  5516. // TODO: implement right orientation of the labels
  5517. // changes in groups are queued key/value map containing id/action
  5518. this.queue = {};
  5519. var me = this;
  5520. this.listeners = {
  5521. 'add': function (event, params) {
  5522. me._onAdd(params.items);
  5523. },
  5524. 'update': function (event, params) {
  5525. me._onUpdate(params.items);
  5526. },
  5527. 'remove': function (event, params) {
  5528. me._onRemove(params.items);
  5529. }
  5530. };
  5531. }
  5532. GroupSet.prototype = new Panel();
  5533. /**
  5534. * Set options for the GroupSet. Existing options will be extended/overwritten.
  5535. * @param {Object} [options] The following options are available:
  5536. * {String | function} groupsOrder
  5537. * TODO: describe options
  5538. */
  5539. GroupSet.prototype.setOptions = Component.prototype.setOptions;
  5540. GroupSet.prototype.setRange = function (range) {
  5541. // TODO: implement setRange
  5542. };
  5543. /**
  5544. * Set items
  5545. * @param {vis.DataSet | null} items
  5546. */
  5547. GroupSet.prototype.setItems = function setItems(items) {
  5548. this.itemsData = items;
  5549. for (var id in this.groups) {
  5550. if (this.groups.hasOwnProperty(id)) {
  5551. var group = this.groups[id];
  5552. group.setItems(items);
  5553. }
  5554. }
  5555. };
  5556. /**
  5557. * Get items
  5558. * @return {vis.DataSet | null} items
  5559. */
  5560. GroupSet.prototype.getItems = function getItems() {
  5561. return this.itemsData;
  5562. };
  5563. /**
  5564. * Set range (start and end).
  5565. * @param {Range | Object} range A Range or an object containing start and end.
  5566. */
  5567. GroupSet.prototype.setRange = function setRange(range) {
  5568. this.range = range;
  5569. };
  5570. /**
  5571. * Set groups
  5572. * @param {vis.DataSet} groups
  5573. */
  5574. GroupSet.prototype.setGroups = function setGroups(groups) {
  5575. var me = this,
  5576. ids;
  5577. // unsubscribe from current dataset
  5578. if (this.groupsData) {
  5579. util.forEach(this.listeners, function (callback, event) {
  5580. me.groupsData.unsubscribe(event, callback);
  5581. });
  5582. // remove all drawn groups
  5583. ids = this.groupsData.getIds();
  5584. this._onRemove(ids);
  5585. }
  5586. // replace the dataset
  5587. if (!groups) {
  5588. this.groupsData = null;
  5589. }
  5590. else if (groups instanceof DataSet) {
  5591. this.groupsData = groups;
  5592. }
  5593. else {
  5594. this.groupsData = new DataSet({
  5595. fieldTypes: {
  5596. start: 'Date',
  5597. end: 'Date'
  5598. }
  5599. });
  5600. this.groupsData.add(groups);
  5601. }
  5602. if (this.groupsData) {
  5603. // subscribe to new dataset
  5604. var id = this.id;
  5605. util.forEach(this.listeners, function (callback, event) {
  5606. me.groupsData.subscribe(event, callback, id);
  5607. });
  5608. // draw all new groups
  5609. ids = this.groupsData.getIds();
  5610. this._onAdd(ids);
  5611. }
  5612. };
  5613. /**
  5614. * Get groups
  5615. * @return {vis.DataSet | null} groups
  5616. */
  5617. GroupSet.prototype.getGroups = function getGroups() {
  5618. return this.groupsData;
  5619. };
  5620. /**
  5621. * Repaint the component
  5622. * @return {Boolean} changed
  5623. */
  5624. GroupSet.prototype.repaint = function repaint() {
  5625. var changed = 0,
  5626. i, id, group, label,
  5627. update = util.updateProperty,
  5628. asSize = util.option.asSize,
  5629. asElement = util.option.asElement,
  5630. options = this.options,
  5631. frame = this.dom.frame,
  5632. labels = this.dom.labels;
  5633. // create frame
  5634. if (!this.parent) {
  5635. throw new Error('Cannot repaint groupset: no parent attached');
  5636. }
  5637. var parentContainer = this.parent.getContainer();
  5638. if (!parentContainer) {
  5639. throw new Error('Cannot repaint groupset: parent has no container element');
  5640. }
  5641. if (!frame) {
  5642. frame = document.createElement('div');
  5643. frame.className = 'groupset';
  5644. this.dom.frame = frame;
  5645. var className = options.className;
  5646. if (className) {
  5647. util.addClassName(frame, util.option.asString(className));
  5648. }
  5649. changed += 1;
  5650. }
  5651. if (!frame.parentNode) {
  5652. parentContainer.appendChild(frame);
  5653. changed += 1;
  5654. }
  5655. // create labels
  5656. var labelContainer = asElement(options.labelContainer);
  5657. if (!labelContainer) {
  5658. throw new Error('Cannot repaint groupset: option "labelContainer" not defined');
  5659. }
  5660. if (!labels) {
  5661. labels = document.createElement('div');
  5662. labels.className = 'labels';
  5663. //frame.appendChild(labels);
  5664. this.dom.labels = labels;
  5665. }
  5666. if (!labels.parentNode || labels.parentNode != labelContainer) {
  5667. if (labels.parentNode) {
  5668. labels.parentNode.removeChild(labels.parentNode);
  5669. }
  5670. labelContainer.appendChild(labels);
  5671. }
  5672. // reposition frame
  5673. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  5674. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  5675. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  5676. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  5677. // reposition labels
  5678. changed += update(labels.style, 'top', asSize(options.top, '0px'));
  5679. var me = this,
  5680. queue = this.queue,
  5681. groups = this.groups,
  5682. groupsData = this.groupsData;
  5683. // show/hide added/changed/removed groups
  5684. var ids = Object.keys(queue);
  5685. if (ids.length) {
  5686. ids.forEach(function (id) {
  5687. var action = queue[id];
  5688. var group = groups[id];
  5689. //noinspection FallthroughInSwitchStatementJS
  5690. switch (action) {
  5691. case 'add':
  5692. case 'update':
  5693. if (!group) {
  5694. var groupOptions = Object.create(me.options);
  5695. group = new Group(me, id, groupOptions);
  5696. group.setItems(me.itemsData); // attach items data
  5697. groups[id] = group;
  5698. me.controller.add(group);
  5699. }
  5700. // TODO: update group data
  5701. group.data = groupsData.get(id);
  5702. delete queue[id];
  5703. break;
  5704. case 'remove':
  5705. if (group) {
  5706. group.setItems(); // detach items data
  5707. delete groups[id];
  5708. me.controller.remove(group);
  5709. }
  5710. // update lists
  5711. delete queue[id];
  5712. break;
  5713. default:
  5714. console.log('Error: unknown action "' + action + '"');
  5715. }
  5716. });
  5717. // the groupset depends on each of the groups
  5718. //this.depends = this.groups; // TODO: gives a circular reference through the parent
  5719. // TODO: apply dependencies of the groupset
  5720. // update the top positions of the groups in the correct order
  5721. var orderedGroups = this.groupsData.getIds({
  5722. order: this.options.groupsOrder
  5723. });
  5724. for (i = 0; i < orderedGroups.length; i++) {
  5725. (function (group, prevGroup) {
  5726. var top = 0;
  5727. if (prevGroup) {
  5728. top = function () {
  5729. // TODO: top must reckon with options.maxHeight
  5730. return prevGroup.top + prevGroup.height;
  5731. }
  5732. }
  5733. group.setOptions({
  5734. top: top
  5735. });
  5736. })(groups[orderedGroups[i]], groups[orderedGroups[i - 1]]);
  5737. }
  5738. // (re)create the labels
  5739. while (labels.firstChild) {
  5740. labels.removeChild(labels.firstChild);
  5741. }
  5742. for (i = 0; i < orderedGroups.length; i++) {
  5743. id = orderedGroups[i];
  5744. label = this._createLabel(id);
  5745. labels.appendChild(label);
  5746. }
  5747. changed++;
  5748. }
  5749. // reposition the labels
  5750. // TODO: labels are not displayed correctly when orientation=='top'
  5751. // TODO: width of labelPanel is not immediately updated on a change in groups
  5752. for (id in groups) {
  5753. if (groups.hasOwnProperty(id)) {
  5754. group = groups[id];
  5755. label = group.label;
  5756. if (label) {
  5757. label.style.top = group.top + 'px';
  5758. label.style.height = group.height + 'px';
  5759. }
  5760. }
  5761. }
  5762. return (changed > 0);
  5763. };
  5764. /**
  5765. * Create a label for group with given id
  5766. * @param {Number} id
  5767. * @return {Element} label
  5768. * @private
  5769. */
  5770. GroupSet.prototype._createLabel = function(id) {
  5771. var group = this.groups[id];
  5772. var label = document.createElement('div');
  5773. label.className = 'label';
  5774. var inner = document.createElement('div');
  5775. inner.className = 'inner';
  5776. label.appendChild(inner);
  5777. var content = group.data && group.data.content;
  5778. if (content instanceof Element) {
  5779. inner.appendChild(content);
  5780. }
  5781. else if (content != undefined) {
  5782. inner.innerHTML = content;
  5783. }
  5784. var className = group.data && group.data.className;
  5785. if (className) {
  5786. util.addClassName(label, className);
  5787. }
  5788. group.label = label; // TODO: not so nice, parking labels in the group this way!!!
  5789. return label;
  5790. };
  5791. /**
  5792. * Get container element
  5793. * @return {HTMLElement} container
  5794. */
  5795. GroupSet.prototype.getContainer = function getContainer() {
  5796. return this.dom.frame;
  5797. };
  5798. /**
  5799. * Get the width of the group labels
  5800. * @return {Number} width
  5801. */
  5802. GroupSet.prototype.getLabelsWidth = function getContainer() {
  5803. return this.props.labels.width;
  5804. };
  5805. /**
  5806. * Reflow the component
  5807. * @return {Boolean} resized
  5808. */
  5809. GroupSet.prototype.reflow = function reflow() {
  5810. var changed = 0,
  5811. id, group,
  5812. options = this.options,
  5813. update = util.updateProperty,
  5814. asNumber = util.option.asNumber,
  5815. asSize = util.option.asSize,
  5816. frame = this.dom.frame;
  5817. if (frame) {
  5818. var maxHeight = asNumber(options.maxHeight);
  5819. var fixedHeight = (asSize(options.height) != null);
  5820. var height;
  5821. if (fixedHeight) {
  5822. height = frame.offsetHeight;
  5823. }
  5824. else {
  5825. // height is not specified, calculate the sum of the height of all groups
  5826. height = 0;
  5827. for (id in this.groups) {
  5828. if (this.groups.hasOwnProperty(id)) {
  5829. group = this.groups[id];
  5830. height += group.height;
  5831. }
  5832. }
  5833. }
  5834. if (maxHeight != null) {
  5835. height = Math.min(height, maxHeight);
  5836. }
  5837. changed += update(this, 'height', height);
  5838. changed += update(this, 'top', frame.offsetTop);
  5839. changed += update(this, 'left', frame.offsetLeft);
  5840. changed += update(this, 'width', frame.offsetWidth);
  5841. }
  5842. // calculate the maximum width of the labels
  5843. var width = 0;
  5844. for (id in this.groups) {
  5845. if (this.groups.hasOwnProperty(id)) {
  5846. group = this.groups[id];
  5847. var labelWidth = group.props && group.props.label && group.props.label.width || 0;
  5848. width = Math.max(width, labelWidth);
  5849. }
  5850. }
  5851. changed += update(this.props.labels, 'width', width);
  5852. return (changed > 0);
  5853. };
  5854. /**
  5855. * Hide the component from the DOM
  5856. * @return {Boolean} changed
  5857. */
  5858. GroupSet.prototype.hide = function hide() {
  5859. if (this.dom.frame && this.dom.frame.parentNode) {
  5860. this.dom.frame.parentNode.removeChild(this.dom.frame);
  5861. return true;
  5862. }
  5863. else {
  5864. return false;
  5865. }
  5866. };
  5867. /**
  5868. * Show the component in the DOM (when not already visible).
  5869. * A repaint will be executed when the component is not visible
  5870. * @return {Boolean} changed
  5871. */
  5872. GroupSet.prototype.show = function show() {
  5873. if (!this.dom.frame || !this.dom.frame.parentNode) {
  5874. return this.repaint();
  5875. }
  5876. else {
  5877. return false;
  5878. }
  5879. };
  5880. /**
  5881. * Handle updated groups
  5882. * @param {Number[]} ids
  5883. * @private
  5884. */
  5885. GroupSet.prototype._onUpdate = function _onUpdate(ids) {
  5886. this._toQueue(ids, 'update');
  5887. };
  5888. /**
  5889. * Handle changed groups
  5890. * @param {Number[]} ids
  5891. * @private
  5892. */
  5893. GroupSet.prototype._onAdd = function _onAdd(ids) {
  5894. this._toQueue(ids, 'add');
  5895. };
  5896. /**
  5897. * Handle removed groups
  5898. * @param {Number[]} ids
  5899. * @private
  5900. */
  5901. GroupSet.prototype._onRemove = function _onRemove(ids) {
  5902. this._toQueue(ids, 'remove');
  5903. };
  5904. /**
  5905. * Put groups in the queue to be added/updated/remove
  5906. * @param {Number[]} ids
  5907. * @param {String} action can be 'add', 'update', 'remove'
  5908. */
  5909. GroupSet.prototype._toQueue = function _toQueue(ids, action) {
  5910. var queue = this.queue;
  5911. ids.forEach(function (id) {
  5912. queue[id] = action;
  5913. });
  5914. if (this.controller) {
  5915. //this.requestReflow();
  5916. this.requestRepaint();
  5917. }
  5918. };
  5919. /**
  5920. * Create a timeline visualization
  5921. * @param {HTMLElement} container
  5922. * @param {vis.DataSet | Array | DataTable} [items]
  5923. * @param {Object} [options] See Timeline.setOptions for the available options.
  5924. * @constructor
  5925. */
  5926. function Timeline (container, items, options) {
  5927. var me = this;
  5928. this.options = util.extend({
  5929. orientation: 'bottom',
  5930. min: null,
  5931. max: null,
  5932. zoomMin: 10, // milliseconds
  5933. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  5934. // moveable: true, // TODO: option moveable
  5935. // zoomable: true, // TODO: option zoomable
  5936. showMinorLabels: true,
  5937. showMajorLabels: true,
  5938. autoResize: false
  5939. }, options);
  5940. // controller
  5941. this.controller = new Controller();
  5942. // root panel
  5943. if (!container) {
  5944. throw new Error('No container element provided');
  5945. }
  5946. var rootOptions = Object.create(this.options);
  5947. rootOptions.height = function () {
  5948. if (me.options.height) {
  5949. // fixed height
  5950. return me.options.height;
  5951. }
  5952. else {
  5953. // auto height
  5954. return me.timeaxis.height + me.content.height;
  5955. }
  5956. };
  5957. this.rootPanel = new RootPanel(container, rootOptions);
  5958. this.controller.add(this.rootPanel);
  5959. // item panel
  5960. var itemOptions = Object.create(this.options);
  5961. itemOptions.left = function () {
  5962. return me.labelPanel.width;
  5963. };
  5964. itemOptions.width = function () {
  5965. return me.rootPanel.width - me.labelPanel.width;
  5966. };
  5967. itemOptions.top = null;
  5968. itemOptions.height = null;
  5969. this.itemPanel = new Panel(this.rootPanel, [], itemOptions);
  5970. this.controller.add(this.itemPanel);
  5971. // label panel
  5972. var labelOptions = Object.create(this.options);
  5973. labelOptions.top = null;
  5974. labelOptions.left = null;
  5975. labelOptions.height = null;
  5976. labelOptions.width = function () {
  5977. if (me.content && typeof me.content.getLabelsWidth === 'function') {
  5978. return me.content.getLabelsWidth();
  5979. }
  5980. else {
  5981. return 0;
  5982. }
  5983. };
  5984. this.labelPanel = new Panel(this.rootPanel, [], labelOptions);
  5985. this.controller.add(this.labelPanel);
  5986. // range
  5987. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  5988. this.range = new Range({
  5989. start: now.clone().add('days', -3).valueOf(),
  5990. end: now.clone().add('days', 4).valueOf()
  5991. });
  5992. // TODO: reckon with options moveable and zoomable
  5993. this.range.subscribe(this.rootPanel, 'move', 'horizontal');
  5994. this.range.subscribe(this.rootPanel, 'zoom', 'horizontal');
  5995. this.range.on('rangechange', function () {
  5996. var force = true;
  5997. me.controller.requestReflow(force);
  5998. });
  5999. this.range.on('rangechanged', function () {
  6000. var force = true;
  6001. me.controller.requestReflow(force);
  6002. });
  6003. // TODO: put the listeners in setOptions, be able to dynamically change with options moveable and zoomable
  6004. // time axis
  6005. var timeaxisOptions = Object.create(rootOptions);
  6006. timeaxisOptions.range = this.range;
  6007. timeaxisOptions.left = null;
  6008. timeaxisOptions.top = null;
  6009. timeaxisOptions.width = '100%';
  6010. timeaxisOptions.height = null;
  6011. this.timeaxis = new TimeAxis(this.itemPanel, [], timeaxisOptions);
  6012. this.timeaxis.setRange(this.range);
  6013. this.controller.add(this.timeaxis);
  6014. // create itemset or groupset
  6015. this.setGroups(null);
  6016. this.itemsData = null; // DataSet
  6017. this.groupsData = null; // DataSet
  6018. // set data
  6019. if (items) {
  6020. this.setItems(items);
  6021. }
  6022. }
  6023. /**
  6024. * Set options
  6025. * @param {Object} options TODO: describe the available options
  6026. */
  6027. Timeline.prototype.setOptions = function (options) {
  6028. if (options) {
  6029. util.extend(this.options, options);
  6030. }
  6031. this.controller.reflow();
  6032. this.controller.repaint();
  6033. };
  6034. /**
  6035. * Set items
  6036. * @param {vis.DataSet | Array | DataTable | null} items
  6037. */
  6038. Timeline.prototype.setItems = function(items) {
  6039. var initialLoad = (this.itemsData == null);
  6040. // convert to type DataSet when needed
  6041. var newItemSet;
  6042. if (!items) {
  6043. newItemSet = null;
  6044. }
  6045. else if (items instanceof DataSet) {
  6046. newItemSet = items;
  6047. }
  6048. if (!(items instanceof DataSet)) {
  6049. newItemSet = new DataSet({
  6050. fieldTypes: {
  6051. start: 'Date',
  6052. end: 'Date'
  6053. }
  6054. });
  6055. newItemSet.add(items);
  6056. }
  6057. // set items
  6058. this.itemsData = newItemSet;
  6059. this.content.setItems(newItemSet);
  6060. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  6061. // apply the data range as range
  6062. var dataRange = this.getItemRange();
  6063. // add 5% on both sides
  6064. var min = dataRange.min;
  6065. var max = dataRange.max;
  6066. if (min != null && max != null) {
  6067. var interval = (max.valueOf() - min.valueOf());
  6068. min = new Date(min.valueOf() - interval * 0.05);
  6069. max = new Date(max.valueOf() + interval * 0.05);
  6070. }
  6071. // override specified start and/or end date
  6072. if (this.options.start != undefined) {
  6073. min = new Date(this.options.start.valueOf());
  6074. }
  6075. if (this.options.end != undefined) {
  6076. max = new Date(this.options.end.valueOf());
  6077. }
  6078. // apply range if there is a min or max available
  6079. if (min != null || max != null) {
  6080. this.range.setRange(min, max);
  6081. }
  6082. }
  6083. };
  6084. /**
  6085. * Set groups
  6086. * @param {vis.DataSet | Array | DataTable} groups
  6087. */
  6088. Timeline.prototype.setGroups = function(groups) {
  6089. var me = this;
  6090. this.groupsData = groups;
  6091. // switch content type between ItemSet or GroupSet when needed
  6092. var type = this.groupsData ? GroupSet : ItemSet;
  6093. if (!(this.content instanceof type)) {
  6094. // remove old content set
  6095. if (this.content) {
  6096. this.content.hide();
  6097. if (this.content.setItems) {
  6098. this.content.setItems(); // disconnect from items
  6099. }
  6100. if (this.content.setGroups) {
  6101. this.content.setGroups(); // disconnect from groups
  6102. }
  6103. this.controller.remove(this.content);
  6104. }
  6105. // create new content set
  6106. var options = Object.create(this.options);
  6107. util.extend(options, {
  6108. top: function () {
  6109. if (me.options.orientation == 'top') {
  6110. return me.timeaxis.height;
  6111. }
  6112. else {
  6113. return me.itemPanel.height - me.timeaxis.height - me.content.height;
  6114. }
  6115. },
  6116. left: null,
  6117. width: '100%',
  6118. height: function () {
  6119. if (me.options.height) {
  6120. return me.itemPanel.height - me.timeaxis.height;
  6121. }
  6122. else {
  6123. return null;
  6124. }
  6125. },
  6126. maxHeight: function () {
  6127. if (me.options.maxHeight) {
  6128. if (!util.isNumber(me.options.maxHeight)) {
  6129. throw new TypeError('Number expected for property maxHeight');
  6130. }
  6131. return me.options.maxHeight - me.timeaxis.height;
  6132. }
  6133. else {
  6134. return null;
  6135. }
  6136. },
  6137. labelContainer: function () {
  6138. return me.labelPanel.getContainer();
  6139. }
  6140. });
  6141. this.content = new type(this.itemPanel, [this.timeaxis], options);
  6142. if (this.content.setRange) {
  6143. this.content.setRange(this.range);
  6144. }
  6145. if (this.content.setItems) {
  6146. this.content.setItems(this.itemsData);
  6147. }
  6148. if (this.content.setGroups) {
  6149. this.content.setGroups(this.groupsData);
  6150. }
  6151. this.controller.add(this.content);
  6152. }
  6153. };
  6154. /**
  6155. * Get the data range of the item set.
  6156. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  6157. * When no minimum is found, min==null
  6158. * When no maximum is found, max==null
  6159. */
  6160. Timeline.prototype.getItemRange = function getItemRange() {
  6161. // calculate min from start filed
  6162. var itemsData = this.itemsData,
  6163. min = null,
  6164. max = null;
  6165. if (itemsData) {
  6166. // calculate the minimum value of the field 'start'
  6167. var minItem = itemsData.min('start');
  6168. min = minItem ? minItem.start.valueOf() : null;
  6169. // calculate maximum value of fields 'start' and 'end'
  6170. var maxStartItem = itemsData.max('start');
  6171. if (maxStartItem) {
  6172. max = maxStartItem.start.valueOf();
  6173. }
  6174. var maxEndItem = itemsData.max('end');
  6175. if (maxEndItem) {
  6176. if (max == null) {
  6177. max = maxEndItem.end.valueOf();
  6178. }
  6179. else {
  6180. max = Math.max(max, maxEndItem.end.valueOf());
  6181. }
  6182. }
  6183. }
  6184. return {
  6185. min: (min != null) ? new Date(min) : null,
  6186. max: (max != null) ? new Date(max) : null
  6187. };
  6188. };
  6189. (function(exports) {
  6190. /**
  6191. * Parse a text source containing data in DOT language into a JSON object.
  6192. * The object contains two lists: one with nodes and one with edges.
  6193. *
  6194. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  6195. *
  6196. * @param {String} data Text containing a graph in DOT-notation
  6197. * @return {Object} graph An object containing two parameters:
  6198. * {Object[]} nodes
  6199. * {Object[]} edges
  6200. */
  6201. function parseDOT (data) {
  6202. dot = data;
  6203. return parseGraph();
  6204. }
  6205. // token types enumeration
  6206. var TOKENTYPE = {
  6207. NULL : 0,
  6208. DELIMITER : 1,
  6209. IDENTIFIER: 2,
  6210. UNKNOWN : 3
  6211. };
  6212. // map with all delimiters
  6213. var DELIMITERS = {
  6214. '{': true,
  6215. '}': true,
  6216. '[': true,
  6217. ']': true,
  6218. ';': true,
  6219. '=': true,
  6220. ',': true,
  6221. '->': true,
  6222. '--': true
  6223. };
  6224. var dot = ''; // current dot file
  6225. var index = 0; // current index in dot file
  6226. var c = ''; // current token character in expr
  6227. var token = ''; // current token
  6228. var tokenType = TOKENTYPE.NULL; // type of the token
  6229. /**
  6230. * Get the first character from the dot file.
  6231. * The character is stored into the char c. If the end of the dot file is
  6232. * reached, the function puts an empty string in c.
  6233. */
  6234. function first() {
  6235. index = 0;
  6236. c = dot.charAt(0);
  6237. }
  6238. /**
  6239. * Get the next character from the dot file.
  6240. * The character is stored into the char c. If the end of the dot file is
  6241. * reached, the function puts an empty string in c.
  6242. */
  6243. function next() {
  6244. index++;
  6245. c = dot.charAt(index);
  6246. }
  6247. /**
  6248. * Preview the next character from the dot file.
  6249. * @return {String} cNext
  6250. */
  6251. function nextPreview() {
  6252. return dot.charAt(index + 1);
  6253. }
  6254. /**
  6255. * Test whether given character is alphabetic or numeric
  6256. * @param {String} c
  6257. * @return {Boolean} isAlphaNumeric
  6258. */
  6259. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  6260. function isAlphaNumeric(c) {
  6261. return regexAlphaNumeric.test(c);
  6262. }
  6263. /**
  6264. * Merge all properties of object b into object b
  6265. * @param {Object} a
  6266. * @param {Object} b
  6267. * @return {Object} a
  6268. */
  6269. function merge (a, b) {
  6270. if (!a) {
  6271. a = {};
  6272. }
  6273. if (b) {
  6274. for (var name in b) {
  6275. if (b.hasOwnProperty(name)) {
  6276. a[name] = b[name];
  6277. }
  6278. }
  6279. }
  6280. return a;
  6281. }
  6282. /**
  6283. * Set a value in an object, where the provided parameter name can be a
  6284. * path with nested parameters. For example:
  6285. *
  6286. * var obj = {a: 2};
  6287. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  6288. *
  6289. * @param {Object} obj
  6290. * @param {String} path A parameter name or dot-separated parameter path,
  6291. * like "color.highlight.border".
  6292. * @param {*} value
  6293. */
  6294. function setValue(obj, path, value) {
  6295. var keys = path.split('.');
  6296. var o = obj;
  6297. while (keys.length) {
  6298. var key = keys.shift();
  6299. if (keys.length) {
  6300. // this isn't the end point
  6301. if (!o[key]) {
  6302. o[key] = {};
  6303. }
  6304. o = o[key];
  6305. }
  6306. else {
  6307. // this is the end point
  6308. o[key] = value;
  6309. }
  6310. }
  6311. }
  6312. /**
  6313. * Add a node to a graph object. If there is already a node with
  6314. * the same id, their attributes will be merged.
  6315. * @param {Object} graph
  6316. * @param {Object} node
  6317. */
  6318. function addNode(graph, node) {
  6319. var i, len;
  6320. var current = null;
  6321. // find root graph (in case of subgraph)
  6322. var graphs = [graph]; // list with all graphs from current graph to root graph
  6323. var root = graph;
  6324. while (root.parent) {
  6325. graphs.push(root.parent);
  6326. root = root.parent;
  6327. }
  6328. // find existing node (at root level) by its id
  6329. if (root.nodes) {
  6330. for (i = 0, len = root.nodes.length; i < len; i++) {
  6331. if (node.id === root.nodes[i].id) {
  6332. current = root.nodes[i];
  6333. break;
  6334. }
  6335. }
  6336. }
  6337. if (!current) {
  6338. // this is a new node
  6339. current = {
  6340. id: node.id
  6341. };
  6342. if (graph.node) {
  6343. // clone default attributes
  6344. current.attr = merge(current.attr, graph.node);
  6345. }
  6346. }
  6347. // add node to this (sub)graph and all its parent graphs
  6348. for (i = graphs.length - 1; i >= 0; i--) {
  6349. var g = graphs[i];
  6350. if (!g.nodes) {
  6351. g.nodes = [];
  6352. }
  6353. if (g.nodes.indexOf(current) == -1) {
  6354. g.nodes.push(current);
  6355. }
  6356. }
  6357. // merge attributes
  6358. if (node.attr) {
  6359. current.attr = merge(current.attr, node.attr);
  6360. }
  6361. }
  6362. /**
  6363. * Add an edge to a graph object
  6364. * @param {Object} graph
  6365. * @param {Object} edge
  6366. */
  6367. function addEdge(graph, edge) {
  6368. if (!graph.edges) {
  6369. graph.edges = [];
  6370. }
  6371. graph.edges.push(edge);
  6372. if (graph.edge) {
  6373. var attr = merge({}, graph.edge); // clone default attributes
  6374. edge.attr = merge(attr, edge.attr); // merge attributes
  6375. }
  6376. }
  6377. /**
  6378. * Create an edge to a graph object
  6379. * @param {Object} graph
  6380. * @param {String | Number | Object} from
  6381. * @param {String | Number | Object} to
  6382. * @param {String} type
  6383. * @param {Object | null} attr
  6384. * @return {Object} edge
  6385. */
  6386. function createEdge(graph, from, to, type, attr) {
  6387. var edge = {
  6388. from: from,
  6389. to: to,
  6390. type: type
  6391. };
  6392. if (graph.edge) {
  6393. edge.attr = merge({}, graph.edge); // clone default attributes
  6394. }
  6395. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  6396. return edge;
  6397. }
  6398. /**
  6399. * Get next token in the current dot file.
  6400. * The token and token type are available as token and tokenType
  6401. */
  6402. function getToken() {
  6403. tokenType = TOKENTYPE.NULL;
  6404. token = '';
  6405. // skip over whitespaces
  6406. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  6407. next();
  6408. }
  6409. do {
  6410. var isComment = false;
  6411. // skip comment
  6412. if (c == '#') {
  6413. // find the previous non-space character
  6414. var i = index - 1;
  6415. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  6416. i--;
  6417. }
  6418. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  6419. // the # is at the start of a line, this is indeed a line comment
  6420. while (c != '' && c != '\n') {
  6421. next();
  6422. }
  6423. isComment = true;
  6424. }
  6425. }
  6426. if (c == '/' && nextPreview() == '/') {
  6427. // skip line comment
  6428. while (c != '' && c != '\n') {
  6429. next();
  6430. }
  6431. isComment = true;
  6432. }
  6433. if (c == '/' && nextPreview() == '*') {
  6434. // skip block comment
  6435. while (c != '') {
  6436. if (c == '*' && nextPreview() == '/') {
  6437. // end of block comment found. skip these last two characters
  6438. next();
  6439. next();
  6440. break;
  6441. }
  6442. else {
  6443. next();
  6444. }
  6445. }
  6446. isComment = true;
  6447. }
  6448. // skip over whitespaces
  6449. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  6450. next();
  6451. }
  6452. }
  6453. while (isComment);
  6454. // check for end of dot file
  6455. if (c == '') {
  6456. // token is still empty
  6457. tokenType = TOKENTYPE.DELIMITER;
  6458. return;
  6459. }
  6460. // check for delimiters consisting of 2 characters
  6461. var c2 = c + nextPreview();
  6462. if (DELIMITERS[c2]) {
  6463. tokenType = TOKENTYPE.DELIMITER;
  6464. token = c2;
  6465. next();
  6466. next();
  6467. return;
  6468. }
  6469. // check for delimiters consisting of 1 character
  6470. if (DELIMITERS[c]) {
  6471. tokenType = TOKENTYPE.DELIMITER;
  6472. token = c;
  6473. next();
  6474. return;
  6475. }
  6476. // check for an identifier (number or string)
  6477. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  6478. if (isAlphaNumeric(c) || c == '-') {
  6479. token += c;
  6480. next();
  6481. while (isAlphaNumeric(c)) {
  6482. token += c;
  6483. next();
  6484. }
  6485. if (token == 'false') {
  6486. token = false; // cast to boolean
  6487. }
  6488. else if (token == 'true') {
  6489. token = true; // cast to boolean
  6490. }
  6491. else if (!isNaN(Number(token))) {
  6492. token = Number(token); // cast to number
  6493. }
  6494. tokenType = TOKENTYPE.IDENTIFIER;
  6495. return;
  6496. }
  6497. // check for a string enclosed by double quotes
  6498. if (c == '"') {
  6499. next();
  6500. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  6501. token += c;
  6502. if (c == '"') { // skip the escape character
  6503. next();
  6504. }
  6505. next();
  6506. }
  6507. if (c != '"') {
  6508. throw newSyntaxError('End of string " expected');
  6509. }
  6510. next();
  6511. tokenType = TOKENTYPE.IDENTIFIER;
  6512. return;
  6513. }
  6514. // something unknown is found, wrong characters, a syntax error
  6515. tokenType = TOKENTYPE.UNKNOWN;
  6516. while (c != '') {
  6517. token += c;
  6518. next();
  6519. }
  6520. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  6521. }
  6522. /**
  6523. * Parse a graph.
  6524. * @returns {Object} graph
  6525. */
  6526. function parseGraph() {
  6527. var graph = {};
  6528. first();
  6529. getToken();
  6530. // optional strict keyword
  6531. if (token == 'strict') {
  6532. graph.strict = true;
  6533. getToken();
  6534. }
  6535. // graph or digraph keyword
  6536. if (token == 'graph' || token == 'digraph') {
  6537. graph.type = token;
  6538. getToken();
  6539. }
  6540. // optional graph id
  6541. if (tokenType == TOKENTYPE.IDENTIFIER) {
  6542. graph.id = token;
  6543. getToken();
  6544. }
  6545. // open angle bracket
  6546. if (token != '{') {
  6547. throw newSyntaxError('Angle bracket { expected');
  6548. }
  6549. getToken();
  6550. // statements
  6551. parseStatements(graph);
  6552. // close angle bracket
  6553. if (token != '}') {
  6554. throw newSyntaxError('Angle bracket } expected');
  6555. }
  6556. getToken();
  6557. // end of file
  6558. if (token !== '') {
  6559. throw newSyntaxError('End of file expected');
  6560. }
  6561. getToken();
  6562. // remove temporary default properties
  6563. delete graph.node;
  6564. delete graph.edge;
  6565. delete graph.graph;
  6566. return graph;
  6567. }
  6568. /**
  6569. * Parse a list with statements.
  6570. * @param {Object} graph
  6571. */
  6572. function parseStatements (graph) {
  6573. while (token !== '' && token != '}') {
  6574. parseStatement(graph);
  6575. if (token == ';') {
  6576. getToken();
  6577. }
  6578. }
  6579. }
  6580. /**
  6581. * Parse a single statement. Can be a an attribute statement, node
  6582. * statement, a series of node statements and edge statements, or a
  6583. * parameter.
  6584. * @param {Object} graph
  6585. */
  6586. function parseStatement(graph) {
  6587. // parse subgraph
  6588. var subgraph = parseSubgraph(graph);
  6589. if (subgraph) {
  6590. // edge statements
  6591. parseEdge(graph, subgraph);
  6592. return;
  6593. }
  6594. // parse an attribute statement
  6595. var attr = parseAttributeStatement(graph);
  6596. if (attr) {
  6597. return;
  6598. }
  6599. // parse node
  6600. if (tokenType != TOKENTYPE.IDENTIFIER) {
  6601. throw newSyntaxError('Identifier expected');
  6602. }
  6603. var id = token; // id can be a string or a number
  6604. getToken();
  6605. if (token == '=') {
  6606. // id statement
  6607. getToken();
  6608. if (tokenType != TOKENTYPE.IDENTIFIER) {
  6609. throw newSyntaxError('Identifier expected');
  6610. }
  6611. graph[id] = token;
  6612. getToken();
  6613. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  6614. }
  6615. else {
  6616. parseNodeStatement(graph, id);
  6617. }
  6618. }
  6619. /**
  6620. * Parse a subgraph
  6621. * @param {Object} graph parent graph object
  6622. * @return {Object | null} subgraph
  6623. */
  6624. function parseSubgraph (graph) {
  6625. var subgraph = null;
  6626. // optional subgraph keyword
  6627. if (token == 'subgraph') {
  6628. subgraph = {};
  6629. subgraph.type = 'subgraph';
  6630. getToken();
  6631. // optional graph id
  6632. if (tokenType == TOKENTYPE.IDENTIFIER) {
  6633. subgraph.id = token;
  6634. getToken();
  6635. }
  6636. }
  6637. // open angle bracket
  6638. if (token == '{') {
  6639. getToken();
  6640. if (!subgraph) {
  6641. subgraph = {};
  6642. }
  6643. subgraph.parent = graph;
  6644. subgraph.node = graph.node;
  6645. subgraph.edge = graph.edge;
  6646. subgraph.graph = graph.graph;
  6647. // statements
  6648. parseStatements(subgraph);
  6649. // close angle bracket
  6650. if (token != '}') {
  6651. throw newSyntaxError('Angle bracket } expected');
  6652. }
  6653. getToken();
  6654. // remove temporary default properties
  6655. delete subgraph.node;
  6656. delete subgraph.edge;
  6657. delete subgraph.graph;
  6658. delete subgraph.parent;
  6659. // register at the parent graph
  6660. if (!graph.subgraphs) {
  6661. graph.subgraphs = [];
  6662. }
  6663. graph.subgraphs.push(subgraph);
  6664. }
  6665. return subgraph;
  6666. }
  6667. /**
  6668. * parse an attribute statement like "node [shape=circle fontSize=16]".
  6669. * Available keywords are 'node', 'edge', 'graph'.
  6670. * The previous list with default attributes will be replaced
  6671. * @param {Object} graph
  6672. * @returns {String | null} keyword Returns the name of the parsed attribute
  6673. * (node, edge, graph), or null if nothing
  6674. * is parsed.
  6675. */
  6676. function parseAttributeStatement (graph) {
  6677. // attribute statements
  6678. if (token == 'node') {
  6679. getToken();
  6680. // node attributes
  6681. graph.node = parseAttributeList();
  6682. return 'node';
  6683. }
  6684. else if (token == 'edge') {
  6685. getToken();
  6686. // edge attributes
  6687. graph.edge = parseAttributeList();
  6688. return 'edge';
  6689. }
  6690. else if (token == 'graph') {
  6691. getToken();
  6692. // graph attributes
  6693. graph.graph = parseAttributeList();
  6694. return 'graph';
  6695. }
  6696. return null;
  6697. }
  6698. /**
  6699. * parse a node statement
  6700. * @param {Object} graph
  6701. * @param {String | Number} id
  6702. */
  6703. function parseNodeStatement(graph, id) {
  6704. // node statement
  6705. var node = {
  6706. id: id
  6707. };
  6708. var attr = parseAttributeList();
  6709. if (attr) {
  6710. node.attr = attr;
  6711. }
  6712. addNode(graph, node);
  6713. // edge statements
  6714. parseEdge(graph, id);
  6715. }
  6716. /**
  6717. * Parse an edge or a series of edges
  6718. * @param {Object} graph
  6719. * @param {String | Number} from Id of the from node
  6720. */
  6721. function parseEdge(graph, from) {
  6722. while (token == '->' || token == '--') {
  6723. var to;
  6724. var type = token;
  6725. getToken();
  6726. var subgraph = parseSubgraph(graph);
  6727. if (subgraph) {
  6728. to = subgraph;
  6729. }
  6730. else {
  6731. if (tokenType != TOKENTYPE.IDENTIFIER) {
  6732. throw newSyntaxError('Identifier or subgraph expected');
  6733. }
  6734. to = token;
  6735. addNode(graph, {
  6736. id: to
  6737. });
  6738. getToken();
  6739. }
  6740. // parse edge attributes
  6741. var attr = parseAttributeList();
  6742. // create edge
  6743. var edge = createEdge(graph, from, to, type, attr);
  6744. addEdge(graph, edge);
  6745. from = to;
  6746. }
  6747. }
  6748. /**
  6749. * Parse a set with attributes,
  6750. * for example [label="1.000", shape=solid]
  6751. * @return {Object | null} attr
  6752. */
  6753. function parseAttributeList() {
  6754. var attr = null;
  6755. while (token == '[') {
  6756. getToken();
  6757. attr = {};
  6758. while (token !== '' && token != ']') {
  6759. if (tokenType != TOKENTYPE.IDENTIFIER) {
  6760. throw newSyntaxError('Attribute name expected');
  6761. }
  6762. var name = token;
  6763. getToken();
  6764. if (token != '=') {
  6765. throw newSyntaxError('Equal sign = expected');
  6766. }
  6767. getToken();
  6768. if (tokenType != TOKENTYPE.IDENTIFIER) {
  6769. throw newSyntaxError('Attribute value expected');
  6770. }
  6771. var value = token;
  6772. setValue(attr, name, value); // name can be a path
  6773. getToken();
  6774. if (token ==',') {
  6775. getToken();
  6776. }
  6777. }
  6778. if (token != ']') {
  6779. throw newSyntaxError('Bracket ] expected');
  6780. }
  6781. getToken();
  6782. }
  6783. return attr;
  6784. }
  6785. /**
  6786. * Create a syntax error with extra information on current token and index.
  6787. * @param {String} message
  6788. * @returns {SyntaxError} err
  6789. */
  6790. function newSyntaxError(message) {
  6791. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  6792. }
  6793. /**
  6794. * Chop off text after a maximum length
  6795. * @param {String} text
  6796. * @param {Number} maxLength
  6797. * @returns {String}
  6798. */
  6799. function chop (text, maxLength) {
  6800. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  6801. }
  6802. /**
  6803. * Execute a function fn for each pair of elements in two arrays
  6804. * @param {Array | *} array1
  6805. * @param {Array | *} array2
  6806. * @param {function} fn
  6807. */
  6808. function forEach2(array1, array2, fn) {
  6809. if (array1 instanceof Array) {
  6810. array1.forEach(function (elem1) {
  6811. if (array2 instanceof Array) {
  6812. array2.forEach(function (elem2) {
  6813. fn(elem1, elem2);
  6814. });
  6815. }
  6816. else {
  6817. fn(elem1, array2);
  6818. }
  6819. });
  6820. }
  6821. else {
  6822. if (array2 instanceof Array) {
  6823. array2.forEach(function (elem2) {
  6824. fn(array1, elem2);
  6825. });
  6826. }
  6827. else {
  6828. fn(array1, array2);
  6829. }
  6830. }
  6831. }
  6832. /**
  6833. * Convert a string containing a graph in DOT language into a map containing
  6834. * with nodes and edges in the format of graph.
  6835. * @param {String} data Text containing a graph in DOT-notation
  6836. * @return {Object} graphData
  6837. */
  6838. function DOTToGraph (data) {
  6839. // parse the DOT file
  6840. var dotData = parseDOT(data);
  6841. var graphData = {
  6842. nodes: [],
  6843. edges: [],
  6844. options: {}
  6845. };
  6846. // copy the nodes
  6847. if (dotData.nodes) {
  6848. dotData.nodes.forEach(function (dotNode) {
  6849. var graphNode = {
  6850. id: dotNode.id,
  6851. label: String(dotNode.label || dotNode.id)
  6852. };
  6853. merge(graphNode, dotNode.attr);
  6854. if (graphNode.image) {
  6855. graphNode.shape = 'image';
  6856. }
  6857. graphData.nodes.push(graphNode);
  6858. });
  6859. }
  6860. // copy the edges
  6861. if (dotData.edges) {
  6862. /**
  6863. * Convert an edge in DOT format to an edge with VisGraph format
  6864. * @param {Object} dotEdge
  6865. * @returns {Object} graphEdge
  6866. */
  6867. function convertEdge(dotEdge) {
  6868. var graphEdge = {
  6869. from: dotEdge.from,
  6870. to: dotEdge.to
  6871. };
  6872. merge(graphEdge, dotEdge.attr);
  6873. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  6874. return graphEdge;
  6875. }
  6876. dotData.edges.forEach(function (dotEdge) {
  6877. var from, to;
  6878. if (dotEdge.from instanceof Object) {
  6879. from = dotEdge.from.nodes;
  6880. }
  6881. else {
  6882. from = {
  6883. id: dotEdge.from
  6884. }
  6885. }
  6886. if (dotEdge.to instanceof Object) {
  6887. to = dotEdge.to.nodes;
  6888. }
  6889. else {
  6890. to = {
  6891. id: dotEdge.to
  6892. }
  6893. }
  6894. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  6895. dotEdge.from.edges.forEach(function (subEdge) {
  6896. var graphEdge = convertEdge(subEdge);
  6897. graphData.edges.push(graphEdge);
  6898. });
  6899. }
  6900. forEach2(from, to, function (from, to) {
  6901. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  6902. var graphEdge = convertEdge(subEdge);
  6903. graphData.edges.push(graphEdge);
  6904. });
  6905. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  6906. dotEdge.to.edges.forEach(function (subEdge) {
  6907. var graphEdge = convertEdge(subEdge);
  6908. graphData.edges.push(graphEdge);
  6909. });
  6910. }
  6911. });
  6912. }
  6913. // copy the options
  6914. if (dotData.attr) {
  6915. graphData.options = dotData.attr;
  6916. }
  6917. return graphData;
  6918. }
  6919. // exports
  6920. exports.parseDOT = parseDOT;
  6921. exports.DOTToGraph = DOTToGraph;
  6922. })(typeof util !== 'undefined' ? util : exports);
  6923. /**
  6924. * Canvas shapes used by the Graph
  6925. */
  6926. if (typeof CanvasRenderingContext2D !== 'undefined') {
  6927. /**
  6928. * Draw a circle shape
  6929. */
  6930. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  6931. this.beginPath();
  6932. this.arc(x, y, r, 0, 2*Math.PI, false);
  6933. };
  6934. /**
  6935. * Draw a square shape
  6936. * @param {Number} x horizontal center
  6937. * @param {Number} y vertical center
  6938. * @param {Number} r size, width and height of the square
  6939. */
  6940. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  6941. this.beginPath();
  6942. this.rect(x - r, y - r, r * 2, r * 2);
  6943. };
  6944. /**
  6945. * Draw a triangle shape
  6946. * @param {Number} x horizontal center
  6947. * @param {Number} y vertical center
  6948. * @param {Number} r radius, half the length of the sides of the triangle
  6949. */
  6950. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  6951. // http://en.wikipedia.org/wiki/Equilateral_triangle
  6952. this.beginPath();
  6953. var s = r * 2;
  6954. var s2 = s / 2;
  6955. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  6956. var h = Math.sqrt(s * s - s2 * s2); // height
  6957. this.moveTo(x, y - (h - ir));
  6958. this.lineTo(x + s2, y + ir);
  6959. this.lineTo(x - s2, y + ir);
  6960. this.lineTo(x, y - (h - ir));
  6961. this.closePath();
  6962. };
  6963. /**
  6964. * Draw a triangle shape in downward orientation
  6965. * @param {Number} x horizontal center
  6966. * @param {Number} y vertical center
  6967. * @param {Number} r radius
  6968. */
  6969. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  6970. // http://en.wikipedia.org/wiki/Equilateral_triangle
  6971. this.beginPath();
  6972. var s = r * 2;
  6973. var s2 = s / 2;
  6974. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  6975. var h = Math.sqrt(s * s - s2 * s2); // height
  6976. this.moveTo(x, y + (h - ir));
  6977. this.lineTo(x + s2, y - ir);
  6978. this.lineTo(x - s2, y - ir);
  6979. this.lineTo(x, y + (h - ir));
  6980. this.closePath();
  6981. };
  6982. /**
  6983. * Draw a star shape, a star with 5 points
  6984. * @param {Number} x horizontal center
  6985. * @param {Number} y vertical center
  6986. * @param {Number} r radius, half the length of the sides of the triangle
  6987. */
  6988. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  6989. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  6990. this.beginPath();
  6991. for (var n = 0; n < 10; n++) {
  6992. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  6993. this.lineTo(
  6994. x + radius * Math.sin(n * 2 * Math.PI / 10),
  6995. y - radius * Math.cos(n * 2 * Math.PI / 10)
  6996. );
  6997. }
  6998. this.closePath();
  6999. };
  7000. /**
  7001. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  7002. */
  7003. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  7004. var r2d = Math.PI/180;
  7005. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  7006. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  7007. this.beginPath();
  7008. this.moveTo(x+r,y);
  7009. this.lineTo(x+w-r,y);
  7010. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  7011. this.lineTo(x+w,y+h-r);
  7012. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  7013. this.lineTo(x+r,y+h);
  7014. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  7015. this.lineTo(x,y+r);
  7016. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  7017. };
  7018. /**
  7019. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7020. */
  7021. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  7022. var kappa = .5522848,
  7023. ox = (w / 2) * kappa, // control point offset horizontal
  7024. oy = (h / 2) * kappa, // control point offset vertical
  7025. xe = x + w, // x-end
  7026. ye = y + h, // y-end
  7027. xm = x + w / 2, // x-middle
  7028. ym = y + h / 2; // y-middle
  7029. this.beginPath();
  7030. this.moveTo(x, ym);
  7031. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7032. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7033. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7034. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7035. };
  7036. /**
  7037. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7038. */
  7039. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  7040. var f = 1/3;
  7041. var wEllipse = w;
  7042. var hEllipse = h * f;
  7043. var kappa = .5522848,
  7044. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  7045. oy = (hEllipse / 2) * kappa, // control point offset vertical
  7046. xe = x + wEllipse, // x-end
  7047. ye = y + hEllipse, // y-end
  7048. xm = x + wEllipse / 2, // x-middle
  7049. ym = y + hEllipse / 2, // y-middle
  7050. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  7051. yeb = y + h; // y-end, bottom ellipse
  7052. this.beginPath();
  7053. this.moveTo(xe, ym);
  7054. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7055. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7056. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7057. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7058. this.lineTo(xe, ymb);
  7059. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  7060. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  7061. this.lineTo(x, ym);
  7062. };
  7063. /**
  7064. * Draw an arrow point (no line)
  7065. */
  7066. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  7067. // tail
  7068. var xt = x - length * Math.cos(angle);
  7069. var yt = y - length * Math.sin(angle);
  7070. // inner tail
  7071. // TODO: allow to customize different shapes
  7072. var xi = x - length * 0.9 * Math.cos(angle);
  7073. var yi = y - length * 0.9 * Math.sin(angle);
  7074. // left
  7075. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  7076. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  7077. // right
  7078. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  7079. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  7080. this.beginPath();
  7081. this.moveTo(x, y);
  7082. this.lineTo(xl, yl);
  7083. this.lineTo(xi, yi);
  7084. this.lineTo(xr, yr);
  7085. this.closePath();
  7086. };
  7087. /**
  7088. * Sets up the dashedLine functionality for drawing
  7089. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  7090. * @author David Jordan
  7091. * @date 2012-08-08
  7092. */
  7093. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  7094. if (!dashArray) dashArray=[10,5];
  7095. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  7096. var dashCount = dashArray.length;
  7097. this.moveTo(x, y);
  7098. var dx = (x2-x), dy = (y2-y);
  7099. var slope = dy/dx;
  7100. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  7101. var dashIndex=0, draw=true;
  7102. while (distRemaining>=0.1){
  7103. var dashLength = dashArray[dashIndex++%dashCount];
  7104. if (dashLength > distRemaining) dashLength = distRemaining;
  7105. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  7106. if (dx<0) xStep = -xStep;
  7107. x += xStep;
  7108. y += slope*xStep;
  7109. this[draw ? 'lineTo' : 'moveTo'](x,y);
  7110. distRemaining -= dashLength;
  7111. draw = !draw;
  7112. }
  7113. };
  7114. // TODO: add diamond shape
  7115. }
  7116. /**
  7117. * @class Node
  7118. * A node. A node can be connected to other nodes via one or multiple edges.
  7119. * @param {object} properties An object containing properties for the node. All
  7120. * properties are optional, except for the id.
  7121. * {number} id Id of the node. Required
  7122. * {string} label Text label for the node
  7123. * {number} x Horizontal position of the node
  7124. * {number} y Vertical position of the node
  7125. * {string} shape Node shape, available:
  7126. * "database", "circle", "ellipse",
  7127. * "box", "image", "text", "dot",
  7128. * "star", "triangle", "triangleDown",
  7129. * "square"
  7130. * {string} image An image url
  7131. * {string} title An title text, can be HTML
  7132. * {anytype} group A group name or number
  7133. * @param {Graph.Images} imagelist A list with images. Only needed
  7134. * when the node has an image
  7135. * @param {Graph.Groups} grouplist A list with groups. Needed for
  7136. * retrieving group properties
  7137. * @param {Object} constants An object with default values for
  7138. * example for the color
  7139. */
  7140. function Node(properties, imagelist, grouplist, constants) {
  7141. this.selected = false;
  7142. this.edges = []; // all edges connected to this node
  7143. this.group = constants.nodes.group;
  7144. this.fontSize = constants.nodes.fontSize;
  7145. this.fontFace = constants.nodes.fontFace;
  7146. this.fontColor = constants.nodes.fontColor;
  7147. this.color = constants.nodes.color;
  7148. // set defaults for the properties
  7149. this.id = undefined;
  7150. this.shape = constants.nodes.shape;
  7151. this.image = constants.nodes.image;
  7152. this.x = 0;
  7153. this.y = 0;
  7154. this.xFixed = false;
  7155. this.yFixed = false;
  7156. this.radius = constants.nodes.radius;
  7157. this.radiusFixed = false;
  7158. this.radiusMin = constants.nodes.radiusMin;
  7159. this.radiusMax = constants.nodes.radiusMax;
  7160. this.imagelist = imagelist;
  7161. this.grouplist = grouplist;
  7162. this.setProperties(properties, constants);
  7163. // mass, force, velocity
  7164. this.mass = 50; // kg (mass is adjusted for the number of connected edges)
  7165. this.fx = 0.0; // external force x
  7166. this.fy = 0.0; // external force y
  7167. this.vx = 0.0; // velocity x
  7168. this.vy = 0.0; // velocity y
  7169. this.minForce = constants.minForce;
  7170. this.damping = 0.9; // damping factor
  7171. };
  7172. /**
  7173. * Attach a edge to the node
  7174. * @param {Edge} edge
  7175. */
  7176. Node.prototype.attachEdge = function(edge) {
  7177. if (this.edges.indexOf(edge) == -1) {
  7178. this.edges.push(edge);
  7179. }
  7180. this._updateMass();
  7181. };
  7182. /**
  7183. * Detach a edge from the node
  7184. * @param {Edge} edge
  7185. */
  7186. Node.prototype.detachEdge = function(edge) {
  7187. var index = this.edges.indexOf(edge);
  7188. if (index != -1) {
  7189. this.edges.splice(index, 1);
  7190. }
  7191. this._updateMass();
  7192. };
  7193. /**
  7194. * Update the nodes mass, which is determined by the number of edges connecting
  7195. * to it (more edges -> heavier node).
  7196. * @private
  7197. */
  7198. Node.prototype._updateMass = function() {
  7199. this.mass = 50 + 20 * this.edges.length; // kg
  7200. };
  7201. /**
  7202. * Set or overwrite properties for the node
  7203. * @param {Object} properties an object with properties
  7204. * @param {Object} constants and object with default, global properties
  7205. */
  7206. Node.prototype.setProperties = function(properties, constants) {
  7207. if (!properties) {
  7208. return;
  7209. }
  7210. // basic properties
  7211. if (properties.id != undefined) {this.id = properties.id;}
  7212. if (properties.label != undefined) {this.label = properties.label;}
  7213. if (properties.title != undefined) {this.title = properties.title;}
  7214. if (properties.group != undefined) {this.group = properties.group;}
  7215. if (properties.x != undefined) {this.x = properties.x;}
  7216. if (properties.y != undefined) {this.y = properties.y;}
  7217. if (properties.value != undefined) {this.value = properties.value;}
  7218. if (this.id === undefined) {
  7219. throw "Node must have an id";
  7220. }
  7221. // copy group properties
  7222. if (this.group) {
  7223. var groupObj = this.grouplist.get(this.group);
  7224. for (var prop in groupObj) {
  7225. if (groupObj.hasOwnProperty(prop)) {
  7226. this[prop] = groupObj[prop];
  7227. }
  7228. }
  7229. }
  7230. // individual shape properties
  7231. if (properties.shape != undefined) {this.shape = properties.shape;}
  7232. if (properties.image != undefined) {this.image = properties.image;}
  7233. if (properties.radius != undefined) {this.radius = properties.radius;}
  7234. if (properties.color != undefined) {this.color = Node.parseColor(properties.color);}
  7235. if (properties.fontColor != undefined) {this.fontColor = properties.fontColor;}
  7236. if (properties.fontSize != undefined) {this.fontSize = properties.fontSize;}
  7237. if (properties.fontFace != undefined) {this.fontFace = properties.fontFace;}
  7238. if (this.image != undefined) {
  7239. if (this.imagelist) {
  7240. this.imageObj = this.imagelist.load(this.image);
  7241. }
  7242. else {
  7243. throw "No imagelist provided";
  7244. }
  7245. }
  7246. this.xFixed = this.xFixed || (properties.x != undefined);
  7247. this.yFixed = this.yFixed || (properties.y != undefined);
  7248. this.radiusFixed = this.radiusFixed || (properties.radius != undefined);
  7249. if (this.shape == 'image') {
  7250. this.radiusMin = constants.nodes.widthMin;
  7251. this.radiusMax = constants.nodes.widthMax;
  7252. }
  7253. // choose draw method depending on the shape
  7254. switch (this.shape) {
  7255. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  7256. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  7257. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  7258. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  7259. // TODO: add diamond shape
  7260. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  7261. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  7262. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  7263. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  7264. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  7265. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  7266. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  7267. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  7268. }
  7269. // reset the size of the node, this can be changed
  7270. this._reset();
  7271. };
  7272. /**
  7273. * Parse a color property into an object with border, background, and
  7274. * hightlight colors
  7275. * @param {Object | String} color
  7276. * @return {Object} colorObject
  7277. */
  7278. Node.parseColor = function(color) {
  7279. var c;
  7280. if (util.isString(color)) {
  7281. c = {
  7282. border: color,
  7283. background: color,
  7284. highlight: {
  7285. border: color,
  7286. background: color
  7287. }
  7288. };
  7289. // TODO: automatically generate a nice highlight color
  7290. }
  7291. else {
  7292. c = {};
  7293. c.background = color.background || 'white';
  7294. c.border = color.border || c.background;
  7295. if (util.isString(color.highlight)) {
  7296. c.highlight = {
  7297. border: color.highlight,
  7298. background: color.highlight
  7299. }
  7300. }
  7301. else {
  7302. c.highlight = {};
  7303. c.highlight.background = color.highlight && color.highlight.background || c.background;
  7304. c.highlight.border = color.highlight && color.highlight.border || c.border;
  7305. }
  7306. }
  7307. return c;
  7308. };
  7309. /**
  7310. * select this node
  7311. */
  7312. Node.prototype.select = function() {
  7313. this.selected = true;
  7314. this._reset();
  7315. };
  7316. /**
  7317. * unselect this node
  7318. */
  7319. Node.prototype.unselect = function() {
  7320. this.selected = false;
  7321. this._reset();
  7322. };
  7323. /**
  7324. * Reset the calculated size of the node, forces it to recalculate its size
  7325. * @private
  7326. */
  7327. Node.prototype._reset = function() {
  7328. this.width = undefined;
  7329. this.height = undefined;
  7330. };
  7331. /**
  7332. * get the title of this node.
  7333. * @return {string} title The title of the node, or undefined when no title
  7334. * has been set.
  7335. */
  7336. Node.prototype.getTitle = function() {
  7337. return this.title;
  7338. };
  7339. /**
  7340. * Calculate the distance to the border of the Node
  7341. * @param {CanvasRenderingContext2D} ctx
  7342. * @param {Number} angle Angle in radians
  7343. * @returns {number} distance Distance to the border in pixels
  7344. */
  7345. Node.prototype.distanceToBorder = function (ctx, angle) {
  7346. var borderWidth = 1;
  7347. if (!this.width) {
  7348. this.resize(ctx);
  7349. }
  7350. //noinspection FallthroughInSwitchStatementJS
  7351. switch (this.shape) {
  7352. case 'circle':
  7353. case 'dot':
  7354. return this.radius + borderWidth;
  7355. case 'ellipse':
  7356. var a = this.width / 2;
  7357. var b = this.height / 2;
  7358. var w = (Math.sin(angle) * a);
  7359. var h = (Math.cos(angle) * b);
  7360. return a * b / Math.sqrt(w * w + h * h);
  7361. // TODO: implement distanceToBorder for database
  7362. // TODO: implement distanceToBorder for triangle
  7363. // TODO: implement distanceToBorder for triangleDown
  7364. case 'box':
  7365. case 'image':
  7366. case 'text':
  7367. default:
  7368. if (this.width) {
  7369. return Math.min(
  7370. Math.abs(this.width / 2 / Math.cos(angle)),
  7371. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  7372. // TODO: reckon with border radius too in case of box
  7373. }
  7374. else {
  7375. return 0;
  7376. }
  7377. }
  7378. // TODO: implement calculation of distance to border for all shapes
  7379. };
  7380. /**
  7381. * Set forces acting on the node
  7382. * @param {number} fx Force in horizontal direction
  7383. * @param {number} fy Force in vertical direction
  7384. */
  7385. Node.prototype._setForce = function(fx, fy) {
  7386. this.fx = fx;
  7387. this.fy = fy;
  7388. };
  7389. /**
  7390. * Add forces acting on the node
  7391. * @param {number} fx Force in horizontal direction
  7392. * @param {number} fy Force in vertical direction
  7393. * @private
  7394. */
  7395. Node.prototype._addForce = function(fx, fy) {
  7396. this.fx += fx;
  7397. this.fy += fy;
  7398. };
  7399. /**
  7400. * Perform one discrete step for the node
  7401. * @param {number} interval Time interval in seconds
  7402. */
  7403. Node.prototype.discreteStep = function(interval) {
  7404. if (!this.xFixed) {
  7405. var dx = -this.damping * this.vx; // damping force
  7406. var ax = (this.fx + dx) / this.mass; // acceleration
  7407. this.vx += ax / interval; // velocity
  7408. this.x += this.vx / interval; // position
  7409. }
  7410. if (!this.yFixed) {
  7411. var dy = -this.damping * this.vy; // damping force
  7412. var ay = (this.fy + dy) / this.mass; // acceleration
  7413. this.vy += ay / interval; // velocity
  7414. this.y += this.vy / interval; // position
  7415. }
  7416. };
  7417. /**
  7418. * Check if this node has a fixed x and y position
  7419. * @return {boolean} true if fixed, false if not
  7420. */
  7421. Node.prototype.isFixed = function() {
  7422. return (this.xFixed && this.yFixed);
  7423. };
  7424. /**
  7425. * Check if this node is moving
  7426. * @param {number} vmin the minimum velocity considered as "moving"
  7427. * @return {boolean} true if moving, false if it has no velocity
  7428. */
  7429. // TODO: replace this method with calculating the kinetic energy
  7430. Node.prototype.isMoving = function(vmin) {
  7431. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin ||
  7432. (!this.xFixed && Math.abs(this.fx) > this.minForce) ||
  7433. (!this.yFixed && Math.abs(this.fy) > this.minForce));
  7434. };
  7435. /**
  7436. * check if this node is selecte
  7437. * @return {boolean} selected True if node is selected, else false
  7438. */
  7439. Node.prototype.isSelected = function() {
  7440. return this.selected;
  7441. };
  7442. /**
  7443. * Retrieve the value of the node. Can be undefined
  7444. * @return {Number} value
  7445. */
  7446. Node.prototype.getValue = function() {
  7447. return this.value;
  7448. };
  7449. /**
  7450. * Calculate the distance from the nodes location to the given location (x,y)
  7451. * @param {Number} x
  7452. * @param {Number} y
  7453. * @return {Number} value
  7454. */
  7455. Node.prototype.getDistance = function(x, y) {
  7456. var dx = this.x - x,
  7457. dy = this.y - y;
  7458. return Math.sqrt(dx * dx + dy * dy);
  7459. };
  7460. /**
  7461. * Adjust the value range of the node. The node will adjust it's radius
  7462. * based on its value.
  7463. * @param {Number} min
  7464. * @param {Number} max
  7465. */
  7466. Node.prototype.setValueRange = function(min, max) {
  7467. if (!this.radiusFixed && this.value !== undefined) {
  7468. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  7469. this.radius = (this.value - min) * scale + this.radiusMin;
  7470. }
  7471. };
  7472. /**
  7473. * Draw this node in the given canvas
  7474. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  7475. * @param {CanvasRenderingContext2D} ctx
  7476. */
  7477. Node.prototype.draw = function(ctx) {
  7478. throw "Draw method not initialized for node";
  7479. };
  7480. /**
  7481. * Recalculate the size of this node in the given canvas
  7482. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  7483. * @param {CanvasRenderingContext2D} ctx
  7484. */
  7485. Node.prototype.resize = function(ctx) {
  7486. throw "Resize method not initialized for node";
  7487. };
  7488. /**
  7489. * Check if this object is overlapping with the provided object
  7490. * @param {Object} obj an object with parameters left, top, right, bottom
  7491. * @return {boolean} True if location is located on node
  7492. */
  7493. Node.prototype.isOverlappingWith = function(obj) {
  7494. return (this.left < obj.right &&
  7495. this.left + this.width > obj.left &&
  7496. this.top < obj.bottom &&
  7497. this.top + this.height > obj.top);
  7498. };
  7499. Node.prototype._resizeImage = function (ctx) {
  7500. // TODO: pre calculate the image size
  7501. if (!this.width) { // undefined or 0
  7502. var width, height;
  7503. if (this.value) {
  7504. var scale = this.imageObj.height / this.imageObj.width;
  7505. width = this.radius || this.imageObj.width;
  7506. height = this.radius * scale || this.imageObj.height;
  7507. }
  7508. else {
  7509. width = this.imageObj.width;
  7510. height = this.imageObj.height;
  7511. }
  7512. this.width = width;
  7513. this.height = height;
  7514. }
  7515. };
  7516. Node.prototype._drawImage = function (ctx) {
  7517. this._resizeImage(ctx);
  7518. this.left = this.x - this.width / 2;
  7519. this.top = this.y - this.height / 2;
  7520. var yLabel;
  7521. if (this.imageObj) {
  7522. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  7523. yLabel = this.y + this.height / 2;
  7524. }
  7525. else {
  7526. // image still loading... just draw the label for now
  7527. yLabel = this.y;
  7528. }
  7529. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  7530. };
  7531. Node.prototype._resizeBox = function (ctx) {
  7532. if (!this.width) {
  7533. var margin = 5;
  7534. var textSize = this.getTextSize(ctx);
  7535. this.width = textSize.width + 2 * margin;
  7536. this.height = textSize.height + 2 * margin;
  7537. }
  7538. };
  7539. Node.prototype._drawBox = function (ctx) {
  7540. this._resizeBox(ctx);
  7541. this.left = this.x - this.width / 2;
  7542. this.top = this.y - this.height / 2;
  7543. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  7544. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  7545. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  7546. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  7547. ctx.fill();
  7548. ctx.stroke();
  7549. this._label(ctx, this.label, this.x, this.y);
  7550. };
  7551. Node.prototype._resizeDatabase = function (ctx) {
  7552. if (!this.width) {
  7553. var margin = 5;
  7554. var textSize = this.getTextSize(ctx);
  7555. var size = textSize.width + 2 * margin;
  7556. this.width = size;
  7557. this.height = size;
  7558. }
  7559. };
  7560. Node.prototype._drawDatabase = function (ctx) {
  7561. this._resizeDatabase(ctx);
  7562. this.left = this.x - this.width / 2;
  7563. this.top = this.y - this.height / 2;
  7564. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  7565. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  7566. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  7567. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  7568. ctx.fill();
  7569. ctx.stroke();
  7570. this._label(ctx, this.label, this.x, this.y);
  7571. };
  7572. Node.prototype._resizeCircle = function (ctx) {
  7573. if (!this.width) {
  7574. var margin = 5;
  7575. var textSize = this.getTextSize(ctx);
  7576. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  7577. this.radius = diameter / 2;
  7578. this.width = diameter;
  7579. this.height = diameter;
  7580. }
  7581. };
  7582. Node.prototype._drawCircle = function (ctx) {
  7583. this._resizeCircle(ctx);
  7584. this.left = this.x - this.width / 2;
  7585. this.top = this.y - this.height / 2;
  7586. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  7587. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  7588. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  7589. ctx.circle(this.x, this.y, this.radius);
  7590. ctx.fill();
  7591. ctx.stroke();
  7592. this._label(ctx, this.label, this.x, this.y);
  7593. };
  7594. Node.prototype._resizeEllipse = function (ctx) {
  7595. if (!this.width) {
  7596. var textSize = this.getTextSize(ctx);
  7597. this.width = textSize.width * 1.5;
  7598. this.height = textSize.height * 2;
  7599. if (this.width < this.height) {
  7600. this.width = this.height;
  7601. }
  7602. }
  7603. };
  7604. Node.prototype._drawEllipse = function (ctx) {
  7605. this._resizeEllipse(ctx);
  7606. this.left = this.x - this.width / 2;
  7607. this.top = this.y - this.height / 2;
  7608. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  7609. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  7610. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  7611. ctx.ellipse(this.left, this.top, this.width, this.height);
  7612. ctx.fill();
  7613. ctx.stroke();
  7614. this._label(ctx, this.label, this.x, this.y);
  7615. };
  7616. Node.prototype._drawDot = function (ctx) {
  7617. this._drawShape(ctx, 'circle');
  7618. };
  7619. Node.prototype._drawTriangle = function (ctx) {
  7620. this._drawShape(ctx, 'triangle');
  7621. };
  7622. Node.prototype._drawTriangleDown = function (ctx) {
  7623. this._drawShape(ctx, 'triangleDown');
  7624. };
  7625. Node.prototype._drawSquare = function (ctx) {
  7626. this._drawShape(ctx, 'square');
  7627. };
  7628. Node.prototype._drawStar = function (ctx) {
  7629. this._drawShape(ctx, 'star');
  7630. };
  7631. Node.prototype._resizeShape = function (ctx) {
  7632. if (!this.width) {
  7633. var size = 2 * this.radius;
  7634. this.width = size;
  7635. this.height = size;
  7636. }
  7637. };
  7638. Node.prototype._drawShape = function (ctx, shape) {
  7639. this._resizeShape(ctx);
  7640. this.left = this.x - this.width / 2;
  7641. this.top = this.y - this.height / 2;
  7642. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  7643. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  7644. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  7645. ctx[shape](this.x, this.y, this.radius);
  7646. ctx.fill();
  7647. ctx.stroke();
  7648. if (this.label) {
  7649. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  7650. }
  7651. };
  7652. Node.prototype._resizeText = function (ctx) {
  7653. if (!this.width) {
  7654. var margin = 5;
  7655. var textSize = this.getTextSize(ctx);
  7656. this.width = textSize.width + 2 * margin;
  7657. this.height = textSize.height + 2 * margin;
  7658. }
  7659. };
  7660. Node.prototype._drawText = function (ctx) {
  7661. this._resizeText(ctx);
  7662. this.left = this.x - this.width / 2;
  7663. this.top = this.y - this.height / 2;
  7664. this._label(ctx, this.label, this.x, this.y);
  7665. };
  7666. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  7667. if (text) {
  7668. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  7669. ctx.fillStyle = this.fontColor || "black";
  7670. ctx.textAlign = align || "center";
  7671. ctx.textBaseline = baseline || "middle";
  7672. var lines = text.split('\n'),
  7673. lineCount = lines.length,
  7674. fontSize = (this.fontSize + 4),
  7675. yLine = y + (1 - lineCount) / 2 * fontSize;
  7676. for (var i = 0; i < lineCount; i++) {
  7677. ctx.fillText(lines[i], x, yLine);
  7678. yLine += fontSize;
  7679. }
  7680. }
  7681. };
  7682. Node.prototype.getTextSize = function(ctx) {
  7683. if (this.label != undefined) {
  7684. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  7685. var lines = this.label.split('\n'),
  7686. height = (this.fontSize + 4) * lines.length,
  7687. width = 0;
  7688. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  7689. width = Math.max(width, ctx.measureText(lines[i]).width);
  7690. }
  7691. return {"width": width, "height": height};
  7692. }
  7693. else {
  7694. return {"width": 0, "height": 0};
  7695. }
  7696. };
  7697. /**
  7698. * @class Edge
  7699. *
  7700. * A edge connects two nodes
  7701. * @param {Object} properties Object with properties. Must contain
  7702. * At least properties from and to.
  7703. * Available properties: from (number),
  7704. * to (number), label (string, color (string),
  7705. * width (number), style (string),
  7706. * length (number), title (string)
  7707. * @param {Graph} graph A graph object, used to find and edge to
  7708. * nodes.
  7709. * @param {Object} constants An object with default values for
  7710. * example for the color
  7711. */
  7712. function Edge (properties, graph, constants) {
  7713. if (!graph) {
  7714. throw "No graph provided";
  7715. }
  7716. this.graph = graph;
  7717. // initialize constants
  7718. this.widthMin = constants.edges.widthMin;
  7719. this.widthMax = constants.edges.widthMax;
  7720. // initialize variables
  7721. this.id = undefined;
  7722. this.fromId = undefined;
  7723. this.toId = undefined;
  7724. this.style = constants.edges.style;
  7725. this.title = undefined;
  7726. this.width = constants.edges.width;
  7727. this.value = undefined;
  7728. this.length = constants.edges.length;
  7729. this.from = null; // a node
  7730. this.to = null; // a node
  7731. this.connected = false;
  7732. // Added to support dashed lines
  7733. // David Jordan
  7734. // 2012-08-08
  7735. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  7736. this.stiffness = undefined; // depends on the length of the edge
  7737. this.color = constants.edges.color;
  7738. this.widthFixed = false;
  7739. this.lengthFixed = false;
  7740. this.setProperties(properties, constants);
  7741. }
  7742. /**
  7743. * Set or overwrite properties for the edge
  7744. * @param {Object} properties an object with properties
  7745. * @param {Object} constants and object with default, global properties
  7746. */
  7747. Edge.prototype.setProperties = function(properties, constants) {
  7748. if (!properties) {
  7749. return;
  7750. }
  7751. if (properties.from != undefined) {this.fromId = properties.from;}
  7752. if (properties.to != undefined) {this.toId = properties.to;}
  7753. if (properties.id != undefined) {this.id = properties.id;}
  7754. if (properties.style != undefined) {this.style = properties.style;}
  7755. if (properties.label != undefined) {this.label = properties.label;}
  7756. if (this.label) {
  7757. this.fontSize = constants.edges.fontSize;
  7758. this.fontFace = constants.edges.fontFace;
  7759. this.fontColor = constants.edges.fontColor;
  7760. if (properties.fontColor != undefined) {this.fontColor = properties.fontColor;}
  7761. if (properties.fontSize != undefined) {this.fontSize = properties.fontSize;}
  7762. if (properties.fontFace != undefined) {this.fontFace = properties.fontFace;}
  7763. }
  7764. if (properties.title != undefined) {this.title = properties.title;}
  7765. if (properties.width != undefined) {this.width = properties.width;}
  7766. if (properties.value != undefined) {this.value = properties.value;}
  7767. if (properties.length != undefined) {this.length = properties.length;}
  7768. // Added to support dashed lines
  7769. // David Jordan
  7770. // 2012-08-08
  7771. if (properties.dash) {
  7772. if (properties.dash.length != undefined) {this.dash.length = properties.dash.length;}
  7773. if (properties.dash.gap != undefined) {this.dash.gap = properties.dash.gap;}
  7774. if (properties.dash.altLength != undefined) {this.dash.altLength = properties.dash.altLength;}
  7775. }
  7776. if (properties.color != undefined) {this.color = properties.color;}
  7777. // A node is connected when it has a from and to node.
  7778. this.connect();
  7779. this.widthFixed = this.widthFixed || (properties.width != undefined);
  7780. this.lengthFixed = this.lengthFixed || (properties.length != undefined);
  7781. this.stiffness = 1 / this.length;
  7782. // set draw method based on style
  7783. switch (this.style) {
  7784. case 'line': this.draw = this._drawLine; break;
  7785. case 'arrow': this.draw = this._drawArrow; break;
  7786. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  7787. case 'dash-line': this.draw = this._drawDashLine; break;
  7788. default: this.draw = this._drawLine; break;
  7789. }
  7790. };
  7791. /**
  7792. * Connect an edge to its nodes
  7793. */
  7794. Edge.prototype.connect = function () {
  7795. this.disconnect();
  7796. this.from = this.graph.nodes[this.fromId] || null;
  7797. this.to = this.graph.nodes[this.toId] || null;
  7798. this.connected = (this.from && this.to);
  7799. if (this.connected) {
  7800. this.from.attachEdge(this);
  7801. this.to.attachEdge(this);
  7802. }
  7803. else {
  7804. if (this.from) {
  7805. this.from.detachEdge(this);
  7806. }
  7807. if (this.to) {
  7808. this.to.detachEdge(this);
  7809. }
  7810. }
  7811. };
  7812. /**
  7813. * Disconnect an edge from its nodes
  7814. */
  7815. Edge.prototype.disconnect = function () {
  7816. if (this.from) {
  7817. this.from.detachEdge(this);
  7818. this.from = null;
  7819. }
  7820. if (this.to) {
  7821. this.to.detachEdge(this);
  7822. this.to = null;
  7823. }
  7824. this.connected = false;
  7825. };
  7826. /**
  7827. * get the title of this edge.
  7828. * @return {string} title The title of the edge, or undefined when no title
  7829. * has been set.
  7830. */
  7831. Edge.prototype.getTitle = function() {
  7832. return this.title;
  7833. };
  7834. /**
  7835. * Retrieve the value of the edge. Can be undefined
  7836. * @return {Number} value
  7837. */
  7838. Edge.prototype.getValue = function() {
  7839. return this.value;
  7840. };
  7841. /**
  7842. * Adjust the value range of the edge. The edge will adjust it's width
  7843. * based on its value.
  7844. * @param {Number} min
  7845. * @param {Number} max
  7846. */
  7847. Edge.prototype.setValueRange = function(min, max) {
  7848. if (!this.widthFixed && this.value !== undefined) {
  7849. var factor = (this.widthMax - this.widthMin) / (max - min);
  7850. this.width = (this.value - min) * factor + this.widthMin;
  7851. }
  7852. };
  7853. /**
  7854. * Redraw a edge
  7855. * Draw this edge in the given canvas
  7856. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  7857. * @param {CanvasRenderingContext2D} ctx
  7858. */
  7859. Edge.prototype.draw = function(ctx) {
  7860. throw "Method draw not initialized in edge";
  7861. };
  7862. /**
  7863. * Check if this object is overlapping with the provided object
  7864. * @param {Object} obj an object with parameters left, top
  7865. * @return {boolean} True if location is located on the edge
  7866. */
  7867. Edge.prototype.isOverlappingWith = function(obj) {
  7868. var distMax = 10;
  7869. var xFrom = this.from.x;
  7870. var yFrom = this.from.y;
  7871. var xTo = this.to.x;
  7872. var yTo = this.to.y;
  7873. var xObj = obj.left;
  7874. var yObj = obj.top;
  7875. var dist = Edge._dist(xFrom, yFrom, xTo, yTo, xObj, yObj);
  7876. return (dist < distMax);
  7877. };
  7878. /**
  7879. * Redraw a edge as a line
  7880. * Draw this edge in the given canvas
  7881. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  7882. * @param {CanvasRenderingContext2D} ctx
  7883. * @private
  7884. */
  7885. Edge.prototype._drawLine = function(ctx) {
  7886. // set style
  7887. ctx.strokeStyle = this.color;
  7888. ctx.lineWidth = this._getLineWidth();
  7889. var point;
  7890. if (this.from != this.to) {
  7891. // draw line
  7892. this._line(ctx);
  7893. // draw label
  7894. if (this.label) {
  7895. point = this._pointOnLine(0.5);
  7896. this._label(ctx, this.label, point.x, point.y);
  7897. }
  7898. }
  7899. else {
  7900. var x, y;
  7901. var radius = this.length / 4;
  7902. var node = this.from;
  7903. if (!node.width) {
  7904. node.resize(ctx);
  7905. }
  7906. if (node.width > node.height) {
  7907. x = node.x + node.width / 2;
  7908. y = node.y - radius;
  7909. }
  7910. else {
  7911. x = node.x + radius;
  7912. y = node.y - node.height / 2;
  7913. }
  7914. this._circle(ctx, x, y, radius);
  7915. point = this._pointOnCircle(x, y, radius, 0.5);
  7916. this._label(ctx, this.label, point.x, point.y);
  7917. }
  7918. };
  7919. /**
  7920. * Get the line width of the edge. Depends on width and whether one of the
  7921. * connected nodes is selected.
  7922. * @return {Number} width
  7923. * @private
  7924. */
  7925. Edge.prototype._getLineWidth = function() {
  7926. if (this.from.selected || this.to.selected) {
  7927. return Math.min(this.width * 2, this.widthMax);
  7928. }
  7929. else {
  7930. return this.width;
  7931. }
  7932. };
  7933. /**
  7934. * Draw a line between two nodes
  7935. * @param {CanvasRenderingContext2D} ctx
  7936. * @private
  7937. */
  7938. Edge.prototype._line = function (ctx) {
  7939. // draw a straight line
  7940. ctx.beginPath();
  7941. ctx.moveTo(this.from.x, this.from.y);
  7942. ctx.lineTo(this.to.x, this.to.y);
  7943. ctx.stroke();
  7944. };
  7945. /**
  7946. * Draw a line from a node to itself, a circle
  7947. * @param {CanvasRenderingContext2D} ctx
  7948. * @param {Number} x
  7949. * @param {Number} y
  7950. * @param {Number} radius
  7951. * @private
  7952. */
  7953. Edge.prototype._circle = function (ctx, x, y, radius) {
  7954. // draw a circle
  7955. ctx.beginPath();
  7956. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  7957. ctx.stroke();
  7958. };
  7959. /**
  7960. * Draw label with white background and with the middle at (x, y)
  7961. * @param {CanvasRenderingContext2D} ctx
  7962. * @param {String} text
  7963. * @param {Number} x
  7964. * @param {Number} y
  7965. * @private
  7966. */
  7967. Edge.prototype._label = function (ctx, text, x, y) {
  7968. if (text) {
  7969. // TODO: cache the calculated size
  7970. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  7971. this.fontSize + "px " + this.fontFace;
  7972. ctx.fillStyle = 'white';
  7973. var width = ctx.measureText(text).width;
  7974. var height = this.fontSize;
  7975. var left = x - width / 2;
  7976. var top = y - height / 2;
  7977. ctx.fillRect(left, top, width, height);
  7978. // draw text
  7979. ctx.fillStyle = this.fontColor || "black";
  7980. ctx.textAlign = "left";
  7981. ctx.textBaseline = "top";
  7982. ctx.fillText(text, left, top);
  7983. }
  7984. };
  7985. /**
  7986. * Redraw a edge as a dashed line
  7987. * Draw this edge in the given canvas
  7988. * @author David Jordan
  7989. * @date 2012-08-08
  7990. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  7991. * @param {CanvasRenderingContext2D} ctx
  7992. * @private
  7993. */
  7994. Edge.prototype._drawDashLine = function(ctx) {
  7995. // set style
  7996. ctx.strokeStyle = this.color;
  7997. ctx.lineWidth = this._getLineWidth();
  7998. // draw dashed line
  7999. ctx.beginPath();
  8000. ctx.lineCap = 'round';
  8001. if (this.dash.altLength != undefined) //If an alt dash value has been set add to the array this value
  8002. {
  8003. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  8004. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  8005. }
  8006. else if (this.dash.length != undefined && this.dash.gap != undefined) //If a dash and gap value has been set add to the array this value
  8007. {
  8008. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  8009. [this.dash.length,this.dash.gap]);
  8010. }
  8011. else //If all else fails draw a line
  8012. {
  8013. ctx.moveTo(this.from.x, this.from.y);
  8014. ctx.lineTo(this.to.x, this.to.y);
  8015. }
  8016. ctx.stroke();
  8017. // draw label
  8018. if (this.label) {
  8019. var point = this._pointOnLine(0.5);
  8020. this._label(ctx, this.label, point.x, point.y);
  8021. }
  8022. };
  8023. /**
  8024. * Get a point on a line
  8025. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  8026. * @return {Object} point
  8027. * @private
  8028. */
  8029. Edge.prototype._pointOnLine = function (percentage) {
  8030. return {
  8031. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  8032. y: (1 - percentage) * this.from.y + percentage * this.to.y
  8033. }
  8034. };
  8035. /**
  8036. * Get a point on a circle
  8037. * @param {Number} x
  8038. * @param {Number} y
  8039. * @param {Number} radius
  8040. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  8041. * @return {Object} point
  8042. * @private
  8043. */
  8044. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  8045. var angle = (percentage - 3/8) * 2 * Math.PI;
  8046. return {
  8047. x: x + radius * Math.cos(angle),
  8048. y: y - radius * Math.sin(angle)
  8049. }
  8050. };
  8051. /**
  8052. * Redraw a edge as a line with an arrow halfway the line
  8053. * Draw this edge in the given canvas
  8054. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8055. * @param {CanvasRenderingContext2D} ctx
  8056. * @private
  8057. */
  8058. Edge.prototype._drawArrowCenter = function(ctx) {
  8059. var point;
  8060. // set style
  8061. ctx.strokeStyle = this.color;
  8062. ctx.fillStyle = this.color;
  8063. ctx.lineWidth = this._getLineWidth();
  8064. if (this.from != this.to) {
  8065. // draw line
  8066. this._line(ctx);
  8067. // draw an arrow halfway the line
  8068. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  8069. var length = 10 + 5 * this.width; // TODO: make customizable?
  8070. point = this._pointOnLine(0.5);
  8071. ctx.arrow(point.x, point.y, angle, length);
  8072. ctx.fill();
  8073. ctx.stroke();
  8074. // draw label
  8075. if (this.label) {
  8076. point = this._pointOnLine(0.5);
  8077. this._label(ctx, this.label, point.x, point.y);
  8078. }
  8079. }
  8080. else {
  8081. // draw circle
  8082. var x, y;
  8083. var radius = this.length / 4;
  8084. var node = this.from;
  8085. if (!node.width) {
  8086. node.resize(ctx);
  8087. }
  8088. if (node.width > node.height) {
  8089. x = node.x + node.width / 2;
  8090. y = node.y - radius;
  8091. }
  8092. else {
  8093. x = node.x + radius;
  8094. y = node.y - node.height / 2;
  8095. }
  8096. this._circle(ctx, x, y, radius);
  8097. // draw all arrows
  8098. var angle = 0.2 * Math.PI;
  8099. var length = 10 + 5 * this.width; // TODO: make customizable?
  8100. point = this._pointOnCircle(x, y, radius, 0.5);
  8101. ctx.arrow(point.x, point.y, angle, length);
  8102. ctx.fill();
  8103. ctx.stroke();
  8104. // draw label
  8105. if (this.label) {
  8106. point = this._pointOnCircle(x, y, radius, 0.5);
  8107. this._label(ctx, this.label, point.x, point.y);
  8108. }
  8109. }
  8110. };
  8111. /**
  8112. * Redraw a edge as a line with an arrow
  8113. * Draw this edge in the given canvas
  8114. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8115. * @param {CanvasRenderingContext2D} ctx
  8116. * @private
  8117. */
  8118. Edge.prototype._drawArrow = function(ctx) {
  8119. // set style
  8120. ctx.strokeStyle = this.color;
  8121. ctx.fillStyle = this.color;
  8122. ctx.lineWidth = this._getLineWidth();
  8123. // draw line
  8124. var angle, length;
  8125. if (this.from != this.to) {
  8126. // calculate length and angle of the line
  8127. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  8128. var dx = (this.to.x - this.from.x);
  8129. var dy = (this.to.y - this.from.y);
  8130. var lEdge = Math.sqrt(dx * dx + dy * dy);
  8131. var lFrom = this.from.distanceToBorder(ctx, angle + Math.PI);
  8132. var pFrom = (lEdge - lFrom) / lEdge;
  8133. var xFrom = (pFrom) * this.from.x + (1 - pFrom) * this.to.x;
  8134. var yFrom = (pFrom) * this.from.y + (1 - pFrom) * this.to.y;
  8135. var lTo = this.to.distanceToBorder(ctx, angle);
  8136. var pTo = (lEdge - lTo) / lEdge;
  8137. var xTo = (1 - pTo) * this.from.x + pTo * this.to.x;
  8138. var yTo = (1 - pTo) * this.from.y + pTo * this.to.y;
  8139. ctx.beginPath();
  8140. ctx.moveTo(xFrom, yFrom);
  8141. ctx.lineTo(xTo, yTo);
  8142. ctx.stroke();
  8143. // draw arrow at the end of the line
  8144. length = 10 + 5 * this.width; // TODO: make customizable?
  8145. ctx.arrow(xTo, yTo, angle, length);
  8146. ctx.fill();
  8147. ctx.stroke();
  8148. // draw label
  8149. if (this.label) {
  8150. var point = this._pointOnLine(0.5);
  8151. this._label(ctx, this.label, point.x, point.y);
  8152. }
  8153. }
  8154. else {
  8155. // draw circle
  8156. var node = this.from;
  8157. var x, y, arrow;
  8158. var radius = this.length / 4;
  8159. if (!node.width) {
  8160. node.resize(ctx);
  8161. }
  8162. if (node.width > node.height) {
  8163. x = node.x + node.width / 2;
  8164. y = node.y - radius;
  8165. arrow = {
  8166. x: x,
  8167. y: node.y,
  8168. angle: 0.9 * Math.PI
  8169. };
  8170. }
  8171. else {
  8172. x = node.x + radius;
  8173. y = node.y - node.height / 2;
  8174. arrow = {
  8175. x: node.x,
  8176. y: y,
  8177. angle: 0.6 * Math.PI
  8178. };
  8179. }
  8180. ctx.beginPath();
  8181. // TODO: do not draw a circle, but an arc
  8182. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  8183. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  8184. ctx.stroke();
  8185. // draw all arrows
  8186. length = 10 + 5 * this.width; // TODO: make customizable?
  8187. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  8188. ctx.fill();
  8189. ctx.stroke();
  8190. // draw label
  8191. if (this.label) {
  8192. point = this._pointOnCircle(x, y, radius, 0.5);
  8193. this._label(ctx, this.label, point.x, point.y);
  8194. }
  8195. }
  8196. };
  8197. /**
  8198. * Calculate the distance between a point (x3,y3) and a line segment from
  8199. * (x1,y1) to (x2,y2).
  8200. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  8201. * @param {number} x1
  8202. * @param {number} y1
  8203. * @param {number} x2
  8204. * @param {number} y2
  8205. * @param {number} x3
  8206. * @param {number} y3
  8207. * @private
  8208. */
  8209. Edge._dist = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  8210. var px = x2-x1,
  8211. py = y2-y1,
  8212. something = px*px + py*py,
  8213. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  8214. if (u > 1) {
  8215. u = 1;
  8216. }
  8217. else if (u < 0) {
  8218. u = 0;
  8219. }
  8220. var x = x1 + u * px,
  8221. y = y1 + u * py,
  8222. dx = x - x3,
  8223. dy = y - y3;
  8224. //# Note: If the actual distance does not matter,
  8225. //# if you only want to compare what this function
  8226. //# returns to other results of this function, you
  8227. //# can just return the squared distance instead
  8228. //# (i.e. remove the sqrt) to gain a little performance
  8229. return Math.sqrt(dx*dx + dy*dy);
  8230. };
  8231. /**
  8232. * Popup is a class to create a popup window with some text
  8233. * @param {Element} container The container object.
  8234. * @param {Number} [x]
  8235. * @param {Number} [y]
  8236. * @param {String} [text]
  8237. */
  8238. function Popup(container, x, y, text) {
  8239. if (container) {
  8240. this.container = container;
  8241. }
  8242. else {
  8243. this.container = document.body;
  8244. }
  8245. this.x = 0;
  8246. this.y = 0;
  8247. this.padding = 5;
  8248. if (x !== undefined && y !== undefined ) {
  8249. this.setPosition(x, y);
  8250. }
  8251. if (text !== undefined) {
  8252. this.setText(text);
  8253. }
  8254. // create the frame
  8255. this.frame = document.createElement("div");
  8256. var style = this.frame.style;
  8257. style.position = "absolute";
  8258. style.visibility = "hidden";
  8259. style.border = "1px solid #666";
  8260. style.color = "black";
  8261. style.padding = this.padding + "px";
  8262. style.backgroundColor = "#FFFFC6";
  8263. style.borderRadius = "3px";
  8264. style.MozBorderRadius = "3px";
  8265. style.WebkitBorderRadius = "3px";
  8266. style.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  8267. style.whiteSpace = "nowrap";
  8268. this.container.appendChild(this.frame);
  8269. };
  8270. /**
  8271. * @param {number} x Horizontal position of the popup window
  8272. * @param {number} y Vertical position of the popup window
  8273. */
  8274. Popup.prototype.setPosition = function(x, y) {
  8275. this.x = parseInt(x);
  8276. this.y = parseInt(y);
  8277. };
  8278. /**
  8279. * Set the text for the popup window. This can be HTML code
  8280. * @param {string} text
  8281. */
  8282. Popup.prototype.setText = function(text) {
  8283. this.frame.innerHTML = text;
  8284. };
  8285. /**
  8286. * Show the popup window
  8287. * @param {boolean} show Optional. Show or hide the window
  8288. */
  8289. Popup.prototype.show = function (show) {
  8290. if (show === undefined) {
  8291. show = true;
  8292. }
  8293. if (show) {
  8294. var height = this.frame.clientHeight;
  8295. var width = this.frame.clientWidth;
  8296. var maxHeight = this.frame.parentNode.clientHeight;
  8297. var maxWidth = this.frame.parentNode.clientWidth;
  8298. var top = (this.y - height);
  8299. if (top + height + this.padding > maxHeight) {
  8300. top = maxHeight - height - this.padding;
  8301. }
  8302. if (top < this.padding) {
  8303. top = this.padding;
  8304. }
  8305. var left = this.x;
  8306. if (left + width + this.padding > maxWidth) {
  8307. left = maxWidth - width - this.padding;
  8308. }
  8309. if (left < this.padding) {
  8310. left = this.padding;
  8311. }
  8312. this.frame.style.left = left + "px";
  8313. this.frame.style.top = top + "px";
  8314. this.frame.style.visibility = "visible";
  8315. }
  8316. else {
  8317. this.hide();
  8318. }
  8319. };
  8320. /**
  8321. * Hide the popup window
  8322. */
  8323. Popup.prototype.hide = function () {
  8324. this.frame.style.visibility = "hidden";
  8325. };
  8326. /**
  8327. * @class Groups
  8328. * This class can store groups and properties specific for groups.
  8329. */
  8330. Groups = function () {
  8331. this.clear();
  8332. this.defaultIndex = 0;
  8333. };
  8334. /**
  8335. * default constants for group colors
  8336. */
  8337. Groups.DEFAULT = [
  8338. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  8339. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  8340. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  8341. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  8342. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  8343. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  8344. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  8345. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  8346. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  8347. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  8348. ];
  8349. /**
  8350. * Clear all groups
  8351. */
  8352. Groups.prototype.clear = function () {
  8353. this.groups = {};
  8354. this.groups.length = function()
  8355. {
  8356. var i = 0;
  8357. for ( var p in this ) {
  8358. if (this.hasOwnProperty(p)) {
  8359. i++;
  8360. }
  8361. }
  8362. return i;
  8363. }
  8364. };
  8365. /**
  8366. * get group properties of a groupname. If groupname is not found, a new group
  8367. * is added.
  8368. * @param {*} groupname Can be a number, string, Date, etc.
  8369. * @return {Object} group The created group, containing all group properties
  8370. */
  8371. Groups.prototype.get = function (groupname) {
  8372. var group = this.groups[groupname];
  8373. if (group == undefined) {
  8374. // create new group
  8375. var index = this.defaultIndex % Groups.DEFAULT.length;
  8376. this.defaultIndex++;
  8377. group = {};
  8378. group.color = Groups.DEFAULT[index];
  8379. this.groups[groupname] = group;
  8380. }
  8381. return group;
  8382. };
  8383. /**
  8384. * Add a custom group style
  8385. * @param {String} groupname
  8386. * @param {Object} style An object containing borderColor,
  8387. * backgroundColor, etc.
  8388. * @return {Object} group The created group object
  8389. */
  8390. Groups.prototype.add = function (groupname, style) {
  8391. this.groups[groupname] = style;
  8392. if (style.color) {
  8393. style.color = Node.parseColor(style.color);
  8394. }
  8395. return style;
  8396. };
  8397. /**
  8398. * @class Images
  8399. * This class loads images and keeps them stored.
  8400. */
  8401. Images = function () {
  8402. this.images = {};
  8403. this.callback = undefined;
  8404. };
  8405. /**
  8406. * Set an onload callback function. This will be called each time an image
  8407. * is loaded
  8408. * @param {function} callback
  8409. */
  8410. Images.prototype.setOnloadCallback = function(callback) {
  8411. this.callback = callback;
  8412. };
  8413. /**
  8414. *
  8415. * @param {string} url Url of the image
  8416. * @return {Image} img The image object
  8417. */
  8418. Images.prototype.load = function(url) {
  8419. var img = this.images[url];
  8420. if (img == undefined) {
  8421. // create the image
  8422. var images = this;
  8423. img = new Image();
  8424. this.images[url] = img;
  8425. img.onload = function() {
  8426. if (images.callback) {
  8427. images.callback(this);
  8428. }
  8429. };
  8430. img.src = url;
  8431. }
  8432. return img;
  8433. };
  8434. /**
  8435. * @constructor Graph
  8436. * Create a graph visualization, displaying nodes and edges.
  8437. *
  8438. * @param {Element} container The DOM element in which the Graph will
  8439. * be created. Normally a div element.
  8440. * @param {Object} data An object containing parameters
  8441. * {Array} nodes
  8442. * {Array} edges
  8443. * @param {Object} options Options
  8444. */
  8445. function Graph (container, data, options) {
  8446. // create variables and set default values
  8447. this.containerElement = container;
  8448. this.width = '100%';
  8449. this.height = '100%';
  8450. this.refreshRate = 50; // milliseconds
  8451. this.stabilize = true; // stabilize before displaying the graph
  8452. this.selectable = true;
  8453. // set constant values
  8454. this.constants = {
  8455. nodes: {
  8456. radiusMin: 5,
  8457. radiusMax: 20,
  8458. radius: 5,
  8459. distance: 100, // px
  8460. shape: 'ellipse',
  8461. image: undefined,
  8462. widthMin: 16, // px
  8463. widthMax: 64, // px
  8464. fontColor: 'black',
  8465. fontSize: 14, // px
  8466. //fontFace: verdana,
  8467. fontFace: 'arial',
  8468. color: {
  8469. border: '#2B7CE9',
  8470. background: '#97C2FC',
  8471. highlight: {
  8472. border: '#2B7CE9',
  8473. background: '#D2E5FF'
  8474. }
  8475. },
  8476. borderColor: '#2B7CE9',
  8477. backgroundColor: '#97C2FC',
  8478. highlightColor: '#D2E5FF',
  8479. group: undefined
  8480. },
  8481. edges: {
  8482. widthMin: 1,
  8483. widthMax: 15,
  8484. width: 1,
  8485. style: 'line',
  8486. color: '#343434',
  8487. fontColor: '#343434',
  8488. fontSize: 14, // px
  8489. fontFace: 'arial',
  8490. //distance: 100, //px
  8491. length: 100, // px
  8492. dash: {
  8493. length: 10,
  8494. gap: 5,
  8495. altLength: undefined
  8496. }
  8497. },
  8498. minForce: 0.05,
  8499. minVelocity: 0.02, // px/s
  8500. maxIterations: 1000 // maximum number of iteration to stabilize
  8501. };
  8502. var graph = this;
  8503. this.nodes = {}; // object with Node objects
  8504. this.edges = {}; // object with Edge objects
  8505. // TODO: create a counter to keep track on the number of nodes having values
  8506. // TODO: create a counter to keep track on the number of nodes currently moving
  8507. // TODO: create a counter to keep track on the number of edges having values
  8508. this.nodesData = null; // A DataSet or DataView
  8509. this.edgesData = null; // A DataSet or DataView
  8510. // create event listeners used to subscribe on the DataSets of the nodes and edges
  8511. var me = this;
  8512. this.nodesListeners = {
  8513. 'add': function (event, params) {
  8514. me._addNodes(params.items);
  8515. me.start();
  8516. },
  8517. 'update': function (event, params) {
  8518. me._updateNodes(params.items);
  8519. me.start();
  8520. },
  8521. 'remove': function (event, params) {
  8522. me._removeNodes(params.items);
  8523. me.start();
  8524. }
  8525. };
  8526. this.edgesListeners = {
  8527. 'add': function (event, params) {
  8528. me._addEdges(params.items);
  8529. me.start();
  8530. },
  8531. 'update': function (event, params) {
  8532. me._updateEdges(params.items);
  8533. me.start();
  8534. },
  8535. 'remove': function (event, params) {
  8536. me._removeEdges(params.items);
  8537. me.start();
  8538. }
  8539. };
  8540. this.groups = new Groups(); // object with groups
  8541. this.images = new Images(); // object with images
  8542. this.images.setOnloadCallback(function () {
  8543. graph._redraw();
  8544. });
  8545. // properties of the data
  8546. this.moving = false; // True if any of the nodes have an undefined position
  8547. this.selection = [];
  8548. this.timer = undefined;
  8549. // create a frame and canvas
  8550. this._create();
  8551. // apply options
  8552. this.setOptions(options);
  8553. // draw data
  8554. this.setData(data);
  8555. }
  8556. /**
  8557. * Set nodes and edges, and optionally options as well.
  8558. *
  8559. * @param {Object} data Object containing parameters:
  8560. * {Array | DataSet | DataView} [nodes] Array with nodes
  8561. * {Array | DataSet | DataView} [edges] Array with edges
  8562. * {String} [dot] String containing data in DOT format
  8563. * {Options} [options] Object with options
  8564. */
  8565. Graph.prototype.setData = function(data) {
  8566. if (data && data.dot && (data.nodes || data.edges)) {
  8567. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  8568. ' parameter pair "nodes" and "edges", but not both.');
  8569. }
  8570. // set options
  8571. this.setOptions(data && data.options);
  8572. // set all data
  8573. if (data && data.dot) {
  8574. // parse DOT file
  8575. if(data && data.dot) {
  8576. var dotData = vis.util.DOTToGraph(data.dot);
  8577. this.setData(dotData);
  8578. return;
  8579. }
  8580. }
  8581. else {
  8582. this._setNodes(data && data.nodes);
  8583. this._setEdges(data && data.edges);
  8584. }
  8585. // find a stable position or start animating to a stable position
  8586. if (this.stabilize) {
  8587. this._doStabilize();
  8588. }
  8589. this.start();
  8590. };
  8591. /**
  8592. * Set options
  8593. * @param {Object} options
  8594. */
  8595. Graph.prototype.setOptions = function (options) {
  8596. if (options) {
  8597. // retrieve parameter values
  8598. if (options.width != undefined) {this.width = options.width;}
  8599. if (options.height != undefined) {this.height = options.height;}
  8600. if (options.stabilize != undefined) {this.stabilize = options.stabilize;}
  8601. if (options.selectable != undefined) {this.selectable = options.selectable;}
  8602. // TODO: work out these options and document them
  8603. if (options.edges) {
  8604. for (var prop in options.edges) {
  8605. if (options.edges.hasOwnProperty(prop)) {
  8606. this.constants.edges[prop] = options.edges[prop];
  8607. }
  8608. }
  8609. if (options.edges.length != undefined &&
  8610. options.nodes && options.nodes.distance == undefined) {
  8611. this.constants.edges.length = options.edges.length;
  8612. this.constants.nodes.distance = options.edges.length * 1.25;
  8613. }
  8614. if (!options.edges.fontColor) {
  8615. this.constants.edges.fontColor = options.edges.color;
  8616. }
  8617. // Added to support dashed lines
  8618. // David Jordan
  8619. // 2012-08-08
  8620. if (options.edges.dash) {
  8621. if (options.edges.dash.length != undefined) {
  8622. this.constants.edges.dash.length = options.edges.dash.length;
  8623. }
  8624. if (options.edges.dash.gap != undefined) {
  8625. this.constants.edges.dash.gap = options.edges.dash.gap;
  8626. }
  8627. if (options.edges.dash.altLength != undefined) {
  8628. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  8629. }
  8630. }
  8631. }
  8632. if (options.nodes) {
  8633. for (prop in options.nodes) {
  8634. if (options.nodes.hasOwnProperty(prop)) {
  8635. this.constants.nodes[prop] = options.nodes[prop];
  8636. }
  8637. }
  8638. if (options.nodes.color) {
  8639. this.constants.nodes.color = Node.parseColor(options.nodes.color);
  8640. }
  8641. /*
  8642. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  8643. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  8644. */
  8645. }
  8646. if (options.groups) {
  8647. for (var groupname in options.groups) {
  8648. if (options.groups.hasOwnProperty(groupname)) {
  8649. var group = options.groups[groupname];
  8650. this.groups.add(groupname, group);
  8651. }
  8652. }
  8653. }
  8654. }
  8655. this.setSize(this.width, this.height);
  8656. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  8657. this._setScale(1);
  8658. };
  8659. /**
  8660. * fire an event
  8661. * @param {String} event The name of an event, for example "select"
  8662. * @param {Object} params Optional object with event parameters
  8663. * @private
  8664. */
  8665. Graph.prototype._trigger = function (event, params) {
  8666. events.trigger(this, event, params);
  8667. };
  8668. /**
  8669. * Create the main frame for the Graph.
  8670. * This function is executed once when a Graph object is created. The frame
  8671. * contains a canvas, and this canvas contains all objects like the axis and
  8672. * nodes.
  8673. * @private
  8674. */
  8675. Graph.prototype._create = function () {
  8676. // remove all elements from the container element.
  8677. while (this.containerElement.hasChildNodes()) {
  8678. this.containerElement.removeChild(this.containerElement.firstChild);
  8679. }
  8680. this.frame = document.createElement("div");
  8681. this.frame.className = "graph-frame";
  8682. this.frame.style.position = "relative";
  8683. this.frame.style.overflow = "hidden";
  8684. // create the graph canvas (HTML canvas element)
  8685. this.frame.canvas = document.createElement( "canvas" );
  8686. this.frame.canvas.style.position = "relative";
  8687. this.frame.appendChild(this.frame.canvas);
  8688. if (!this.frame.canvas.getContext) {
  8689. var noCanvas = document.createElement( "DIV" );
  8690. noCanvas.style.color = "red";
  8691. noCanvas.style.fontWeight = "bold" ;
  8692. noCanvas.style.padding = "10px";
  8693. noCanvas.innerHTML = "Error: your browser does not support HTML canvas";
  8694. this.frame.canvas.appendChild(noCanvas);
  8695. }
  8696. // create event listeners
  8697. var me = this;
  8698. var onmousedown = function (event) {me._onMouseDown(event);};
  8699. var onmousemove = function (event) {me._onMouseMoveTitle(event);};
  8700. var onmousewheel = function (event) {me._onMouseWheel(event);};
  8701. var ontouchstart = function (event) {me._onTouchStart(event);};
  8702. vis.util.addEventListener(this.frame.canvas, "mousedown", onmousedown);
  8703. vis.util.addEventListener(this.frame.canvas, "mousemove", onmousemove);
  8704. vis.util.addEventListener(this.frame.canvas, "mousewheel", onmousewheel);
  8705. vis.util.addEventListener(this.frame.canvas, "touchstart", ontouchstart);
  8706. // add the frame to the container element
  8707. this.containerElement.appendChild(this.frame);
  8708. };
  8709. /**
  8710. * handle on mouse down event
  8711. * @private
  8712. */
  8713. Graph.prototype._onMouseDown = function (event) {
  8714. event = event || window.event;
  8715. if (!this.selectable) {
  8716. return;
  8717. }
  8718. // check if mouse is still down (may be up when focus is lost for example
  8719. // in an iframe)
  8720. if (this.leftButtonDown) {
  8721. this._onMouseUp(event);
  8722. }
  8723. // only react on left mouse button down
  8724. this.leftButtonDown = event.which ? (event.which == 1) : (event.button == 1);
  8725. if (!this.leftButtonDown && !this.touchDown) {
  8726. return;
  8727. }
  8728. // add event listeners to handle moving the contents
  8729. // we store the function onmousemove and onmouseup in the timeline, so we can
  8730. // remove the eventlisteners lateron in the function mouseUp()
  8731. var me = this;
  8732. if (!this.onmousemove) {
  8733. this.onmousemove = function (event) {me._onMouseMove(event);};
  8734. vis.util.addEventListener(document, "mousemove", me.onmousemove);
  8735. }
  8736. if (!this.onmouseup) {
  8737. this.onmouseup = function (event) {me._onMouseUp(event);};
  8738. vis.util.addEventListener(document, "mouseup", me.onmouseup);
  8739. }
  8740. vis.util.preventDefault(event);
  8741. // store the start x and y position of the mouse
  8742. this.startMouseX = event.clientX || event.targetTouches[0].clientX;
  8743. this.startMouseY = event.clientY || event.targetTouches[0].clientY;
  8744. this.startFrameLeft = vis.util.getAbsoluteLeft(this.frame.canvas);
  8745. this.startFrameTop = vis.util.getAbsoluteTop(this.frame.canvas);
  8746. this.startTranslation = this._getTranslation();
  8747. this.ctrlKeyDown = event.ctrlKey;
  8748. this.shiftKeyDown = event.shiftKey;
  8749. var obj = {
  8750. left: this._xToCanvas(this.startMouseX - this.startFrameLeft),
  8751. top: this._yToCanvas(this.startMouseY - this.startFrameTop),
  8752. right: this._xToCanvas(this.startMouseX - this.startFrameLeft),
  8753. bottom: this._yToCanvas(this.startMouseY - this.startFrameTop)
  8754. };
  8755. var overlappingNodes = this._getNodesOverlappingWith(obj);
  8756. // if there are overlapping nodes, select the last one, this is the
  8757. // one which is drawn on top of the others
  8758. this.startClickedObj = (overlappingNodes.length > 0) ?
  8759. overlappingNodes[overlappingNodes.length - 1] : undefined;
  8760. if (this.startClickedObj) {
  8761. // move clicked node with the mouse
  8762. // make the clicked node temporarily fixed, and store their original state
  8763. var node = this.nodes[this.startClickedObj];
  8764. this.startClickedObj.xFixed = node.xFixed;
  8765. this.startClickedObj.yFixed = node.yFixed;
  8766. node.xFixed = true;
  8767. node.yFixed = true;
  8768. if (!this.ctrlKeyDown || !node.isSelected()) {
  8769. // select this node
  8770. this._selectNodes([this.startClickedObj], this.ctrlKeyDown);
  8771. }
  8772. else {
  8773. // unselect this node
  8774. this._unselectNodes([this.startClickedObj]);
  8775. }
  8776. if (!this.moving) {
  8777. this._redraw();
  8778. }
  8779. }
  8780. else if (this.shiftKeyDown) {
  8781. // start selection of multiple nodes
  8782. }
  8783. else {
  8784. // start moving the graph
  8785. this.moved = false;
  8786. }
  8787. };
  8788. /**
  8789. * handle on mouse move event
  8790. * @param {Event} event
  8791. * @private
  8792. */
  8793. Graph.prototype._onMouseMove = function (event) {
  8794. event = event || window.event;
  8795. if (!this.selectable) {
  8796. return;
  8797. }
  8798. var mouseX = event.clientX || (event.targetTouches && event.targetTouches[0].clientX) || 0;
  8799. var mouseY = event.clientY || (event.targetTouches && event.targetTouches[0].clientY) || 0;
  8800. this.mouseX = mouseX;
  8801. this.mouseY = mouseY;
  8802. if (this.startClickedObj) {
  8803. var node = this.nodes[this.startClickedObj];
  8804. if (!this.startClickedObj.xFixed)
  8805. node.x = this._xToCanvas(mouseX - this.startFrameLeft);
  8806. if (!this.startClickedObj.yFixed)
  8807. node.y = this._yToCanvas(mouseY - this.startFrameTop);
  8808. // start animation if not yet running
  8809. if (!this.moving) {
  8810. this.moving = true;
  8811. this.start();
  8812. }
  8813. }
  8814. else if (this.shiftKeyDown) {
  8815. // draw a rect from start mouse location to current mouse location
  8816. if (this.frame.selRect == undefined) {
  8817. this.frame.selRect = document.createElement("DIV");
  8818. this.frame.appendChild(this.frame.selRect);
  8819. this.frame.selRect.style.position = "absolute";
  8820. this.frame.selRect.style.border = "1px dashed red";
  8821. }
  8822. var left = Math.min(this.startMouseX, mouseX) - this.startFrameLeft;
  8823. var top = Math.min(this.startMouseY, mouseY) - this.startFrameTop;
  8824. var right = Math.max(this.startMouseX, mouseX) - this.startFrameLeft;
  8825. var bottom = Math.max(this.startMouseY, mouseY) - this.startFrameTop;
  8826. this.frame.selRect.style.left = left + "px";
  8827. this.frame.selRect.style.top = top + "px";
  8828. this.frame.selRect.style.width = (right - left) + "px";
  8829. this.frame.selRect.style.height = (bottom - top) + "px";
  8830. }
  8831. else {
  8832. // move the graph
  8833. var diffX = mouseX - this.startMouseX;
  8834. var diffY = mouseY - this.startMouseY;
  8835. this._setTranslation(
  8836. this.startTranslation.x + diffX,
  8837. this.startTranslation.y + diffY);
  8838. this._redraw();
  8839. this.moved = true;
  8840. }
  8841. vis.util.preventDefault(event);
  8842. };
  8843. /**
  8844. * handle on mouse up event
  8845. * @param {Event} event
  8846. * @private
  8847. */
  8848. Graph.prototype._onMouseUp = function (event) {
  8849. event = event || window.event;
  8850. if (!this.selectable) {
  8851. return;
  8852. }
  8853. // remove event listeners here, important for Safari
  8854. if (this.onmousemove) {
  8855. vis.util.removeEventListener(document, "mousemove", this.onmousemove);
  8856. this.onmousemove = undefined;
  8857. }
  8858. if (this.onmouseup) {
  8859. vis.util.removeEventListener(document, "mouseup", this.onmouseup);
  8860. this.onmouseup = undefined;
  8861. }
  8862. vis.util.preventDefault(event);
  8863. // check selected nodes
  8864. var endMouseX = event.clientX || this.mouseX || 0;
  8865. var endMouseY = event.clientY || this.mouseY || 0;
  8866. var ctrlKey = event ? event.ctrlKey : window.event.ctrlKey;
  8867. if (this.startClickedObj) {
  8868. // restore the original fixed state
  8869. var node = this.nodes[this.startClickedObj];
  8870. node.xFixed = this.startClickedObj.xFixed;
  8871. node.yFixed = this.startClickedObj.yFixed;
  8872. }
  8873. else if (this.shiftKeyDown) {
  8874. // select nodes inside selection area
  8875. var obj = {
  8876. "left": this._xToCanvas(Math.min(this.startMouseX, endMouseX) - this.startFrameLeft),
  8877. "top": this._yToCanvas(Math.min(this.startMouseY, endMouseY) - this.startFrameTop),
  8878. "right": this._xToCanvas(Math.max(this.startMouseX, endMouseX) - this.startFrameLeft),
  8879. "bottom": this._yToCanvas(Math.max(this.startMouseY, endMouseY) - this.startFrameTop)
  8880. };
  8881. var overlappingNodes = this._getNodesOverlappingWith(obj);
  8882. this._selectNodes(overlappingNodes, ctrlKey);
  8883. this.redraw();
  8884. // remove the selection rectangle
  8885. if (this.frame.selRect) {
  8886. this.frame.removeChild(this.frame.selRect);
  8887. this.frame.selRect = undefined;
  8888. }
  8889. }
  8890. else {
  8891. if (!this.ctrlKeyDown && !this.moved) {
  8892. // remove selection
  8893. this._unselectNodes();
  8894. this._redraw();
  8895. }
  8896. }
  8897. this.leftButtonDown = false;
  8898. this.ctrlKeyDown = false;
  8899. };
  8900. /**
  8901. * Event handler for mouse wheel event, used to zoom the timeline
  8902. * Code from http://adomas.org/javascript-mouse-wheel/
  8903. * @param {Event} event
  8904. * @private
  8905. */
  8906. Graph.prototype._onMouseWheel = function(event) {
  8907. event = event || window.event;
  8908. var mouseX = event.clientX;
  8909. var mouseY = event.clientY;
  8910. // retrieve delta
  8911. var delta = 0;
  8912. if (event.wheelDelta) { /* IE/Opera. */
  8913. delta = event.wheelDelta/120;
  8914. } else if (event.detail) { /* Mozilla case. */
  8915. // In Mozilla, sign of delta is different than in IE.
  8916. // Also, delta is multiple of 3.
  8917. delta = -event.detail/3;
  8918. }
  8919. // If delta is nonzero, handle it.
  8920. // Basically, delta is now positive if wheel was scrolled up,
  8921. // and negative, if wheel was scrolled down.
  8922. if (delta) {
  8923. // determine zoom factor, and adjust the zoom factor such that zooming in
  8924. // and zooming out correspond wich each other
  8925. var zoom = delta / 10;
  8926. if (delta < 0) {
  8927. zoom = zoom / (1 - zoom);
  8928. }
  8929. var scaleOld = this._getScale();
  8930. var scaleNew = scaleOld * (1 + zoom);
  8931. if (scaleNew < 0.01) {
  8932. scaleNew = 0.01;
  8933. }
  8934. if (scaleNew > 10) {
  8935. scaleNew = 10;
  8936. }
  8937. var frameLeft = vis.util.getAbsoluteLeft(this.frame.canvas);
  8938. var frameTop = vis.util.getAbsoluteTop(this.frame.canvas);
  8939. var x = mouseX - frameLeft;
  8940. var y = mouseY - frameTop;
  8941. var translation = this._getTranslation();
  8942. var scaleFrac = scaleNew / scaleOld;
  8943. var tx = (1 - scaleFrac) * x + translation.x * scaleFrac;
  8944. var ty = (1 - scaleFrac) * y + translation.y * scaleFrac;
  8945. this._setScale(scaleNew);
  8946. this._setTranslation(tx, ty);
  8947. this._redraw();
  8948. }
  8949. // Prevent default actions caused by mouse wheel.
  8950. // That might be ugly, but we handle scrolls somehow
  8951. // anyway, so don't bother here...
  8952. vis.util.preventDefault(event);
  8953. };
  8954. /**
  8955. * Mouse move handler for checking whether the title moves over a node with a title.
  8956. * @param {Event} event
  8957. * @private
  8958. */
  8959. Graph.prototype._onMouseMoveTitle = function (event) {
  8960. event = event || window.event;
  8961. var startMouseX = event.clientX;
  8962. var startMouseY = event.clientY;
  8963. this.startFrameLeft = this.startFrameLeft || vis.util.getAbsoluteLeft(this.frame.canvas);
  8964. this.startFrameTop = this.startFrameTop || vis.util.getAbsoluteTop(this.frame.canvas);
  8965. var x = startMouseX - this.startFrameLeft;
  8966. var y = startMouseY - this.startFrameTop;
  8967. // check if the previously selected node is still selected
  8968. if (this.popupNode) {
  8969. this._checkHidePopup(x, y);
  8970. }
  8971. // start a timeout that will check if the mouse is positioned above
  8972. // an element
  8973. var me = this;
  8974. var checkShow = function() {
  8975. me._checkShowPopup(x, y);
  8976. };
  8977. if (this.popupTimer) {
  8978. clearInterval(this.popupTimer); // stop any running timer
  8979. }
  8980. if (!this.leftButtonDown) {
  8981. this.popupTimer = setTimeout(checkShow, 300);
  8982. }
  8983. };
  8984. /**
  8985. * Check if there is an element on the given position in the graph
  8986. * (a node or edge). If so, and if this element has a title,
  8987. * show a popup window with its title.
  8988. *
  8989. * @param {number} x
  8990. * @param {number} y
  8991. * @private
  8992. */
  8993. Graph.prototype._checkShowPopup = function (x, y) {
  8994. var obj = {
  8995. "left" : this._xToCanvas(x),
  8996. "top" : this._yToCanvas(y),
  8997. "right" : this._xToCanvas(x),
  8998. "bottom" : this._yToCanvas(y)
  8999. };
  9000. var id;
  9001. var lastPopupNode = this.popupNode;
  9002. if (this.popupNode == undefined) {
  9003. // search the nodes for overlap, select the top one in case of multiple nodes
  9004. var nodes = this.nodes;
  9005. for (id in nodes) {
  9006. if (nodes.hasOwnProperty(id)) {
  9007. var node = nodes[id];
  9008. if (node.getTitle() != undefined && node.isOverlappingWith(obj)) {
  9009. this.popupNode = node;
  9010. break;
  9011. }
  9012. }
  9013. }
  9014. }
  9015. if (this.popupNode == undefined) {
  9016. // search the edges for overlap
  9017. var edges = this.edges;
  9018. for (id in edges) {
  9019. if (edges.hasOwnProperty(id)) {
  9020. var edge = edges[id];
  9021. if (edge.connected && (edge.getTitle() != undefined) &&
  9022. edge.isOverlappingWith(obj)) {
  9023. this.popupNode = edge;
  9024. break;
  9025. }
  9026. }
  9027. }
  9028. }
  9029. if (this.popupNode) {
  9030. // show popup message window
  9031. if (this.popupNode != lastPopupNode) {
  9032. var me = this;
  9033. if (!me.popup) {
  9034. me.popup = new Popup(me.frame);
  9035. }
  9036. // adjust a small offset such that the mouse cursor is located in the
  9037. // bottom left location of the popup, and you can easily move over the
  9038. // popup area
  9039. me.popup.setPosition(x - 3, y - 3);
  9040. me.popup.setText(me.popupNode.getTitle());
  9041. me.popup.show();
  9042. }
  9043. }
  9044. else {
  9045. if (this.popup) {
  9046. this.popup.hide();
  9047. }
  9048. }
  9049. };
  9050. /**
  9051. * Check if the popup must be hided, which is the case when the mouse is no
  9052. * longer hovering on the object
  9053. * @param {number} x
  9054. * @param {number} y
  9055. * @private
  9056. */
  9057. Graph.prototype._checkHidePopup = function (x, y) {
  9058. var obj = {
  9059. "left" : x,
  9060. "top" : y,
  9061. "right" : x,
  9062. "bottom" : y
  9063. };
  9064. if (!this.popupNode || !this.popupNode.isOverlappingWith(obj) ) {
  9065. this.popupNode = undefined;
  9066. if (this.popup) {
  9067. this.popup.hide();
  9068. }
  9069. }
  9070. };
  9071. /**
  9072. * Event handler for touchstart event on mobile devices
  9073. * @param {Event} event
  9074. * @private
  9075. */
  9076. Graph.prototype._onTouchStart = function(event) {
  9077. vis.util.preventDefault(event);
  9078. if (this.touchDown) {
  9079. // if already moving, return
  9080. return;
  9081. }
  9082. this.touchDown = true;
  9083. var me = this;
  9084. if (!this.ontouchmove) {
  9085. this.ontouchmove = function (event) {me._onTouchMove(event);};
  9086. vis.util.addEventListener(document, "touchmove", this.ontouchmove);
  9087. }
  9088. if (!this.ontouchend) {
  9089. this.ontouchend = function (event) {me._onTouchEnd(event);};
  9090. vis.util.addEventListener(document, "touchend", this.ontouchend);
  9091. }
  9092. this._onMouseDown(event);
  9093. };
  9094. /**
  9095. * Event handler for touchmove event on mobile devices
  9096. * @param {Event} event
  9097. * @private
  9098. */
  9099. Graph.prototype._onTouchMove = function(event) {
  9100. vis.util.preventDefault(event);
  9101. this._onMouseMove(event);
  9102. };
  9103. /**
  9104. * Event handler for touchend event on mobile devices
  9105. * @param {Event} event
  9106. * @private
  9107. */
  9108. Graph.prototype._onTouchEnd = function(event) {
  9109. vis.util.preventDefault(event);
  9110. this.touchDown = false;
  9111. if (this.ontouchmove) {
  9112. vis.util.removeEventListener(document, "touchmove", this.ontouchmove);
  9113. this.ontouchmove = undefined;
  9114. }
  9115. if (this.ontouchend) {
  9116. vis.util.removeEventListener(document, "touchend", this.ontouchend);
  9117. this.ontouchend = undefined;
  9118. }
  9119. this._onMouseUp(event);
  9120. };
  9121. /**
  9122. * Unselect selected nodes. If no selection array is provided, all nodes
  9123. * are unselected
  9124. * @param {Object[]} selection Array with selection objects, each selection
  9125. * object has a parameter row. Optional
  9126. * @param {Boolean} triggerSelect If true (default), the select event
  9127. * is triggered when nodes are unselected
  9128. * @return {Boolean} changed True if the selection is changed
  9129. * @private
  9130. */
  9131. Graph.prototype._unselectNodes = function(selection, triggerSelect) {
  9132. var changed = false;
  9133. var i, iMax, id;
  9134. if (selection) {
  9135. // remove provided selections
  9136. for (i = 0, iMax = selection.length; i < iMax; i++) {
  9137. id = selection[i];
  9138. this.nodes[id].unselect();
  9139. var j = 0;
  9140. while (j < this.selection.length) {
  9141. if (this.selection[j] == id) {
  9142. this.selection.splice(j, 1);
  9143. changed = true;
  9144. }
  9145. else {
  9146. j++;
  9147. }
  9148. }
  9149. }
  9150. }
  9151. else if (this.selection && this.selection.length) {
  9152. // remove all selections
  9153. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  9154. id = this.selection[i];
  9155. this.nodes[id].unselect();
  9156. changed = true;
  9157. }
  9158. this.selection = [];
  9159. }
  9160. if (changed && (triggerSelect == true || triggerSelect == undefined)) {
  9161. // fire the select event
  9162. this._trigger('select');
  9163. }
  9164. return changed;
  9165. };
  9166. /**
  9167. * select all nodes on given location x, y
  9168. * @param {Array} selection an array with node ids
  9169. * @param {boolean} append If true, the new selection will be appended to the
  9170. * current selection (except for duplicate entries)
  9171. * @return {Boolean} changed True if the selection is changed
  9172. * @private
  9173. */
  9174. Graph.prototype._selectNodes = function(selection, append) {
  9175. var changed = false;
  9176. var i, iMax;
  9177. // TODO: the selectNodes method is a little messy, rework this
  9178. // check if the current selection equals the desired selection
  9179. var selectionAlreadyThere = true;
  9180. if (selection.length != this.selection.length) {
  9181. selectionAlreadyThere = false;
  9182. }
  9183. else {
  9184. for (i = 0, iMax = Math.min(selection.length, this.selection.length); i < iMax; i++) {
  9185. if (selection[i] != this.selection[i]) {
  9186. selectionAlreadyThere = false;
  9187. break;
  9188. }
  9189. }
  9190. }
  9191. if (selectionAlreadyThere) {
  9192. return changed;
  9193. }
  9194. if (append == undefined || append == false) {
  9195. // first deselect any selected node
  9196. var triggerSelect = false;
  9197. changed = this._unselectNodes(undefined, triggerSelect);
  9198. }
  9199. for (i = 0, iMax = selection.length; i < iMax; i++) {
  9200. // add each of the new selections, but only when they are not duplicate
  9201. var id = selection[i];
  9202. var isDuplicate = (this.selection.indexOf(id) != -1);
  9203. if (!isDuplicate) {
  9204. this.nodes[id].select();
  9205. this.selection.push(id);
  9206. changed = true;
  9207. }
  9208. }
  9209. if (changed) {
  9210. // fire the select event
  9211. this._trigger('select');
  9212. }
  9213. return changed;
  9214. };
  9215. /**
  9216. * retrieve all nodes overlapping with given object
  9217. * @param {Object} obj An object with parameters left, top, right, bottom
  9218. * @return {Object[]} An array with selection objects containing
  9219. * the parameter row.
  9220. * @private
  9221. */
  9222. Graph.prototype._getNodesOverlappingWith = function (obj) {
  9223. var nodes = this.nodes,
  9224. overlappingNodes = [];
  9225. for (var id in nodes) {
  9226. if (nodes.hasOwnProperty(id)) {
  9227. if (nodes[id].isOverlappingWith(obj)) {
  9228. overlappingNodes.push(id);
  9229. }
  9230. }
  9231. }
  9232. return overlappingNodes;
  9233. };
  9234. /**
  9235. * retrieve the currently selected nodes
  9236. * @return {Number[] | String[]} selection An array with the ids of the
  9237. * selected nodes.
  9238. */
  9239. Graph.prototype.getSelection = function() {
  9240. return this.selection.concat([]);
  9241. };
  9242. /**
  9243. * select zero or more nodes
  9244. * @param {Number[] | String[]} selection An array with the ids of the
  9245. * selected nodes.
  9246. */
  9247. Graph.prototype.setSelection = function(selection) {
  9248. var i, iMax, id;
  9249. if (selection.length == undefined)
  9250. throw "Selection must be an array with ids";
  9251. // first unselect any selected node
  9252. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  9253. id = this.selection[i];
  9254. this.nodes[id].unselect();
  9255. }
  9256. this.selection = [];
  9257. for (i = 0, iMax = selection.length; i < iMax; i++) {
  9258. id = selection[i];
  9259. var node = this.nodes[id];
  9260. if (!node) {
  9261. throw new RangeError('Node with id "' + id + '" not found');
  9262. }
  9263. node.select();
  9264. this.selection.push(id);
  9265. }
  9266. this.redraw();
  9267. };
  9268. /**
  9269. * Validate the selection: remove ids of nodes which no longer exist
  9270. * @private
  9271. */
  9272. Graph.prototype._updateSelection = function () {
  9273. var i = 0;
  9274. while (i < this.selection.length) {
  9275. var id = this.selection[i];
  9276. if (!this.nodes[id]) {
  9277. this.selection.splice(i, 1);
  9278. }
  9279. else {
  9280. i++;
  9281. }
  9282. }
  9283. };
  9284. /**
  9285. * Temporary method to test calculating a hub value for the nodes
  9286. * @param {number} level Maximum number edges between two nodes in order
  9287. * to call them connected. Optional, 1 by default
  9288. * @return {Number[]} connectioncount array with the connection count
  9289. * for each node
  9290. * @private
  9291. */
  9292. Graph.prototype._getConnectionCount = function(level) {
  9293. if (level == undefined) {
  9294. level = 1;
  9295. }
  9296. // get the nodes connected to given nodes
  9297. function getConnectedNodes(nodes) {
  9298. var connectedNodes = [];
  9299. for (var j = 0, jMax = nodes.length; j < jMax; j++) {
  9300. var node = nodes[j];
  9301. // find all nodes connected to this node
  9302. var edges = node.edges;
  9303. for (var i = 0, iMax = edges.length; i < iMax; i++) {
  9304. var edge = edges[i];
  9305. var other = null;
  9306. // check if connected
  9307. if (edge.from == node)
  9308. other = edge.to;
  9309. else if (edge.to == node)
  9310. other = edge.from;
  9311. // check if the other node is not already in the list with nodes
  9312. var k, kMax;
  9313. if (other) {
  9314. for (k = 0, kMax = nodes.length; k < kMax; k++) {
  9315. if (nodes[k] == other) {
  9316. other = null;
  9317. break;
  9318. }
  9319. }
  9320. }
  9321. if (other) {
  9322. for (k = 0, kMax = connectedNodes.length; k < kMax; k++) {
  9323. if (connectedNodes[k] == other) {
  9324. other = null;
  9325. break;
  9326. }
  9327. }
  9328. }
  9329. if (other)
  9330. connectedNodes.push(other);
  9331. }
  9332. }
  9333. return connectedNodes;
  9334. }
  9335. var connections = [];
  9336. var nodes = this.nodes;
  9337. for (var id in nodes) {
  9338. if (nodes.hasOwnProperty(id)) {
  9339. var c = [nodes[id]];
  9340. for (var l = 0; l < level; l++) {
  9341. c = c.concat(getConnectedNodes(c));
  9342. }
  9343. connections.push(c);
  9344. }
  9345. }
  9346. var hubs = [];
  9347. for (var i = 0, len = connections.length; i < len; i++) {
  9348. hubs.push(connections[i].length);
  9349. }
  9350. return hubs;
  9351. };
  9352. /**
  9353. * Set a new size for the graph
  9354. * @param {string} width Width in pixels or percentage (for example "800px"
  9355. * or "50%")
  9356. * @param {string} height Height in pixels or percentage (for example "400px"
  9357. * or "30%")
  9358. */
  9359. Graph.prototype.setSize = function(width, height) {
  9360. this.frame.style.width = width;
  9361. this.frame.style.height = height;
  9362. this.frame.canvas.style.width = "100%";
  9363. this.frame.canvas.style.height = "100%";
  9364. this.frame.canvas.width = this.frame.canvas.clientWidth;
  9365. this.frame.canvas.height = this.frame.canvas.clientHeight;
  9366. };
  9367. /**
  9368. * Set a data set with nodes for the graph
  9369. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  9370. * @private
  9371. */
  9372. Graph.prototype._setNodes = function(nodes) {
  9373. var oldNodesData = this.nodesData;
  9374. if (nodes instanceof DataSet || nodes instanceof DataView) {
  9375. this.nodesData = nodes;
  9376. }
  9377. else if (nodes instanceof Array) {
  9378. this.nodesData = new DataSet();
  9379. this.nodesData.add(nodes);
  9380. }
  9381. else if (!nodes) {
  9382. this.nodesData = new DataSet();
  9383. }
  9384. else {
  9385. throw new TypeError('Array or DataSet expected');
  9386. }
  9387. if (oldNodesData) {
  9388. // unsubscribe from old dataset
  9389. util.forEach(this.nodesListeners, function (callback, event) {
  9390. oldNodesData.unsubscribe(event, callback);
  9391. });
  9392. }
  9393. // remove drawn nodes
  9394. this.nodes = {};
  9395. if (this.nodesData) {
  9396. // subscribe to new dataset
  9397. var me = this;
  9398. util.forEach(this.nodesListeners, function (callback, event) {
  9399. me.nodesData.subscribe(event, callback);
  9400. });
  9401. // draw all new nodes
  9402. var ids = this.nodesData.getIds();
  9403. this._addNodes(ids);
  9404. }
  9405. this._updateSelection();
  9406. };
  9407. /**
  9408. * Add nodes
  9409. * @param {Number[] | String[]} ids
  9410. * @private
  9411. */
  9412. Graph.prototype._addNodes = function(ids) {
  9413. var id;
  9414. for (var i = 0, len = ids.length; i < len; i++) {
  9415. id = ids[i];
  9416. var data = this.nodesData.get(id);
  9417. var node = new Node(data, this.images, this.groups, this.constants);
  9418. this.nodes[id] = node; // note: this may replace an existing node
  9419. if (!node.isFixed()) {
  9420. // TODO: position new nodes in a smarter way!
  9421. var radius = this.constants.edges.length * 2;
  9422. var count = ids.length;
  9423. var angle = 2 * Math.PI * (i / count);
  9424. node.x = radius * Math.cos(angle);
  9425. node.y = radius * Math.sin(angle);
  9426. // note: no not use node.isMoving() here, as that gives the current
  9427. // velocity of the node, which is zero after creation of the node.
  9428. this.moving = true;
  9429. }
  9430. }
  9431. this._reconnectEdges();
  9432. this._updateValueRange(this.nodes);
  9433. };
  9434. /**
  9435. * Update existing nodes, or create them when not yet existing
  9436. * @param {Number[] | String[]} ids
  9437. * @private
  9438. */
  9439. Graph.prototype._updateNodes = function(ids) {
  9440. var nodes = this.nodes,
  9441. nodesData = this.nodesData;
  9442. for (var i = 0, len = ids.length; i < len; i++) {
  9443. var id = ids[i];
  9444. var node = nodes[id];
  9445. var data = nodesData.get(id);
  9446. if (node) {
  9447. // update node
  9448. node.setProperties(data, this.constants);
  9449. }
  9450. else {
  9451. // create node
  9452. node = new Node(properties, this.images, this.groups, this.constants);
  9453. nodes[id] = node;
  9454. if (!node.isFixed()) {
  9455. this.moving = true;
  9456. }
  9457. }
  9458. }
  9459. this._reconnectEdges();
  9460. this._updateValueRange(nodes);
  9461. };
  9462. /**
  9463. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  9464. * @param {Number[] | String[]} ids
  9465. * @private
  9466. */
  9467. Graph.prototype._removeNodes = function(ids) {
  9468. var nodes = this.nodes;
  9469. for (var i = 0, len = ids.length; i < len; i++) {
  9470. var id = ids[i];
  9471. delete nodes[id];
  9472. }
  9473. this._reconnectEdges();
  9474. this._updateSelection();
  9475. this._updateValueRange(nodes);
  9476. };
  9477. /**
  9478. * Load edges by reading the data table
  9479. * @param {Array | DataSet | DataView} edges The data containing the edges.
  9480. * @private
  9481. * @private
  9482. */
  9483. Graph.prototype._setEdges = function(edges) {
  9484. var oldEdgesData = this.edgesData;
  9485. if (edges instanceof DataSet || edges instanceof DataView) {
  9486. this.edgesData = edges;
  9487. }
  9488. else if (edges instanceof Array) {
  9489. this.edgesData = new DataSet();
  9490. this.edgesData.add(edges);
  9491. }
  9492. else if (!edges) {
  9493. this.edgesData = new DataSet();
  9494. }
  9495. else {
  9496. throw new TypeError('Array or DataSet expected');
  9497. }
  9498. if (oldEdgesData) {
  9499. // unsubscribe from old dataset
  9500. util.forEach(this.edgesListeners, function (callback, event) {
  9501. oldEdgesData.unsubscribe(event, callback);
  9502. });
  9503. }
  9504. // remove drawn edges
  9505. this.edges = {};
  9506. if (this.edgesData) {
  9507. // subscribe to new dataset
  9508. var me = this;
  9509. util.forEach(this.edgesListeners, function (callback, event) {
  9510. me.edgesData.subscribe(event, callback);
  9511. });
  9512. // draw all new nodes
  9513. var ids = this.edgesData.getIds();
  9514. this._addEdges(ids);
  9515. }
  9516. this._reconnectEdges();
  9517. };
  9518. /**
  9519. * Add edges
  9520. * @param {Number[] | String[]} ids
  9521. * @private
  9522. */
  9523. Graph.prototype._addEdges = function (ids) {
  9524. var edges = this.edges,
  9525. edgesData = this.edgesData;
  9526. for (var i = 0, len = ids.length; i < len; i++) {
  9527. var id = ids[i];
  9528. var oldEdge = edges[id];
  9529. if (oldEdge) {
  9530. oldEdge.disconnect();
  9531. }
  9532. var data = edgesData.get(id);
  9533. edges[id] = new Edge(data, this, this.constants);
  9534. }
  9535. this.moving = true;
  9536. this._updateValueRange(edges);
  9537. };
  9538. /**
  9539. * Update existing edges, or create them when not yet existing
  9540. * @param {Number[] | String[]} ids
  9541. * @private
  9542. */
  9543. Graph.prototype._updateEdges = function (ids) {
  9544. var edges = this.edges,
  9545. edgesData = this.edgesData;
  9546. for (var i = 0, len = ids.length; i < len; i++) {
  9547. var id = ids[i];
  9548. var data = edgesData.get(id);
  9549. var edge = edges[id];
  9550. if (edge) {
  9551. // update edge
  9552. edge.disconnect();
  9553. edge.setProperties(data, this.constants);
  9554. edge.connect();
  9555. }
  9556. else {
  9557. // create edge
  9558. edge = new Edge(data, this, this.constants);
  9559. this.edges[id] = edge;
  9560. }
  9561. }
  9562. this.moving = true;
  9563. this._updateValueRange(edges);
  9564. };
  9565. /**
  9566. * Remove existing edges. Non existing ids will be ignored
  9567. * @param {Number[] | String[]} ids
  9568. * @private
  9569. */
  9570. Graph.prototype._removeEdges = function (ids) {
  9571. var edges = this.edges;
  9572. for (var i = 0, len = ids.length; i < len; i++) {
  9573. var id = ids[i];
  9574. var edge = edges[id];
  9575. if (edge) {
  9576. edge.disconnect();
  9577. delete edges[id];
  9578. }
  9579. }
  9580. this.moving = true;
  9581. this._updateValueRange(edges);
  9582. };
  9583. /**
  9584. * Reconnect all edges
  9585. * @private
  9586. */
  9587. Graph.prototype._reconnectEdges = function() {
  9588. var id,
  9589. nodes = this.nodes,
  9590. edges = this.edges;
  9591. for (id in nodes) {
  9592. if (nodes.hasOwnProperty(id)) {
  9593. nodes[id].edges = [];
  9594. }
  9595. }
  9596. for (id in edges) {
  9597. if (edges.hasOwnProperty(id)) {
  9598. var edge = edges[id];
  9599. edge.from = null;
  9600. edge.to = null;
  9601. edge.connect();
  9602. }
  9603. }
  9604. };
  9605. /**
  9606. * Update the values of all object in the given array according to the current
  9607. * value range of the objects in the array.
  9608. * @param {Object} obj An object containing a set of Edges or Nodes
  9609. * The objects must have a method getValue() and
  9610. * setValueRange(min, max).
  9611. * @private
  9612. */
  9613. Graph.prototype._updateValueRange = function(obj) {
  9614. var id;
  9615. // determine the range of the objects
  9616. var valueMin = undefined;
  9617. var valueMax = undefined;
  9618. for (id in obj) {
  9619. if (obj.hasOwnProperty(id)) {
  9620. var value = obj[id].getValue();
  9621. if (value !== undefined) {
  9622. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  9623. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  9624. }
  9625. }
  9626. }
  9627. // adjust the range of all objects
  9628. if (valueMin !== undefined && valueMax !== undefined) {
  9629. for (id in obj) {
  9630. if (obj.hasOwnProperty(id)) {
  9631. obj[id].setValueRange(valueMin, valueMax);
  9632. }
  9633. }
  9634. }
  9635. };
  9636. /**
  9637. * Redraw the graph with the current data
  9638. * chart will be resized too.
  9639. */
  9640. Graph.prototype.redraw = function() {
  9641. this.setSize(this.width, this.height);
  9642. this._redraw();
  9643. };
  9644. /**
  9645. * Redraw the graph with the current data
  9646. * @private
  9647. */
  9648. Graph.prototype._redraw = function() {
  9649. var ctx = this.frame.canvas.getContext("2d");
  9650. // clear the canvas
  9651. var w = this.frame.canvas.width;
  9652. var h = this.frame.canvas.height;
  9653. ctx.clearRect(0, 0, w, h);
  9654. // set scaling and translation
  9655. ctx.save();
  9656. ctx.translate(this.translation.x, this.translation.y);
  9657. ctx.scale(this.scale, this.scale);
  9658. this._drawEdges(ctx);
  9659. this._drawNodes(ctx);
  9660. // restore original scaling and translation
  9661. ctx.restore();
  9662. };
  9663. /**
  9664. * Set the translation of the graph
  9665. * @param {Number} offsetX Horizontal offset
  9666. * @param {Number} offsetY Vertical offset
  9667. * @private
  9668. */
  9669. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  9670. if (this.translation === undefined) {
  9671. this.translation = {
  9672. "x": 0,
  9673. "y": 0
  9674. };
  9675. }
  9676. if (offsetX !== undefined) {
  9677. this.translation.x = offsetX;
  9678. }
  9679. if (offsetY !== undefined) {
  9680. this.translation.y = offsetY;
  9681. }
  9682. };
  9683. /**
  9684. * Get the translation of the graph
  9685. * @return {Object} translation An object with parameters x and y, both a number
  9686. * @private
  9687. */
  9688. Graph.prototype._getTranslation = function() {
  9689. return {
  9690. "x": this.translation.x,
  9691. "y": this.translation.y
  9692. };
  9693. };
  9694. /**
  9695. * Scale the graph
  9696. * @param {Number} scale Scaling factor 1.0 is unscaled
  9697. * @private
  9698. */
  9699. Graph.prototype._setScale = function(scale) {
  9700. this.scale = scale;
  9701. };
  9702. /**
  9703. * Get the current scale of the graph
  9704. * @return {Number} scale Scaling factor 1.0 is unscaled
  9705. * @private
  9706. */
  9707. Graph.prototype._getScale = function() {
  9708. return this.scale;
  9709. };
  9710. Graph.prototype._xToCanvas = function(x) {
  9711. return (x - this.translation.x) / this.scale;
  9712. };
  9713. Graph.prototype._canvasToX = function(x) {
  9714. return x * this.scale + this.translation.x;
  9715. };
  9716. Graph.prototype._yToCanvas = function(y) {
  9717. return (y - this.translation.y) / this.scale;
  9718. };
  9719. Graph.prototype._canvasToY = function(y) {
  9720. return y * this.scale + this.translation.y ;
  9721. };
  9722. /**
  9723. * Redraw all nodes
  9724. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9725. * @param {CanvasRenderingContext2D} ctx
  9726. * @private
  9727. */
  9728. Graph.prototype._drawNodes = function(ctx) {
  9729. // first draw the unselected nodes
  9730. var nodes = this.nodes;
  9731. var selected = [];
  9732. for (var id in nodes) {
  9733. if (nodes.hasOwnProperty(id)) {
  9734. if (nodes[id].isSelected()) {
  9735. selected.push(id);
  9736. }
  9737. else {
  9738. nodes[id].draw(ctx);
  9739. }
  9740. }
  9741. }
  9742. // draw the selected nodes on top
  9743. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  9744. nodes[selected[s]].draw(ctx);
  9745. }
  9746. };
  9747. /**
  9748. * Redraw all edges
  9749. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9750. * @param {CanvasRenderingContext2D} ctx
  9751. * @private
  9752. */
  9753. Graph.prototype._drawEdges = function(ctx) {
  9754. var edges = this.edges;
  9755. for (var id in edges) {
  9756. if (edges.hasOwnProperty(id)) {
  9757. var edge = edges[id];
  9758. if (edge.connected) {
  9759. edges[id].draw(ctx);
  9760. }
  9761. }
  9762. }
  9763. };
  9764. /**
  9765. * Find a stable position for all nodes
  9766. * @private
  9767. */
  9768. Graph.prototype._doStabilize = function() {
  9769. var start = new Date();
  9770. // find stable position
  9771. var count = 0;
  9772. var vmin = this.constants.minVelocity;
  9773. var stable = false;
  9774. while (!stable && count < this.constants.maxIterations) {
  9775. this._calculateForces();
  9776. this._discreteStepNodes();
  9777. stable = !this._isMoving(vmin);
  9778. count++;
  9779. }
  9780. var end = new Date();
  9781. // console.log("Stabilized in " + (end-start) + " ms, " + count + " iterations" ); // TODO: cleanup
  9782. };
  9783. /**
  9784. * Calculate the external forces acting on the nodes
  9785. * Forces are caused by: edges, repulsing forces between nodes, gravity
  9786. * @private
  9787. */
  9788. Graph.prototype._calculateForces = function() {
  9789. // create a local edge to the nodes and edges, that is faster
  9790. var id, dx, dy, angle, distance, fx, fy,
  9791. repulsingForce, springForce, length, edgeLength,
  9792. nodes = this.nodes,
  9793. edges = this.edges;
  9794. // gravity, add a small constant force to pull the nodes towards the center of
  9795. // the graph
  9796. // Also, the forces are reset to zero in this loop by using _setForce instead
  9797. // of _addForce
  9798. var gravity = 0.01,
  9799. gx = this.frame.canvas.clientWidth / 2,
  9800. gy = this.frame.canvas.clientHeight / 2;
  9801. for (id in nodes) {
  9802. if (nodes.hasOwnProperty(id)) {
  9803. var node = nodes[id];
  9804. dx = gx - node.x;
  9805. dy = gy - node.y;
  9806. angle = Math.atan2(dy, dx);
  9807. fx = Math.cos(angle) * gravity;
  9808. fy = Math.sin(angle) * gravity;
  9809. node._setForce(fx, fy);
  9810. }
  9811. }
  9812. // repulsing forces between nodes
  9813. var minimumDistance = this.constants.nodes.distance,
  9814. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  9815. for (var id1 in nodes) {
  9816. if (nodes.hasOwnProperty(id1)) {
  9817. var node1 = nodes[id1];
  9818. for (var id2 in nodes) {
  9819. if (nodes.hasOwnProperty(id2)) {
  9820. var node2 = nodes[id2];
  9821. // calculate normally distributed force
  9822. dx = node2.x - node1.x;
  9823. dy = node2.y - node1.y;
  9824. distance = Math.sqrt(dx * dx + dy * dy);
  9825. angle = Math.atan2(dy, dx);
  9826. // TODO: correct factor for repulsing force
  9827. //repulsingForce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  9828. //repulsingForce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  9829. repulsingForce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)); // TODO: customize the repulsing force
  9830. fx = Math.cos(angle) * repulsingForce;
  9831. fy = Math.sin(angle) * repulsingForce;
  9832. node1._addForce(-fx, -fy);
  9833. node2._addForce(fx, fy);
  9834. }
  9835. }
  9836. }
  9837. }
  9838. /* TODO: re-implement repulsion of edges
  9839. for (var n = 0; n < nodes.length; n++) {
  9840. for (var l = 0; l < edges.length; l++) {
  9841. var lx = edges[l].from.x+(edges[l].to.x - edges[l].from.x)/2,
  9842. ly = edges[l].from.y+(edges[l].to.y - edges[l].from.y)/2,
  9843. // calculate normally distributed force
  9844. dx = nodes[n].x - lx,
  9845. dy = nodes[n].y - ly,
  9846. distance = Math.sqrt(dx * dx + dy * dy),
  9847. angle = Math.atan2(dy, dx),
  9848. // TODO: correct factor for repulsing force
  9849. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  9850. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  9851. repulsingforce = 1 / (1 + Math.exp((distance / (minimumDistance / 2) - 1) * steepness)), // TODO: customize the repulsing force
  9852. fx = Math.cos(angle) * repulsingforce,
  9853. fy = Math.sin(angle) * repulsingforce;
  9854. nodes[n]._addForce(fx, fy);
  9855. edges[l].from._addForce(-fx/2,-fy/2);
  9856. edges[l].to._addForce(-fx/2,-fy/2);
  9857. }
  9858. }
  9859. */
  9860. // forces caused by the edges, modelled as springs
  9861. for (id in edges) {
  9862. if (edges.hasOwnProperty(id)) {
  9863. var edge = edges[id];
  9864. if (edge.connected) {
  9865. dx = (edge.to.x - edge.from.x);
  9866. dy = (edge.to.y - edge.from.y);
  9867. //edgeLength = (edge.from.width + edge.from.height + edge.to.width + edge.to.height)/2 || edge.length; // TODO: dmin
  9868. //edgeLength = (edge.from.width + edge.to.width)/2 || edge.length; // TODO: dmin
  9869. //edgeLength = 20 + ((edge.from.width + edge.to.width) || 0) / 2;
  9870. edgeLength = edge.length;
  9871. length = Math.sqrt(dx * dx + dy * dy);
  9872. angle = Math.atan2(dy, dx);
  9873. springForce = edge.stiffness * (edgeLength - length);
  9874. fx = Math.cos(angle) * springForce;
  9875. fy = Math.sin(angle) * springForce;
  9876. edge.from._addForce(-fx, -fy);
  9877. edge.to._addForce(fx, fy);
  9878. }
  9879. }
  9880. }
  9881. /* TODO: re-implement repulsion of edges
  9882. // repulsing forces between edges
  9883. var minimumDistance = this.constants.edges.distance,
  9884. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  9885. for (var l = 0; l < edges.length; l++) {
  9886. //Keep distance from other edge centers
  9887. for (var l2 = l + 1; l2 < this.edges.length; l2++) {
  9888. //var dmin = (nodes[n].width + nodes[n].height + nodes[n2].width + nodes[n2].height) / 1 || minimumDistance, // TODO: dmin
  9889. //var dmin = (nodes[n].width + nodes[n2].width)/2 || minimumDistance, // TODO: dmin
  9890. //dmin = 40 + ((nodes[n].width/2 + nodes[n2].width/2) || 0),
  9891. var lx = edges[l].from.x+(edges[l].to.x - edges[l].from.x)/2,
  9892. ly = edges[l].from.y+(edges[l].to.y - edges[l].from.y)/2,
  9893. l2x = edges[l2].from.x+(edges[l2].to.x - edges[l2].from.x)/2,
  9894. l2y = edges[l2].from.y+(edges[l2].to.y - edges[l2].from.y)/2,
  9895. // calculate normally distributed force
  9896. dx = l2x - lx,
  9897. dy = l2y - ly,
  9898. distance = Math.sqrt(dx * dx + dy * dy),
  9899. angle = Math.atan2(dy, dx),
  9900. // TODO: correct factor for repulsing force
  9901. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  9902. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  9903. repulsingforce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)), // TODO: customize the repulsing force
  9904. fx = Math.cos(angle) * repulsingforce,
  9905. fy = Math.sin(angle) * repulsingforce;
  9906. edges[l].from._addForce(-fx, -fy);
  9907. edges[l].to._addForce(-fx, -fy);
  9908. edges[l2].from._addForce(fx, fy);
  9909. edges[l2].to._addForce(fx, fy);
  9910. }
  9911. }
  9912. */
  9913. };
  9914. /**
  9915. * Check if any of the nodes is still moving
  9916. * @param {number} vmin the minimum velocity considered as "moving"
  9917. * @return {boolean} true if moving, false if non of the nodes is moving
  9918. * @private
  9919. */
  9920. Graph.prototype._isMoving = function(vmin) {
  9921. // TODO: ismoving does not work well: should check the kinetic energy, not its velocity
  9922. var nodes = this.nodes;
  9923. for (var id in nodes) {
  9924. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  9925. return true;
  9926. }
  9927. }
  9928. return false;
  9929. };
  9930. /**
  9931. * Perform one discrete step for all nodes
  9932. * @private
  9933. */
  9934. Graph.prototype._discreteStepNodes = function() {
  9935. var interval = this.refreshRate / 1000.0; // in seconds
  9936. var nodes = this.nodes;
  9937. for (var id in nodes) {
  9938. if (nodes.hasOwnProperty(id)) {
  9939. nodes[id].discreteStep(interval);
  9940. }
  9941. }
  9942. };
  9943. /**
  9944. * Start animating nodes and edges
  9945. */
  9946. Graph.prototype.start = function() {
  9947. if (this.moving) {
  9948. this._calculateForces();
  9949. this._discreteStepNodes();
  9950. var vmin = this.constants.minVelocity;
  9951. this.moving = this._isMoving(vmin);
  9952. }
  9953. if (this.moving) {
  9954. // start animation. only start timer if it is not already running
  9955. if (!this.timer) {
  9956. var graph = this;
  9957. this.timer = window.setTimeout(function () {
  9958. graph.timer = undefined;
  9959. graph.start();
  9960. graph._redraw();
  9961. }, this.refreshRate);
  9962. }
  9963. }
  9964. else {
  9965. this._redraw();
  9966. }
  9967. };
  9968. /**
  9969. * Stop animating nodes and edges.
  9970. */
  9971. Graph.prototype.stop = function () {
  9972. if (this.timer) {
  9973. window.clearInterval(this.timer);
  9974. this.timer = undefined;
  9975. }
  9976. };
  9977. /**
  9978. * vis.js module exports
  9979. */
  9980. var vis = {
  9981. util: util,
  9982. events: events,
  9983. Controller: Controller,
  9984. DataSet: DataSet,
  9985. DataView: DataView,
  9986. Range: Range,
  9987. Stack: Stack,
  9988. TimeStep: TimeStep,
  9989. EventBus: EventBus,
  9990. components: {
  9991. items: {
  9992. Item: Item,
  9993. ItemBox: ItemBox,
  9994. ItemPoint: ItemPoint,
  9995. ItemRange: ItemRange
  9996. },
  9997. Component: Component,
  9998. Panel: Panel,
  9999. RootPanel: RootPanel,
  10000. ItemSet: ItemSet,
  10001. TimeAxis: TimeAxis
  10002. },
  10003. graph: {
  10004. Node: Node,
  10005. Edge: Edge,
  10006. Popup: Popup,
  10007. Groups: Groups,
  10008. Images: Images
  10009. },
  10010. Timeline: Timeline,
  10011. Graph: Graph
  10012. };
  10013. /**
  10014. * CommonJS module exports
  10015. */
  10016. if (typeof exports !== 'undefined') {
  10017. exports = vis;
  10018. }
  10019. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  10020. module.exports = vis;
  10021. }
  10022. /**
  10023. * AMD module exports
  10024. */
  10025. if (typeof(define) === 'function') {
  10026. define(function () {
  10027. return vis;
  10028. });
  10029. }
  10030. /**
  10031. * Window exports
  10032. */
  10033. if (typeof window !== 'undefined') {
  10034. // attach the module to the window, load as a regular javascript file
  10035. window['vis'] = vis;
  10036. }
  10037. // inject css
  10038. util.loadCss("/* vis.js stylesheet */\n.vis.timeline {\n}\n\n\n.vis.timeline.rootpanel {\n position: relative;\n overflow: hidden;\n\n border: 1px solid #bfbfbf;\n -moz-box-sizing: border-box;\n box-sizing: border-box;\n}\n\n.vis.timeline .panel {\n position: absolute;\n overflow: hidden;\n}\n\n\n.vis.timeline .groupset {\n position: absolute;\n padding: 0;\n margin: 0;\n}\n\n.vis.timeline .labels {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n\n padding: 0;\n margin: 0;\n\n border-right: 1px solid #bfbfbf;\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n}\n\n.vis.timeline .labels .label {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n border-bottom: 1px solid #bfbfbf;\n color: #4d4d4d;\n}\n\n.vis.timeline .labels .label .inner {\n display: inline-block;\n padding: 5px;\n}\n\n\n.vis.timeline .itemset {\n position: absolute;\n padding: 0;\n margin: 0;\n overflow: hidden;\n}\n\n.vis.timeline .background {\n}\n\n.vis.timeline .foreground {\n}\n\n.vis.timeline .itemset-axis {\n position: absolute;\n}\n\n.vis.timeline .groupset .itemset-axis {\n border-top: 1px solid #bfbfbf;\n}\n\n/* TODO: with orientation=='bottom', this will more or less overlap with timeline axis\n.vis.timeline .groupset .itemset-axis:last-child {\n border-top: none;\n}\n*/\n\n\n.vis.timeline .item {\n position: absolute;\n color: #1A1A1A;\n border-color: #97B0F8;\n background-color: #D5DDF6;\n display: inline-block;\n}\n\n.vis.timeline .item.selected {\n border-color: #FFC200;\n background-color: #FFF785;\n z-index: 999;\n}\n\n.vis.timeline .item.cluster {\n /* TODO: use another color or pattern? */\n background: #97B0F8 url('img/cluster_bg.png');\n color: white;\n}\n.vis.timeline .item.cluster.point {\n border-color: #D5DDF6;\n}\n\n.vis.timeline .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.vis.timeline .item.point {\n background: none;\n}\n\n.vis.timeline .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.vis.timeline .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.vis.timeline .item.range .drag-left {\n cursor: w-resize;\n z-index: 1000;\n}\n\n.vis.timeline .item.range .drag-right {\n cursor: e-resize;\n z-index: 1000;\n}\n\n.vis.timeline .item.range .content {\n position: relative;\n display: inline-block;\n}\n\n.vis.timeline .item.line {\n position: absolute;\n width: 0;\n border-left-width: 1px;\n border-left-style: solid;\n}\n\n.vis.timeline .item .content {\n margin: 5px;\n white-space: nowrap;\n overflow: hidden;\n}\n\n.vis.timeline .axis {\n position: relative;\n}\n\n.vis.timeline .axis .text {\n position: absolute;\n color: #4d4d4d;\n padding: 3px;\n white-space: nowrap;\n}\n\n.vis.timeline .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.vis.timeline .axis .grid.vertical {\n position: absolute;\n width: 0;\n border-right: 1px solid;\n}\n\n.vis.timeline .axis .grid.horizontal {\n position: absolute;\n left: 0;\n width: 100%;\n height: 0;\n border-bottom: 1px solid;\n}\n\n.vis.timeline .axis .grid.minor {\n border-color: #e5e5e5;\n}\n\n.vis.timeline .axis .grid.major {\n border-color: #bfbfbf;\n}\n\n");
  10039. })()
  10040. },{"moment":2}],2:[function(require,module,exports){
  10041. (function(){// moment.js
  10042. // version : 2.0.0
  10043. // author : Tim Wood
  10044. // license : MIT
  10045. // momentjs.com
  10046. (function (undefined) {
  10047. /************************************
  10048. Constants
  10049. ************************************/
  10050. var moment,
  10051. VERSION = "2.0.0",
  10052. round = Math.round, i,
  10053. // internal storage for language config files
  10054. languages = {},
  10055. // check for nodeJS
  10056. hasModule = (typeof module !== 'undefined' && module.exports),
  10057. // ASP.NET json date format regex
  10058. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  10059. // format tokens
  10060. 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,
  10061. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  10062. // parsing tokens
  10063. parseMultipleFormatChunker = /([0-9a-zA-Z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)/gi,
  10064. // parsing token regexes
  10065. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  10066. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  10067. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  10068. parseTokenFourDigits = /\d{1,4}/, // 0 - 9999
  10069. parseTokenSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  10070. 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.
  10071. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/i, // +00:00 -00:00 +0000 -0000 or Z
  10072. parseTokenT = /T/i, // T (ISO seperator)
  10073. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  10074. // preliminary iso regex
  10075. // 0000-00-00 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000
  10076. isoRegex = /^\s*\d{4}-\d\d-\d\d((T| )(\d\d(:\d\d(:\d\d(\.\d\d?\d?)?)?)?)?([\+\-]\d\d:?\d\d)?)?/,
  10077. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  10078. // iso time formats and regexes
  10079. isoTimes = [
  10080. ['HH:mm:ss.S', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/],
  10081. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  10082. ['HH:mm', /(T| )\d\d:\d\d/],
  10083. ['HH', /(T| )\d\d/]
  10084. ],
  10085. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  10086. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  10087. // getter and setter names
  10088. proxyGettersAndSetters = 'Month|Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  10089. unitMillisecondFactors = {
  10090. 'Milliseconds' : 1,
  10091. 'Seconds' : 1e3,
  10092. 'Minutes' : 6e4,
  10093. 'Hours' : 36e5,
  10094. 'Days' : 864e5,
  10095. 'Months' : 2592e6,
  10096. 'Years' : 31536e6
  10097. },
  10098. // format function strings
  10099. formatFunctions = {},
  10100. // tokens to ordinalize and pad
  10101. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  10102. paddedTokens = 'M D H h m s w W'.split(' '),
  10103. formatTokenFunctions = {
  10104. M : function () {
  10105. return this.month() + 1;
  10106. },
  10107. MMM : function (format) {
  10108. return this.lang().monthsShort(this, format);
  10109. },
  10110. MMMM : function (format) {
  10111. return this.lang().months(this, format);
  10112. },
  10113. D : function () {
  10114. return this.date();
  10115. },
  10116. DDD : function () {
  10117. return this.dayOfYear();
  10118. },
  10119. d : function () {
  10120. return this.day();
  10121. },
  10122. dd : function (format) {
  10123. return this.lang().weekdaysMin(this, format);
  10124. },
  10125. ddd : function (format) {
  10126. return this.lang().weekdaysShort(this, format);
  10127. },
  10128. dddd : function (format) {
  10129. return this.lang().weekdays(this, format);
  10130. },
  10131. w : function () {
  10132. return this.week();
  10133. },
  10134. W : function () {
  10135. return this.isoWeek();
  10136. },
  10137. YY : function () {
  10138. return leftZeroFill(this.year() % 100, 2);
  10139. },
  10140. YYYY : function () {
  10141. return leftZeroFill(this.year(), 4);
  10142. },
  10143. YYYYY : function () {
  10144. return leftZeroFill(this.year(), 5);
  10145. },
  10146. a : function () {
  10147. return this.lang().meridiem(this.hours(), this.minutes(), true);
  10148. },
  10149. A : function () {
  10150. return this.lang().meridiem(this.hours(), this.minutes(), false);
  10151. },
  10152. H : function () {
  10153. return this.hours();
  10154. },
  10155. h : function () {
  10156. return this.hours() % 12 || 12;
  10157. },
  10158. m : function () {
  10159. return this.minutes();
  10160. },
  10161. s : function () {
  10162. return this.seconds();
  10163. },
  10164. S : function () {
  10165. return ~~(this.milliseconds() / 100);
  10166. },
  10167. SS : function () {
  10168. return leftZeroFill(~~(this.milliseconds() / 10), 2);
  10169. },
  10170. SSS : function () {
  10171. return leftZeroFill(this.milliseconds(), 3);
  10172. },
  10173. Z : function () {
  10174. var a = -this.zone(),
  10175. b = "+";
  10176. if (a < 0) {
  10177. a = -a;
  10178. b = "-";
  10179. }
  10180. return b + leftZeroFill(~~(a / 60), 2) + ":" + leftZeroFill(~~a % 60, 2);
  10181. },
  10182. ZZ : function () {
  10183. var a = -this.zone(),
  10184. b = "+";
  10185. if (a < 0) {
  10186. a = -a;
  10187. b = "-";
  10188. }
  10189. return b + leftZeroFill(~~(10 * a / 6), 4);
  10190. },
  10191. X : function () {
  10192. return this.unix();
  10193. }
  10194. };
  10195. function padToken(func, count) {
  10196. return function (a) {
  10197. return leftZeroFill(func.call(this, a), count);
  10198. };
  10199. }
  10200. function ordinalizeToken(func) {
  10201. return function (a) {
  10202. return this.lang().ordinal(func.call(this, a));
  10203. };
  10204. }
  10205. while (ordinalizeTokens.length) {
  10206. i = ordinalizeTokens.pop();
  10207. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i]);
  10208. }
  10209. while (paddedTokens.length) {
  10210. i = paddedTokens.pop();
  10211. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  10212. }
  10213. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  10214. /************************************
  10215. Constructors
  10216. ************************************/
  10217. function Language() {
  10218. }
  10219. // Moment prototype object
  10220. function Moment(config) {
  10221. extend(this, config);
  10222. }
  10223. // Duration Constructor
  10224. function Duration(duration) {
  10225. var data = this._data = {},
  10226. years = duration.years || duration.year || duration.y || 0,
  10227. months = duration.months || duration.month || duration.M || 0,
  10228. weeks = duration.weeks || duration.week || duration.w || 0,
  10229. days = duration.days || duration.day || duration.d || 0,
  10230. hours = duration.hours || duration.hour || duration.h || 0,
  10231. minutes = duration.minutes || duration.minute || duration.m || 0,
  10232. seconds = duration.seconds || duration.second || duration.s || 0,
  10233. milliseconds = duration.milliseconds || duration.millisecond || duration.ms || 0;
  10234. // representation for dateAddRemove
  10235. this._milliseconds = milliseconds +
  10236. seconds * 1e3 + // 1000
  10237. minutes * 6e4 + // 1000 * 60
  10238. hours * 36e5; // 1000 * 60 * 60
  10239. // Because of dateAddRemove treats 24 hours as different from a
  10240. // day when working around DST, we need to store them separately
  10241. this._days = days +
  10242. weeks * 7;
  10243. // It is impossible translate months into days without knowing
  10244. // which months you are are talking about, so we have to store
  10245. // it separately.
  10246. this._months = months +
  10247. years * 12;
  10248. // The following code bubbles up values, see the tests for
  10249. // examples of what that means.
  10250. data.milliseconds = milliseconds % 1000;
  10251. seconds += absRound(milliseconds / 1000);
  10252. data.seconds = seconds % 60;
  10253. minutes += absRound(seconds / 60);
  10254. data.minutes = minutes % 60;
  10255. hours += absRound(minutes / 60);
  10256. data.hours = hours % 24;
  10257. days += absRound(hours / 24);
  10258. days += weeks * 7;
  10259. data.days = days % 30;
  10260. months += absRound(days / 30);
  10261. data.months = months % 12;
  10262. years += absRound(months / 12);
  10263. data.years = years;
  10264. }
  10265. /************************************
  10266. Helpers
  10267. ************************************/
  10268. function extend(a, b) {
  10269. for (var i in b) {
  10270. if (b.hasOwnProperty(i)) {
  10271. a[i] = b[i];
  10272. }
  10273. }
  10274. return a;
  10275. }
  10276. function absRound(number) {
  10277. if (number < 0) {
  10278. return Math.ceil(number);
  10279. } else {
  10280. return Math.floor(number);
  10281. }
  10282. }
  10283. // left zero fill a number
  10284. // see http://jsperf.com/left-zero-filling for performance comparison
  10285. function leftZeroFill(number, targetLength) {
  10286. var output = number + '';
  10287. while (output.length < targetLength) {
  10288. output = '0' + output;
  10289. }
  10290. return output;
  10291. }
  10292. // helper function for _.addTime and _.subtractTime
  10293. function addOrSubtractDurationFromMoment(mom, duration, isAdding) {
  10294. var ms = duration._milliseconds,
  10295. d = duration._days,
  10296. M = duration._months,
  10297. currentDate;
  10298. if (ms) {
  10299. mom._d.setTime(+mom + ms * isAdding);
  10300. }
  10301. if (d) {
  10302. mom.date(mom.date() + d * isAdding);
  10303. }
  10304. if (M) {
  10305. currentDate = mom.date();
  10306. mom.date(1)
  10307. .month(mom.month() + M * isAdding)
  10308. .date(Math.min(currentDate, mom.daysInMonth()));
  10309. }
  10310. }
  10311. // check if is an array
  10312. function isArray(input) {
  10313. return Object.prototype.toString.call(input) === '[object Array]';
  10314. }
  10315. // compare two arrays, return the number of differences
  10316. function compareArrays(array1, array2) {
  10317. var len = Math.min(array1.length, array2.length),
  10318. lengthDiff = Math.abs(array1.length - array2.length),
  10319. diffs = 0,
  10320. i;
  10321. for (i = 0; i < len; i++) {
  10322. if (~~array1[i] !== ~~array2[i]) {
  10323. diffs++;
  10324. }
  10325. }
  10326. return diffs + lengthDiff;
  10327. }
  10328. /************************************
  10329. Languages
  10330. ************************************/
  10331. Language.prototype = {
  10332. set : function (config) {
  10333. var prop, i;
  10334. for (i in config) {
  10335. prop = config[i];
  10336. if (typeof prop === 'function') {
  10337. this[i] = prop;
  10338. } else {
  10339. this['_' + i] = prop;
  10340. }
  10341. }
  10342. },
  10343. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  10344. months : function (m) {
  10345. return this._months[m.month()];
  10346. },
  10347. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  10348. monthsShort : function (m) {
  10349. return this._monthsShort[m.month()];
  10350. },
  10351. monthsParse : function (monthName) {
  10352. var i, mom, regex, output;
  10353. if (!this._monthsParse) {
  10354. this._monthsParse = [];
  10355. }
  10356. for (i = 0; i < 12; i++) {
  10357. // make the regex if we don't have it already
  10358. if (!this._monthsParse[i]) {
  10359. mom = moment([2000, i]);
  10360. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  10361. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  10362. }
  10363. // test the regex
  10364. if (this._monthsParse[i].test(monthName)) {
  10365. return i;
  10366. }
  10367. }
  10368. },
  10369. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  10370. weekdays : function (m) {
  10371. return this._weekdays[m.day()];
  10372. },
  10373. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  10374. weekdaysShort : function (m) {
  10375. return this._weekdaysShort[m.day()];
  10376. },
  10377. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  10378. weekdaysMin : function (m) {
  10379. return this._weekdaysMin[m.day()];
  10380. },
  10381. _longDateFormat : {
  10382. LT : "h:mm A",
  10383. L : "MM/DD/YYYY",
  10384. LL : "MMMM D YYYY",
  10385. LLL : "MMMM D YYYY LT",
  10386. LLLL : "dddd, MMMM D YYYY LT"
  10387. },
  10388. longDateFormat : function (key) {
  10389. var output = this._longDateFormat[key];
  10390. if (!output && this._longDateFormat[key.toUpperCase()]) {
  10391. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  10392. return val.slice(1);
  10393. });
  10394. this._longDateFormat[key] = output;
  10395. }
  10396. return output;
  10397. },
  10398. meridiem : function (hours, minutes, isLower) {
  10399. if (hours > 11) {
  10400. return isLower ? 'pm' : 'PM';
  10401. } else {
  10402. return isLower ? 'am' : 'AM';
  10403. }
  10404. },
  10405. _calendar : {
  10406. sameDay : '[Today at] LT',
  10407. nextDay : '[Tomorrow at] LT',
  10408. nextWeek : 'dddd [at] LT',
  10409. lastDay : '[Yesterday at] LT',
  10410. lastWeek : '[last] dddd [at] LT',
  10411. sameElse : 'L'
  10412. },
  10413. calendar : function (key, mom) {
  10414. var output = this._calendar[key];
  10415. return typeof output === 'function' ? output.apply(mom) : output;
  10416. },
  10417. _relativeTime : {
  10418. future : "in %s",
  10419. past : "%s ago",
  10420. s : "a few seconds",
  10421. m : "a minute",
  10422. mm : "%d minutes",
  10423. h : "an hour",
  10424. hh : "%d hours",
  10425. d : "a day",
  10426. dd : "%d days",
  10427. M : "a month",
  10428. MM : "%d months",
  10429. y : "a year",
  10430. yy : "%d years"
  10431. },
  10432. relativeTime : function (number, withoutSuffix, string, isFuture) {
  10433. var output = this._relativeTime[string];
  10434. return (typeof output === 'function') ?
  10435. output(number, withoutSuffix, string, isFuture) :
  10436. output.replace(/%d/i, number);
  10437. },
  10438. pastFuture : function (diff, output) {
  10439. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  10440. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  10441. },
  10442. ordinal : function (number) {
  10443. return this._ordinal.replace("%d", number);
  10444. },
  10445. _ordinal : "%d",
  10446. preparse : function (string) {
  10447. return string;
  10448. },
  10449. postformat : function (string) {
  10450. return string;
  10451. },
  10452. week : function (mom) {
  10453. return weekOfYear(mom, this._week.dow, this._week.doy);
  10454. },
  10455. _week : {
  10456. dow : 0, // Sunday is the first day of the week.
  10457. doy : 6 // The week that contains Jan 1st is the first week of the year.
  10458. }
  10459. };
  10460. // Loads a language definition into the `languages` cache. The function
  10461. // takes a key and optionally values. If not in the browser and no values
  10462. // are provided, it will load the language file module. As a convenience,
  10463. // this function also returns the language values.
  10464. function loadLang(key, values) {
  10465. values.abbr = key;
  10466. if (!languages[key]) {
  10467. languages[key] = new Language();
  10468. }
  10469. languages[key].set(values);
  10470. return languages[key];
  10471. }
  10472. // Determines which language definition to use and returns it.
  10473. //
  10474. // With no parameters, it will return the global language. If you
  10475. // pass in a language key, such as 'en', it will return the
  10476. // definition for 'en', so long as 'en' has already been loaded using
  10477. // moment.lang.
  10478. function getLangDefinition(key) {
  10479. if (!key) {
  10480. return moment.fn._lang;
  10481. }
  10482. if (!languages[key] && hasModule) {
  10483. require('./lang/' + key);
  10484. }
  10485. return languages[key];
  10486. }
  10487. /************************************
  10488. Formatting
  10489. ************************************/
  10490. function removeFormattingTokens(input) {
  10491. if (input.match(/\[.*\]/)) {
  10492. return input.replace(/^\[|\]$/g, "");
  10493. }
  10494. return input.replace(/\\/g, "");
  10495. }
  10496. function makeFormatFunction(format) {
  10497. var array = format.match(formattingTokens), i, length;
  10498. for (i = 0, length = array.length; i < length; i++) {
  10499. if (formatTokenFunctions[array[i]]) {
  10500. array[i] = formatTokenFunctions[array[i]];
  10501. } else {
  10502. array[i] = removeFormattingTokens(array[i]);
  10503. }
  10504. }
  10505. return function (mom) {
  10506. var output = "";
  10507. for (i = 0; i < length; i++) {
  10508. output += typeof array[i].call === 'function' ? array[i].call(mom, format) : array[i];
  10509. }
  10510. return output;
  10511. };
  10512. }
  10513. // format date using native date object
  10514. function formatMoment(m, format) {
  10515. var i = 5;
  10516. function replaceLongDateFormatTokens(input) {
  10517. return m.lang().longDateFormat(input) || input;
  10518. }
  10519. while (i-- && localFormattingTokens.test(format)) {
  10520. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  10521. }
  10522. if (!formatFunctions[format]) {
  10523. formatFunctions[format] = makeFormatFunction(format);
  10524. }
  10525. return formatFunctions[format](m);
  10526. }
  10527. /************************************
  10528. Parsing
  10529. ************************************/
  10530. // get the regex to find the next token
  10531. function getParseRegexForToken(token) {
  10532. switch (token) {
  10533. case 'DDDD':
  10534. return parseTokenThreeDigits;
  10535. case 'YYYY':
  10536. return parseTokenFourDigits;
  10537. case 'YYYYY':
  10538. return parseTokenSixDigits;
  10539. case 'S':
  10540. case 'SS':
  10541. case 'SSS':
  10542. case 'DDD':
  10543. return parseTokenOneToThreeDigits;
  10544. case 'MMM':
  10545. case 'MMMM':
  10546. case 'dd':
  10547. case 'ddd':
  10548. case 'dddd':
  10549. case 'a':
  10550. case 'A':
  10551. return parseTokenWord;
  10552. case 'X':
  10553. return parseTokenTimestampMs;
  10554. case 'Z':
  10555. case 'ZZ':
  10556. return parseTokenTimezone;
  10557. case 'T':
  10558. return parseTokenT;
  10559. case 'MM':
  10560. case 'DD':
  10561. case 'YY':
  10562. case 'HH':
  10563. case 'hh':
  10564. case 'mm':
  10565. case 'ss':
  10566. case 'M':
  10567. case 'D':
  10568. case 'd':
  10569. case 'H':
  10570. case 'h':
  10571. case 'm':
  10572. case 's':
  10573. return parseTokenOneOrTwoDigits;
  10574. default :
  10575. return new RegExp(token.replace('\\', ''));
  10576. }
  10577. }
  10578. // function to convert string input to date
  10579. function addTimeToArrayFromToken(token, input, config) {
  10580. var a, b,
  10581. datePartArray = config._a;
  10582. switch (token) {
  10583. // MONTH
  10584. case 'M' : // fall through to MM
  10585. case 'MM' :
  10586. datePartArray[1] = (input == null) ? 0 : ~~input - 1;
  10587. break;
  10588. case 'MMM' : // fall through to MMMM
  10589. case 'MMMM' :
  10590. a = getLangDefinition(config._l).monthsParse(input);
  10591. // if we didn't find a month name, mark the date as invalid.
  10592. if (a != null) {
  10593. datePartArray[1] = a;
  10594. } else {
  10595. config._isValid = false;
  10596. }
  10597. break;
  10598. // DAY OF MONTH
  10599. case 'D' : // fall through to DDDD
  10600. case 'DD' : // fall through to DDDD
  10601. case 'DDD' : // fall through to DDDD
  10602. case 'DDDD' :
  10603. if (input != null) {
  10604. datePartArray[2] = ~~input;
  10605. }
  10606. break;
  10607. // YEAR
  10608. case 'YY' :
  10609. datePartArray[0] = ~~input + (~~input > 68 ? 1900 : 2000);
  10610. break;
  10611. case 'YYYY' :
  10612. case 'YYYYY' :
  10613. datePartArray[0] = ~~input;
  10614. break;
  10615. // AM / PM
  10616. case 'a' : // fall through to A
  10617. case 'A' :
  10618. config._isPm = ((input + '').toLowerCase() === 'pm');
  10619. break;
  10620. // 24 HOUR
  10621. case 'H' : // fall through to hh
  10622. case 'HH' : // fall through to hh
  10623. case 'h' : // fall through to hh
  10624. case 'hh' :
  10625. datePartArray[3] = ~~input;
  10626. break;
  10627. // MINUTE
  10628. case 'm' : // fall through to mm
  10629. case 'mm' :
  10630. datePartArray[4] = ~~input;
  10631. break;
  10632. // SECOND
  10633. case 's' : // fall through to ss
  10634. case 'ss' :
  10635. datePartArray[5] = ~~input;
  10636. break;
  10637. // MILLISECOND
  10638. case 'S' :
  10639. case 'SS' :
  10640. case 'SSS' :
  10641. datePartArray[6] = ~~ (('0.' + input) * 1000);
  10642. break;
  10643. // UNIX TIMESTAMP WITH MS
  10644. case 'X':
  10645. config._d = new Date(parseFloat(input) * 1000);
  10646. break;
  10647. // TIMEZONE
  10648. case 'Z' : // fall through to ZZ
  10649. case 'ZZ' :
  10650. config._useUTC = true;
  10651. a = (input + '').match(parseTimezoneChunker);
  10652. if (a && a[1]) {
  10653. config._tzh = ~~a[1];
  10654. }
  10655. if (a && a[2]) {
  10656. config._tzm = ~~a[2];
  10657. }
  10658. // reverse offsets
  10659. if (a && a[0] === '+') {
  10660. config._tzh = -config._tzh;
  10661. config._tzm = -config._tzm;
  10662. }
  10663. break;
  10664. }
  10665. // if the input is null, the date is not valid
  10666. if (input == null) {
  10667. config._isValid = false;
  10668. }
  10669. }
  10670. // convert an array to a date.
  10671. // the array should mirror the parameters below
  10672. // note: all values past the year are optional and will default to the lowest possible value.
  10673. // [year, month, day , hour, minute, second, millisecond]
  10674. function dateFromArray(config) {
  10675. var i, date, input = [];
  10676. if (config._d) {
  10677. return;
  10678. }
  10679. for (i = 0; i < 7; i++) {
  10680. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  10681. }
  10682. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  10683. input[3] += config._tzh || 0;
  10684. input[4] += config._tzm || 0;
  10685. date = new Date(0);
  10686. if (config._useUTC) {
  10687. date.setUTCFullYear(input[0], input[1], input[2]);
  10688. date.setUTCHours(input[3], input[4], input[5], input[6]);
  10689. } else {
  10690. date.setFullYear(input[0], input[1], input[2]);
  10691. date.setHours(input[3], input[4], input[5], input[6]);
  10692. }
  10693. config._d = date;
  10694. }
  10695. // date from string and format string
  10696. function makeDateFromStringAndFormat(config) {
  10697. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  10698. var tokens = config._f.match(formattingTokens),
  10699. string = config._i,
  10700. i, parsedInput;
  10701. config._a = [];
  10702. for (i = 0; i < tokens.length; i++) {
  10703. parsedInput = (getParseRegexForToken(tokens[i]).exec(string) || [])[0];
  10704. if (parsedInput) {
  10705. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  10706. }
  10707. // don't parse if its not a known token
  10708. if (formatTokenFunctions[tokens[i]]) {
  10709. addTimeToArrayFromToken(tokens[i], parsedInput, config);
  10710. }
  10711. }
  10712. // handle am pm
  10713. if (config._isPm && config._a[3] < 12) {
  10714. config._a[3] += 12;
  10715. }
  10716. // if is 12 am, change hours to 0
  10717. if (config._isPm === false && config._a[3] === 12) {
  10718. config._a[3] = 0;
  10719. }
  10720. // return
  10721. dateFromArray(config);
  10722. }
  10723. // date from string and array of format strings
  10724. function makeDateFromStringAndArray(config) {
  10725. var tempConfig,
  10726. tempMoment,
  10727. bestMoment,
  10728. scoreToBeat = 99,
  10729. i,
  10730. currentDate,
  10731. currentScore;
  10732. while (config._f.length) {
  10733. tempConfig = extend({}, config);
  10734. tempConfig._f = config._f.pop();
  10735. makeDateFromStringAndFormat(tempConfig);
  10736. tempMoment = new Moment(tempConfig);
  10737. if (tempMoment.isValid()) {
  10738. bestMoment = tempMoment;
  10739. break;
  10740. }
  10741. currentScore = compareArrays(tempConfig._a, tempMoment.toArray());
  10742. if (currentScore < scoreToBeat) {
  10743. scoreToBeat = currentScore;
  10744. bestMoment = tempMoment;
  10745. }
  10746. }
  10747. extend(config, bestMoment);
  10748. }
  10749. // date from iso format
  10750. function makeDateFromString(config) {
  10751. var i,
  10752. string = config._i;
  10753. if (isoRegex.exec(string)) {
  10754. config._f = 'YYYY-MM-DDT';
  10755. for (i = 0; i < 4; i++) {
  10756. if (isoTimes[i][1].exec(string)) {
  10757. config._f += isoTimes[i][0];
  10758. break;
  10759. }
  10760. }
  10761. if (parseTokenTimezone.exec(string)) {
  10762. config._f += " Z";
  10763. }
  10764. makeDateFromStringAndFormat(config);
  10765. } else {
  10766. config._d = new Date(string);
  10767. }
  10768. }
  10769. function makeDateFromInput(config) {
  10770. var input = config._i,
  10771. matched = aspNetJsonRegex.exec(input);
  10772. if (input === undefined) {
  10773. config._d = new Date();
  10774. } else if (matched) {
  10775. config._d = new Date(+matched[1]);
  10776. } else if (typeof input === 'string') {
  10777. makeDateFromString(config);
  10778. } else if (isArray(input)) {
  10779. config._a = input.slice(0);
  10780. dateFromArray(config);
  10781. } else {
  10782. config._d = input instanceof Date ? new Date(+input) : new Date(input);
  10783. }
  10784. }
  10785. /************************************
  10786. Relative Time
  10787. ************************************/
  10788. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  10789. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  10790. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  10791. }
  10792. function relativeTime(milliseconds, withoutSuffix, lang) {
  10793. var seconds = round(Math.abs(milliseconds) / 1000),
  10794. minutes = round(seconds / 60),
  10795. hours = round(minutes / 60),
  10796. days = round(hours / 24),
  10797. years = round(days / 365),
  10798. args = seconds < 45 && ['s', seconds] ||
  10799. minutes === 1 && ['m'] ||
  10800. minutes < 45 && ['mm', minutes] ||
  10801. hours === 1 && ['h'] ||
  10802. hours < 22 && ['hh', hours] ||
  10803. days === 1 && ['d'] ||
  10804. days <= 25 && ['dd', days] ||
  10805. days <= 45 && ['M'] ||
  10806. days < 345 && ['MM', round(days / 30)] ||
  10807. years === 1 && ['y'] || ['yy', years];
  10808. args[2] = withoutSuffix;
  10809. args[3] = milliseconds > 0;
  10810. args[4] = lang;
  10811. return substituteTimeAgo.apply({}, args);
  10812. }
  10813. /************************************
  10814. Week of Year
  10815. ************************************/
  10816. // firstDayOfWeek 0 = sun, 6 = sat
  10817. // the day of the week that starts the week
  10818. // (usually sunday or monday)
  10819. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  10820. // the first week is the week that contains the first
  10821. // of this day of the week
  10822. // (eg. ISO weeks use thursday (4))
  10823. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  10824. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  10825. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day();
  10826. if (daysToDayOfWeek > end) {
  10827. daysToDayOfWeek -= 7;
  10828. }
  10829. if (daysToDayOfWeek < end - 7) {
  10830. daysToDayOfWeek += 7;
  10831. }
  10832. return Math.ceil(moment(mom).add('d', daysToDayOfWeek).dayOfYear() / 7);
  10833. }
  10834. /************************************
  10835. Top Level Functions
  10836. ************************************/
  10837. function makeMoment(config) {
  10838. var input = config._i,
  10839. format = config._f;
  10840. if (input === null || input === '') {
  10841. return null;
  10842. }
  10843. if (typeof input === 'string') {
  10844. config._i = input = getLangDefinition().preparse(input);
  10845. }
  10846. if (moment.isMoment(input)) {
  10847. config = extend({}, input);
  10848. config._d = new Date(+input._d);
  10849. } else if (format) {
  10850. if (isArray(format)) {
  10851. makeDateFromStringAndArray(config);
  10852. } else {
  10853. makeDateFromStringAndFormat(config);
  10854. }
  10855. } else {
  10856. makeDateFromInput(config);
  10857. }
  10858. return new Moment(config);
  10859. }
  10860. moment = function (input, format, lang) {
  10861. return makeMoment({
  10862. _i : input,
  10863. _f : format,
  10864. _l : lang,
  10865. _isUTC : false
  10866. });
  10867. };
  10868. // creating with utc
  10869. moment.utc = function (input, format, lang) {
  10870. return makeMoment({
  10871. _useUTC : true,
  10872. _isUTC : true,
  10873. _l : lang,
  10874. _i : input,
  10875. _f : format
  10876. });
  10877. };
  10878. // creating with unix timestamp (in seconds)
  10879. moment.unix = function (input) {
  10880. return moment(input * 1000);
  10881. };
  10882. // duration
  10883. moment.duration = function (input, key) {
  10884. var isDuration = moment.isDuration(input),
  10885. isNumber = (typeof input === 'number'),
  10886. duration = (isDuration ? input._data : (isNumber ? {} : input)),
  10887. ret;
  10888. if (isNumber) {
  10889. if (key) {
  10890. duration[key] = input;
  10891. } else {
  10892. duration.milliseconds = input;
  10893. }
  10894. }
  10895. ret = new Duration(duration);
  10896. if (isDuration && input.hasOwnProperty('_lang')) {
  10897. ret._lang = input._lang;
  10898. }
  10899. return ret;
  10900. };
  10901. // version number
  10902. moment.version = VERSION;
  10903. // default format
  10904. moment.defaultFormat = isoFormat;
  10905. // This function will load languages and then set the global language. If
  10906. // no arguments are passed in, it will simply return the current global
  10907. // language key.
  10908. moment.lang = function (key, values) {
  10909. var i;
  10910. if (!key) {
  10911. return moment.fn._lang._abbr;
  10912. }
  10913. if (values) {
  10914. loadLang(key, values);
  10915. } else if (!languages[key]) {
  10916. getLangDefinition(key);
  10917. }
  10918. moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  10919. };
  10920. // returns language data
  10921. moment.langData = function (key) {
  10922. if (key && key._lang && key._lang._abbr) {
  10923. key = key._lang._abbr;
  10924. }
  10925. return getLangDefinition(key);
  10926. };
  10927. // compare moment object
  10928. moment.isMoment = function (obj) {
  10929. return obj instanceof Moment;
  10930. };
  10931. // for typechecking Duration objects
  10932. moment.isDuration = function (obj) {
  10933. return obj instanceof Duration;
  10934. };
  10935. /************************************
  10936. Moment Prototype
  10937. ************************************/
  10938. moment.fn = Moment.prototype = {
  10939. clone : function () {
  10940. return moment(this);
  10941. },
  10942. valueOf : function () {
  10943. return +this._d;
  10944. },
  10945. unix : function () {
  10946. return Math.floor(+this._d / 1000);
  10947. },
  10948. toString : function () {
  10949. return this.format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  10950. },
  10951. toDate : function () {
  10952. return this._d;
  10953. },
  10954. toJSON : function () {
  10955. return moment.utc(this).format('YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  10956. },
  10957. toArray : function () {
  10958. var m = this;
  10959. return [
  10960. m.year(),
  10961. m.month(),
  10962. m.date(),
  10963. m.hours(),
  10964. m.minutes(),
  10965. m.seconds(),
  10966. m.milliseconds()
  10967. ];
  10968. },
  10969. isValid : function () {
  10970. if (this._isValid == null) {
  10971. if (this._a) {
  10972. this._isValid = !compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray());
  10973. } else {
  10974. this._isValid = !isNaN(this._d.getTime());
  10975. }
  10976. }
  10977. return !!this._isValid;
  10978. },
  10979. utc : function () {
  10980. this._isUTC = true;
  10981. return this;
  10982. },
  10983. local : function () {
  10984. this._isUTC = false;
  10985. return this;
  10986. },
  10987. format : function (inputString) {
  10988. var output = formatMoment(this, inputString || moment.defaultFormat);
  10989. return this.lang().postformat(output);
  10990. },
  10991. add : function (input, val) {
  10992. var dur;
  10993. // switch args to support add('s', 1) and add(1, 's')
  10994. if (typeof input === 'string') {
  10995. dur = moment.duration(+val, input);
  10996. } else {
  10997. dur = moment.duration(input, val);
  10998. }
  10999. addOrSubtractDurationFromMoment(this, dur, 1);
  11000. return this;
  11001. },
  11002. subtract : function (input, val) {
  11003. var dur;
  11004. // switch args to support subtract('s', 1) and subtract(1, 's')
  11005. if (typeof input === 'string') {
  11006. dur = moment.duration(+val, input);
  11007. } else {
  11008. dur = moment.duration(input, val);
  11009. }
  11010. addOrSubtractDurationFromMoment(this, dur, -1);
  11011. return this;
  11012. },
  11013. diff : function (input, units, asFloat) {
  11014. var that = this._isUTC ? moment(input).utc() : moment(input).local(),
  11015. zoneDiff = (this.zone() - that.zone()) * 6e4,
  11016. diff, output;
  11017. if (units) {
  11018. // standardize on singular form
  11019. units = units.replace(/s$/, '');
  11020. }
  11021. if (units === 'year' || units === 'month') {
  11022. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  11023. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  11024. output += ((this - moment(this).startOf('month')) - (that - moment(that).startOf('month'))) / diff;
  11025. if (units === 'year') {
  11026. output = output / 12;
  11027. }
  11028. } else {
  11029. diff = (this - that) - zoneDiff;
  11030. output = units === 'second' ? diff / 1e3 : // 1000
  11031. units === 'minute' ? diff / 6e4 : // 1000 * 60
  11032. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  11033. units === 'day' ? diff / 864e5 : // 1000 * 60 * 60 * 24
  11034. units === 'week' ? diff / 6048e5 : // 1000 * 60 * 60 * 24 * 7
  11035. diff;
  11036. }
  11037. return asFloat ? output : absRound(output);
  11038. },
  11039. from : function (time, withoutSuffix) {
  11040. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  11041. },
  11042. fromNow : function (withoutSuffix) {
  11043. return this.from(moment(), withoutSuffix);
  11044. },
  11045. calendar : function () {
  11046. var diff = this.diff(moment().startOf('day'), 'days', true),
  11047. format = diff < -6 ? 'sameElse' :
  11048. diff < -1 ? 'lastWeek' :
  11049. diff < 0 ? 'lastDay' :
  11050. diff < 1 ? 'sameDay' :
  11051. diff < 2 ? 'nextDay' :
  11052. diff < 7 ? 'nextWeek' : 'sameElse';
  11053. return this.format(this.lang().calendar(format, this));
  11054. },
  11055. isLeapYear : function () {
  11056. var year = this.year();
  11057. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  11058. },
  11059. isDST : function () {
  11060. return (this.zone() < moment([this.year()]).zone() ||
  11061. this.zone() < moment([this.year(), 5]).zone());
  11062. },
  11063. day : function (input) {
  11064. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  11065. return input == null ? day :
  11066. this.add({ d : input - day });
  11067. },
  11068. startOf: function (units) {
  11069. units = units.replace(/s$/, '');
  11070. // the following switch intentionally omits break keywords
  11071. // to utilize falling through the cases.
  11072. switch (units) {
  11073. case 'year':
  11074. this.month(0);
  11075. /* falls through */
  11076. case 'month':
  11077. this.date(1);
  11078. /* falls through */
  11079. case 'week':
  11080. case 'day':
  11081. this.hours(0);
  11082. /* falls through */
  11083. case 'hour':
  11084. this.minutes(0);
  11085. /* falls through */
  11086. case 'minute':
  11087. this.seconds(0);
  11088. /* falls through */
  11089. case 'second':
  11090. this.milliseconds(0);
  11091. /* falls through */
  11092. }
  11093. // weeks are a special case
  11094. if (units === 'week') {
  11095. this.day(0);
  11096. }
  11097. return this;
  11098. },
  11099. endOf: function (units) {
  11100. return this.startOf(units).add(units.replace(/s?$/, 's'), 1).subtract('ms', 1);
  11101. },
  11102. isAfter: function (input, units) {
  11103. units = typeof units !== 'undefined' ? units : 'millisecond';
  11104. return +this.clone().startOf(units) > +moment(input).startOf(units);
  11105. },
  11106. isBefore: function (input, units) {
  11107. units = typeof units !== 'undefined' ? units : 'millisecond';
  11108. return +this.clone().startOf(units) < +moment(input).startOf(units);
  11109. },
  11110. isSame: function (input, units) {
  11111. units = typeof units !== 'undefined' ? units : 'millisecond';
  11112. return +this.clone().startOf(units) === +moment(input).startOf(units);
  11113. },
  11114. zone : function () {
  11115. return this._isUTC ? 0 : this._d.getTimezoneOffset();
  11116. },
  11117. daysInMonth : function () {
  11118. return moment.utc([this.year(), this.month() + 1, 0]).date();
  11119. },
  11120. dayOfYear : function (input) {
  11121. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  11122. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  11123. },
  11124. isoWeek : function (input) {
  11125. var week = weekOfYear(this, 1, 4);
  11126. return input == null ? week : this.add("d", (input - week) * 7);
  11127. },
  11128. week : function (input) {
  11129. var week = this.lang().week(this);
  11130. return input == null ? week : this.add("d", (input - week) * 7);
  11131. },
  11132. // If passed a language key, it will set the language for this
  11133. // instance. Otherwise, it will return the language configuration
  11134. // variables for this instance.
  11135. lang : function (key) {
  11136. if (key === undefined) {
  11137. return this._lang;
  11138. } else {
  11139. this._lang = getLangDefinition(key);
  11140. return this;
  11141. }
  11142. }
  11143. };
  11144. // helper for adding shortcuts
  11145. function makeGetterAndSetter(name, key) {
  11146. moment.fn[name] = moment.fn[name + 's'] = function (input) {
  11147. var utc = this._isUTC ? 'UTC' : '';
  11148. if (input != null) {
  11149. this._d['set' + utc + key](input);
  11150. return this;
  11151. } else {
  11152. return this._d['get' + utc + key]();
  11153. }
  11154. };
  11155. }
  11156. // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds)
  11157. for (i = 0; i < proxyGettersAndSetters.length; i ++) {
  11158. makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]);
  11159. }
  11160. // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear')
  11161. makeGetterAndSetter('year', 'FullYear');
  11162. // add plural methods
  11163. moment.fn.days = moment.fn.day;
  11164. moment.fn.weeks = moment.fn.week;
  11165. moment.fn.isoWeeks = moment.fn.isoWeek;
  11166. /************************************
  11167. Duration Prototype
  11168. ************************************/
  11169. moment.duration.fn = Duration.prototype = {
  11170. weeks : function () {
  11171. return absRound(this.days() / 7);
  11172. },
  11173. valueOf : function () {
  11174. return this._milliseconds +
  11175. this._days * 864e5 +
  11176. this._months * 2592e6;
  11177. },
  11178. humanize : function (withSuffix) {
  11179. var difference = +this,
  11180. output = relativeTime(difference, !withSuffix, this.lang());
  11181. if (withSuffix) {
  11182. output = this.lang().pastFuture(difference, output);
  11183. }
  11184. return this.lang().postformat(output);
  11185. },
  11186. lang : moment.fn.lang
  11187. };
  11188. function makeDurationGetter(name) {
  11189. moment.duration.fn[name] = function () {
  11190. return this._data[name];
  11191. };
  11192. }
  11193. function makeDurationAsGetter(name, factor) {
  11194. moment.duration.fn['as' + name] = function () {
  11195. return +this / factor;
  11196. };
  11197. }
  11198. for (i in unitMillisecondFactors) {
  11199. if (unitMillisecondFactors.hasOwnProperty(i)) {
  11200. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  11201. makeDurationGetter(i.toLowerCase());
  11202. }
  11203. }
  11204. makeDurationAsGetter('Weeks', 6048e5);
  11205. /************************************
  11206. Default Lang
  11207. ************************************/
  11208. // Set default language, other languages will inherit from English.
  11209. moment.lang('en', {
  11210. ordinal : function (number) {
  11211. var b = number % 10,
  11212. output = (~~ (number % 100 / 10) === 1) ? 'th' :
  11213. (b === 1) ? 'st' :
  11214. (b === 2) ? 'nd' :
  11215. (b === 3) ? 'rd' : 'th';
  11216. return number + output;
  11217. }
  11218. });
  11219. /************************************
  11220. Exposing Moment
  11221. ************************************/
  11222. // CommonJS module is defined
  11223. if (hasModule) {
  11224. module.exports = moment;
  11225. }
  11226. /*global ender:false */
  11227. if (typeof ender === 'undefined') {
  11228. // here, `this` means `window` in the browser, or `global` on the server
  11229. // add `moment` as a global object via a string identifier,
  11230. // for Closure Compiler "advanced" mode
  11231. this['moment'] = moment;
  11232. }
  11233. /*global define:false */
  11234. if (typeof define === "function" && define.amd) {
  11235. define("moment", [], function () {
  11236. return moment;
  11237. });
  11238. }
  11239. }).call(this);
  11240. })()
  11241. },{}]},{},[1])(1)
  11242. });
  11243. ;