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.

12641 lines
379 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-10
  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. function DataSet (options) {
  1038. this.id = util.randomUUID();
  1039. this.options = options || {};
  1040. this.data = {}; // map with data indexed by id
  1041. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  1042. this.fieldTypes = {}; // field types by field name
  1043. if (this.options.fieldTypes) {
  1044. for (var field in this.options.fieldTypes) {
  1045. if (this.options.fieldTypes.hasOwnProperty(field)) {
  1046. var value = this.options.fieldTypes[field];
  1047. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1048. this.fieldTypes[field] = 'Date';
  1049. }
  1050. else {
  1051. this.fieldTypes[field] = value;
  1052. }
  1053. }
  1054. }
  1055. }
  1056. // event subscribers
  1057. this.subscribers = {};
  1058. this.internalIds = {}; // internally generated id's
  1059. }
  1060. /**
  1061. * Subscribe to an event, add an event listener
  1062. * @param {String} event Event name. Available events: 'put', 'update',
  1063. * 'remove'
  1064. * @param {function} callback Callback method. Called with three parameters:
  1065. * {String} event
  1066. * {Object | null} params
  1067. * {String} senderId
  1068. * @param {String} [id] Optional id for the sender, used to filter
  1069. * events triggered by the sender itself.
  1070. */
  1071. DataSet.prototype.subscribe = function (event, callback, id) {
  1072. var subscribers = this.subscribers[event];
  1073. if (!subscribers) {
  1074. subscribers = [];
  1075. this.subscribers[event] = subscribers;
  1076. }
  1077. subscribers.push({
  1078. id: id ? String(id) : null,
  1079. callback: callback
  1080. });
  1081. };
  1082. /**
  1083. * Unsubscribe from an event, remove an event listener
  1084. * @param {String} event
  1085. * @param {function} callback
  1086. */
  1087. DataSet.prototype.unsubscribe = function (event, callback) {
  1088. var subscribers = this.subscribers[event];
  1089. if (subscribers) {
  1090. this.subscribers[event] = subscribers.filter(function (listener) {
  1091. return (listener.callback != callback);
  1092. });
  1093. }
  1094. };
  1095. /**
  1096. * Trigger an event
  1097. * @param {String} event
  1098. * @param {Object | null} params
  1099. * @param {String} [senderId] Optional id of the sender.
  1100. * @private
  1101. */
  1102. DataSet.prototype._trigger = function (event, params, senderId) {
  1103. if (event == '*') {
  1104. throw new Error('Cannot trigger event *');
  1105. }
  1106. var subscribers = [];
  1107. if (event in this.subscribers) {
  1108. subscribers = subscribers.concat(this.subscribers[event]);
  1109. }
  1110. if ('*' in this.subscribers) {
  1111. subscribers = subscribers.concat(this.subscribers['*']);
  1112. }
  1113. for (var i = 0; i < subscribers.length; i++) {
  1114. var subscriber = subscribers[i];
  1115. if (subscriber.callback) {
  1116. subscriber.callback(event, params, senderId || null);
  1117. }
  1118. }
  1119. };
  1120. /**
  1121. * Add data.
  1122. * Adding an item will fail when there already is an item with the same id.
  1123. * @param {Object | Array | DataTable} data
  1124. * @param {String} [senderId] Optional sender id
  1125. */
  1126. DataSet.prototype.add = function (data, senderId) {
  1127. var addedItems = [],
  1128. id,
  1129. me = this;
  1130. if (data instanceof Array) {
  1131. // Array
  1132. for (var i = 0, len = data.length; i < len; i++) {
  1133. id = me._addItem(data[i]);
  1134. addedItems.push(id);
  1135. }
  1136. }
  1137. else if (util.isDataTable(data)) {
  1138. // Google DataTable
  1139. var columns = this._getColumnNames(data);
  1140. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1141. var item = {};
  1142. for (var col = 0, cols = columns.length; col < cols; col++) {
  1143. var field = columns[col];
  1144. item[field] = data.getValue(row, col);
  1145. }
  1146. id = me._addItem(item);
  1147. addedItems.push(id);
  1148. }
  1149. }
  1150. else if (data instanceof Object) {
  1151. // Single item
  1152. id = me._addItem(data);
  1153. addedItems.push(id);
  1154. }
  1155. else {
  1156. throw new Error('Unknown dataType');
  1157. }
  1158. if (addedItems.length) {
  1159. this._trigger('add', {items: addedItems}, senderId);
  1160. }
  1161. };
  1162. /**
  1163. * Update existing items. When an item does not exist, it will be created
  1164. * @param {Object | Array | DataTable} data
  1165. * @param {String} [senderId] Optional sender id
  1166. */
  1167. DataSet.prototype.update = function (data, senderId) {
  1168. var addedItems = [],
  1169. updatedItems = [],
  1170. me = this,
  1171. fieldId = me.fieldId;
  1172. var addOrUpdate = function (item) {
  1173. var id = item[fieldId];
  1174. if (me.data[id]) {
  1175. // update item
  1176. id = me._updateItem(item);
  1177. updatedItems.push(id);
  1178. }
  1179. else {
  1180. // add new item
  1181. id = me._addItem(item);
  1182. addedItems.push(id);
  1183. }
  1184. };
  1185. if (data instanceof Array) {
  1186. // Array
  1187. for (var i = 0, len = data.length; i < len; i++) {
  1188. addOrUpdate(data[i]);
  1189. }
  1190. }
  1191. else if (util.isDataTable(data)) {
  1192. // Google DataTable
  1193. var columns = this._getColumnNames(data);
  1194. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1195. var item = {};
  1196. for (var col = 0, cols = columns.length; col < cols; col++) {
  1197. var field = columns[col];
  1198. item[field] = data.getValue(row, col);
  1199. }
  1200. addOrUpdate(item);
  1201. }
  1202. }
  1203. else if (data instanceof Object) {
  1204. // Single item
  1205. addOrUpdate(data);
  1206. }
  1207. else {
  1208. throw new Error('Unknown dataType');
  1209. }
  1210. if (addedItems.length) {
  1211. this._trigger('add', {items: addedItems}, senderId);
  1212. }
  1213. if (updatedItems.length) {
  1214. this._trigger('update', {items: updatedItems}, senderId);
  1215. }
  1216. };
  1217. /**
  1218. * Get a data item or multiple items.
  1219. *
  1220. * Usage:
  1221. *
  1222. * get()
  1223. * get(options: Object)
  1224. * get(options: Object, data: Array | DataTable)
  1225. *
  1226. * get(id: Number | String)
  1227. * get(id: Number | String, options: Object)
  1228. * get(id: Number | String, options: Object, data: Array | DataTable)
  1229. *
  1230. * get(ids: Number[] | String[])
  1231. * get(ids: Number[] | String[], options: Object)
  1232. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1233. *
  1234. * Where:
  1235. *
  1236. * {Number | String} id The id of an item
  1237. * {Number[] | String{}} ids An array with ids of items
  1238. * {Object} options An Object with options. Available options:
  1239. * {String} [type] Type of data to be returned. Can
  1240. * be 'DataTable' or 'Array' (default)
  1241. * {Object.<String, String>} [fieldTypes]
  1242. * {String[]} [fields] field names to be returned
  1243. * {function} [filter] filter items
  1244. * {String | function} [order] Order the items by
  1245. * a field name or custom sort function.
  1246. * {Array | DataTable} [data] If provided, items will be appended to this
  1247. * array or table. Required in case of Google
  1248. * DataTable.
  1249. *
  1250. * @throws Error
  1251. */
  1252. DataSet.prototype.get = function (args) {
  1253. var me = this;
  1254. // parse the arguments
  1255. var id, ids, options, data;
  1256. var firstType = util.getType(arguments[0]);
  1257. if (firstType == 'String' || firstType == 'Number') {
  1258. // get(id [, options] [, data])
  1259. id = arguments[0];
  1260. options = arguments[1];
  1261. data = arguments[2];
  1262. }
  1263. else if (firstType == 'Array') {
  1264. // get(ids [, options] [, data])
  1265. ids = arguments[0];
  1266. options = arguments[1];
  1267. data = arguments[2];
  1268. }
  1269. else {
  1270. // get([, options] [, data])
  1271. options = arguments[0];
  1272. data = arguments[1];
  1273. }
  1274. // determine the return type
  1275. var type;
  1276. if (options && options.type) {
  1277. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  1278. if (data && (type != util.getType(data))) {
  1279. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1280. 'does not correspond with specified options.type (' + options.type + ')');
  1281. }
  1282. if (type == 'DataTable' && !util.isDataTable(data)) {
  1283. throw new Error('Parameter "data" must be a DataTable ' +
  1284. 'when options.type is "DataTable"');
  1285. }
  1286. }
  1287. else if (data) {
  1288. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1289. }
  1290. else {
  1291. type = 'Array';
  1292. }
  1293. // build options
  1294. var fieldTypes = options && options.fieldTypes || this.options.fieldTypes;
  1295. var filter = options && options.filter;
  1296. var items = [], item, itemId, i, len;
  1297. // cast items
  1298. if (id != undefined) {
  1299. // return a single item
  1300. item = me._getItem(id, fieldTypes);
  1301. if (filter && !filter(item)) {
  1302. item = null;
  1303. }
  1304. }
  1305. else if (ids != undefined) {
  1306. // return a subset of items
  1307. for (i = 0, len = ids.length; i < len; i++) {
  1308. item = me._getItem(ids[i], fieldTypes);
  1309. if (!filter || filter(item)) {
  1310. items.push(item);
  1311. }
  1312. }
  1313. }
  1314. else {
  1315. // return all items
  1316. for (itemId in this.data) {
  1317. if (this.data.hasOwnProperty(itemId)) {
  1318. item = me._getItem(itemId, fieldTypes);
  1319. if (!filter || filter(item)) {
  1320. items.push(item);
  1321. }
  1322. }
  1323. }
  1324. }
  1325. // order the results
  1326. if (options && options.order && id == undefined) {
  1327. this._sort(items, options.order);
  1328. }
  1329. // filter fields of the items
  1330. if (options && options.fields) {
  1331. var fields = options.fields;
  1332. if (id != undefined) {
  1333. item = this._filterFields(item, fields);
  1334. }
  1335. else {
  1336. for (i = 0, len = items.length; i < len; i++) {
  1337. items[i] = this._filterFields(items[i], fields);
  1338. }
  1339. }
  1340. }
  1341. // return the results
  1342. if (type == 'DataTable') {
  1343. var columns = this._getColumnNames(data);
  1344. if (id != undefined) {
  1345. // append a single item to the data table
  1346. me._appendRow(data, columns, item);
  1347. }
  1348. else {
  1349. // copy the items to the provided data table
  1350. for (i = 0, len = items.length; i < len; i++) {
  1351. me._appendRow(data, columns, items[i]);
  1352. }
  1353. }
  1354. return data;
  1355. }
  1356. else {
  1357. // return an array
  1358. if (id != undefined) {
  1359. // a single item
  1360. return item;
  1361. }
  1362. else {
  1363. // multiple items
  1364. if (data) {
  1365. // copy the items to the provided array
  1366. for (i = 0, len = items.length; i < len; i++) {
  1367. data.push(items[i]);
  1368. }
  1369. return data;
  1370. }
  1371. else {
  1372. // just return our array
  1373. return items;
  1374. }
  1375. }
  1376. }
  1377. };
  1378. /**
  1379. * Get ids of all items or from a filtered set of items.
  1380. * @param {Object} [options] An Object with options. Available options:
  1381. * {function} [filter] filter items
  1382. * {String | function} [order] Order the items by
  1383. * a field name or custom sort function.
  1384. * @return {Array} ids
  1385. */
  1386. DataSet.prototype.getIds = function (options) {
  1387. var data = this.data,
  1388. filter = options && options.filter,
  1389. order = options && options.order,
  1390. fieldTypes = options && options.fieldTypes || this.options.fieldTypes,
  1391. i,
  1392. len,
  1393. id,
  1394. item,
  1395. items,
  1396. ids = [];
  1397. if (filter) {
  1398. // get filtered items
  1399. if (order) {
  1400. // create ordered list
  1401. items = [];
  1402. for (id in data) {
  1403. if (data.hasOwnProperty(id)) {
  1404. item = this._getItem(id, fieldTypes);
  1405. if (filter(item)) {
  1406. items.push(item);
  1407. }
  1408. }
  1409. }
  1410. this._sort(items, order);
  1411. for (i = 0, len = items.length; i < len; i++) {
  1412. ids[i] = items[i][this.fieldId];
  1413. }
  1414. }
  1415. else {
  1416. // create unordered list
  1417. for (id in data) {
  1418. if (data.hasOwnProperty(id)) {
  1419. item = this._getItem(id, fieldTypes);
  1420. if (filter(item)) {
  1421. ids.push(item[this.fieldId]);
  1422. }
  1423. }
  1424. }
  1425. }
  1426. }
  1427. else {
  1428. // get all items
  1429. if (order) {
  1430. // create an ordered list
  1431. items = [];
  1432. for (id in data) {
  1433. if (data.hasOwnProperty(id)) {
  1434. items.push(data[id]);
  1435. }
  1436. }
  1437. this._sort(items, order);
  1438. for (i = 0, len = items.length; i < len; i++) {
  1439. ids[i] = items[i][this.fieldId];
  1440. }
  1441. }
  1442. else {
  1443. // create unordered list
  1444. for (id in data) {
  1445. if (data.hasOwnProperty(id)) {
  1446. item = data[id];
  1447. ids.push(item[this.fieldId]);
  1448. }
  1449. }
  1450. }
  1451. }
  1452. return ids;
  1453. };
  1454. /**
  1455. * Execute a callback function for every item in the dataset.
  1456. * The order of the items is not determined.
  1457. * @param {function} callback
  1458. * @param {Object} [options] Available options:
  1459. * {Object.<String, String>} [fieldTypes]
  1460. * {String[]} [fields] filter fields
  1461. * {function} [filter] filter items
  1462. * {String | function} [order] Order the items by
  1463. * a field name or custom sort function.
  1464. */
  1465. DataSet.prototype.forEach = function (callback, options) {
  1466. var filter = options && options.filter,
  1467. fieldTypes = options && options.fieldTypes || this.options.fieldTypes,
  1468. data = this.data,
  1469. item,
  1470. id;
  1471. if (options && options.order) {
  1472. // execute forEach on ordered list
  1473. var items = this.get(options);
  1474. for (var i = 0, len = items.length; i < len; i++) {
  1475. item = items[i];
  1476. id = item[this.fieldId];
  1477. callback(item, id);
  1478. }
  1479. }
  1480. else {
  1481. // unordered
  1482. for (id in data) {
  1483. if (data.hasOwnProperty(id)) {
  1484. item = this._getItem(id, fieldTypes);
  1485. if (!filter || filter(item)) {
  1486. callback(item, id);
  1487. }
  1488. }
  1489. }
  1490. }
  1491. };
  1492. /**
  1493. * Map every item in the dataset.
  1494. * @param {function} callback
  1495. * @param {Object} [options] Available options:
  1496. * {Object.<String, String>} [fieldTypes]
  1497. * {String[]} [fields] filter fields
  1498. * {function} [filter] filter items
  1499. * {String | function} [order] Order the items by
  1500. * a field name or custom sort function.
  1501. * @return {Object[]} mappedItems
  1502. */
  1503. DataSet.prototype.map = function (callback, options) {
  1504. var filter = options && options.filter,
  1505. fieldTypes = options && options.fieldTypes || this.options.fieldTypes,
  1506. mappedItems = [],
  1507. data = this.data,
  1508. item;
  1509. // cast and filter items
  1510. for (var id in data) {
  1511. if (data.hasOwnProperty(id)) {
  1512. item = this._getItem(id, fieldTypes);
  1513. if (!filter || filter(item)) {
  1514. mappedItems.push(callback(item, id));
  1515. }
  1516. }
  1517. }
  1518. // order items
  1519. if (options && options.order) {
  1520. this._sort(mappedItems, options.order);
  1521. }
  1522. return mappedItems;
  1523. };
  1524. /**
  1525. * Filter the fields of an item
  1526. * @param {Object} item
  1527. * @param {String[]} fields Field names
  1528. * @return {Object} filteredItem
  1529. * @private
  1530. */
  1531. DataSet.prototype._filterFields = function (item, fields) {
  1532. var filteredItem = {};
  1533. for (var field in item) {
  1534. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  1535. filteredItem[field] = item[field];
  1536. }
  1537. }
  1538. return filteredItem;
  1539. };
  1540. /**
  1541. * Sort the provided array with items
  1542. * @param {Object[]} items
  1543. * @param {String | function} order A field name or custom sort function.
  1544. * @private
  1545. */
  1546. DataSet.prototype._sort = function (items, order) {
  1547. if (util.isString(order)) {
  1548. // order by provided field name
  1549. var name = order; // field name
  1550. items.sort(function (a, b) {
  1551. var av = a[name];
  1552. var bv = b[name];
  1553. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  1554. });
  1555. }
  1556. else if (typeof order === 'function') {
  1557. // order by sort function
  1558. items.sort(order);
  1559. }
  1560. // TODO: extend order by an Object {field:String, direction:String}
  1561. // where direction can be 'asc' or 'desc'
  1562. else {
  1563. throw new TypeError('Order must be a function or a string');
  1564. }
  1565. };
  1566. /**
  1567. * Remove an object by pointer or by id
  1568. * @param {String | Number | Object | Array} id Object or id, or an array with
  1569. * objects or ids to be removed
  1570. * @param {String} [senderId] Optional sender id
  1571. */
  1572. DataSet.prototype.remove = function (id, senderId) {
  1573. var removedItems = [],
  1574. i, len;
  1575. if (util.isNumber(id) || util.isString(id)) {
  1576. delete this.data[id];
  1577. delete this.internalIds[id];
  1578. removedItems.push(id);
  1579. }
  1580. else if (id instanceof Array) {
  1581. for (i = 0, len = id.length; i < len; i++) {
  1582. this.remove(id[i]);
  1583. }
  1584. removedItems = items.concat(id);
  1585. }
  1586. else if (id instanceof Object) {
  1587. // search for the object
  1588. for (i in this.data) {
  1589. if (this.data.hasOwnProperty(i)) {
  1590. if (this.data[i] == id) {
  1591. delete this.data[i];
  1592. delete this.internalIds[i];
  1593. removedItems.push(i);
  1594. }
  1595. }
  1596. }
  1597. }
  1598. if (removedItems.length) {
  1599. this._trigger('remove', {items: removedItems}, senderId);
  1600. }
  1601. };
  1602. /**
  1603. * Clear the data
  1604. * @param {String} [senderId] Optional sender id
  1605. */
  1606. DataSet.prototype.clear = function (senderId) {
  1607. var ids = Object.keys(this.data);
  1608. this.data = {};
  1609. this.internalIds = {};
  1610. this._trigger('remove', {items: ids}, senderId);
  1611. };
  1612. /**
  1613. * Find the item with maximum value of a specified field
  1614. * @param {String} field
  1615. * @return {Object | null} item Item containing max value, or null if no items
  1616. */
  1617. DataSet.prototype.max = function (field) {
  1618. var data = this.data,
  1619. max = null,
  1620. maxField = null;
  1621. for (var id in data) {
  1622. if (data.hasOwnProperty(id)) {
  1623. var item = data[id];
  1624. var itemField = item[field];
  1625. if (itemField != null && (!max || itemField > maxField)) {
  1626. max = item;
  1627. maxField = itemField;
  1628. }
  1629. }
  1630. }
  1631. return max;
  1632. };
  1633. /**
  1634. * Find the item with minimum value of a specified field
  1635. * @param {String} field
  1636. * @return {Object | null} item Item containing max value, or null if no items
  1637. */
  1638. DataSet.prototype.min = function (field) {
  1639. var data = this.data,
  1640. min = null,
  1641. minField = null;
  1642. for (var id in data) {
  1643. if (data.hasOwnProperty(id)) {
  1644. var item = data[id];
  1645. var itemField = item[field];
  1646. if (itemField != null && (!min || itemField < minField)) {
  1647. min = item;
  1648. minField = itemField;
  1649. }
  1650. }
  1651. }
  1652. return min;
  1653. };
  1654. /**
  1655. * Find all distinct values of a specified field
  1656. * @param {String} field
  1657. * @return {Array} values Array containing all distinct values. If the data
  1658. * items do not contain the specified field, an array
  1659. * containing a single value undefined is returned.
  1660. * The returned array is unordered.
  1661. */
  1662. DataSet.prototype.distinct = function (field) {
  1663. var data = this.data,
  1664. values = [],
  1665. fieldType = this.options.fieldTypes[field],
  1666. count = 0;
  1667. for (var prop in data) {
  1668. if (data.hasOwnProperty(prop)) {
  1669. var item = data[prop];
  1670. var value = util.cast(item[field], fieldType);
  1671. var exists = false;
  1672. for (var i = 0; i < count; i++) {
  1673. if (values[i] == value) {
  1674. exists = true;
  1675. break;
  1676. }
  1677. }
  1678. if (!exists) {
  1679. values[count] = value;
  1680. count++;
  1681. }
  1682. }
  1683. }
  1684. return values;
  1685. };
  1686. /**
  1687. * Add a single item. Will fail when an item with the same id already exists.
  1688. * @param {Object} item
  1689. * @return {String} id
  1690. * @private
  1691. */
  1692. DataSet.prototype._addItem = function (item) {
  1693. var id = item[this.fieldId];
  1694. if (id != undefined) {
  1695. // check whether this id is already taken
  1696. if (this.data[id]) {
  1697. // item already exists
  1698. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  1699. }
  1700. }
  1701. else {
  1702. // generate an id
  1703. id = util.randomUUID();
  1704. item[this.fieldId] = id;
  1705. this.internalIds[id] = item;
  1706. }
  1707. var d = {};
  1708. for (var field in item) {
  1709. if (item.hasOwnProperty(field)) {
  1710. var type = this.fieldTypes[field]; // type may be undefined
  1711. d[field] = util.cast(item[field], type);
  1712. }
  1713. }
  1714. this.data[id] = d;
  1715. return id;
  1716. };
  1717. /**
  1718. * Get an item. Fields can be casted to a specific type
  1719. * @param {String} id
  1720. * @param {Object.<String, String>} [fieldTypes] Cast field types
  1721. * @return {Object | null} item
  1722. * @private
  1723. */
  1724. DataSet.prototype._getItem = function (id, fieldTypes) {
  1725. var field, value;
  1726. // get the item from the dataset
  1727. var raw = this.data[id];
  1728. if (!raw) {
  1729. return null;
  1730. }
  1731. // cast the items field types
  1732. var casted = {},
  1733. fieldId = this.fieldId,
  1734. internalIds = this.internalIds;
  1735. if (fieldTypes) {
  1736. for (field in raw) {
  1737. if (raw.hasOwnProperty(field)) {
  1738. value = raw[field];
  1739. // output all fields, except internal ids
  1740. if ((field != fieldId) || !(value in internalIds)) {
  1741. casted[field] = util.cast(value, fieldTypes[field]);
  1742. }
  1743. }
  1744. }
  1745. }
  1746. else {
  1747. // no field types specified, no casting needed
  1748. for (field in raw) {
  1749. if (raw.hasOwnProperty(field)) {
  1750. value = raw[field];
  1751. // output all fields, except internal ids
  1752. if ((field != fieldId) || !(value in internalIds)) {
  1753. casted[field] = value;
  1754. }
  1755. }
  1756. }
  1757. }
  1758. return casted;
  1759. };
  1760. /**
  1761. * Update a single item: merge with existing item.
  1762. * Will fail when the item has no id, or when there does not exist an item
  1763. * with the same id.
  1764. * @param {Object} item
  1765. * @return {String} id
  1766. * @private
  1767. */
  1768. DataSet.prototype._updateItem = function (item) {
  1769. var id = item[this.fieldId];
  1770. if (id == undefined) {
  1771. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  1772. }
  1773. var d = this.data[id];
  1774. if (!d) {
  1775. // item doesn't exist
  1776. throw new Error('Cannot update item: no item with id ' + id + ' found');
  1777. }
  1778. // merge with current item
  1779. for (var field in item) {
  1780. if (item.hasOwnProperty(field)) {
  1781. var type = this.fieldTypes[field]; // type may be undefined
  1782. d[field] = util.cast(item[field], type);
  1783. }
  1784. }
  1785. return id;
  1786. };
  1787. /**
  1788. * Get an array with the column names of a Google DataTable
  1789. * @param {DataTable} dataTable
  1790. * @return {String[]} columnNames
  1791. * @private
  1792. */
  1793. DataSet.prototype._getColumnNames = function (dataTable) {
  1794. var columns = [];
  1795. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  1796. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  1797. }
  1798. return columns;
  1799. };
  1800. /**
  1801. * Append an item as a row to the dataTable
  1802. * @param dataTable
  1803. * @param columns
  1804. * @param item
  1805. * @private
  1806. */
  1807. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  1808. var row = dataTable.addRow();
  1809. for (var col = 0, cols = columns.length; col < cols; col++) {
  1810. var field = columns[col];
  1811. dataTable.setValue(row, col, item[field]);
  1812. }
  1813. };
  1814. /**
  1815. * DataView
  1816. *
  1817. * a dataview offers a filtered view on a dataset or an other dataview.
  1818. *
  1819. * @param {DataSet | DataView} data
  1820. * @param {Object} [options] Available options: see method get
  1821. *
  1822. * @constructor DataView
  1823. */
  1824. function DataView (data, options) {
  1825. this.id = util.randomUUID();
  1826. this.data = null;
  1827. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  1828. this.options = options || {};
  1829. this.fieldId = 'id'; // name of the field containing id
  1830. this.subscribers = {}; // event subscribers
  1831. var me = this;
  1832. this.listener = function () {
  1833. me._onEvent.apply(me, arguments);
  1834. };
  1835. this.setData(data);
  1836. }
  1837. /**
  1838. * Set a data source for the view
  1839. * @param {DataSet | DataView} data
  1840. */
  1841. DataView.prototype.setData = function (data) {
  1842. var ids, dataItems, i, len;
  1843. if (this.data) {
  1844. // unsubscribe from current dataset
  1845. if (this.data.unsubscribe) {
  1846. this.data.unsubscribe('*', this.listener);
  1847. }
  1848. // trigger a remove of all items in memory
  1849. ids = [];
  1850. for (var id in this.ids) {
  1851. if (this.ids.hasOwnProperty(id)) {
  1852. ids.push(id);
  1853. }
  1854. }
  1855. this.ids = {};
  1856. this._trigger('remove', {items: ids});
  1857. }
  1858. this.data = data;
  1859. if (this.data) {
  1860. // update fieldId
  1861. this.fieldId = this.options.fieldId ||
  1862. (this.data && this.data.options && this.data.options.fieldId) ||
  1863. 'id';
  1864. // trigger an add of all added items
  1865. ids = this.data.getIds({filter: this.options && this.options.filter});
  1866. for (i = 0, len = ids.length; i < len; i++) {
  1867. id = ids[i];
  1868. this.ids[id] = true;
  1869. }
  1870. this._trigger('add', {items: ids});
  1871. // subscribe to new dataset
  1872. if (this.data.subscribe) {
  1873. this.data.subscribe('*', this.listener);
  1874. }
  1875. }
  1876. };
  1877. /**
  1878. * Get data from the data view
  1879. *
  1880. * Usage:
  1881. *
  1882. * get()
  1883. * get(options: Object)
  1884. * get(options: Object, data: Array | DataTable)
  1885. *
  1886. * get(id: Number)
  1887. * get(id: Number, options: Object)
  1888. * get(id: Number, options: Object, data: Array | DataTable)
  1889. *
  1890. * get(ids: Number[])
  1891. * get(ids: Number[], options: Object)
  1892. * get(ids: Number[], options: Object, data: Array | DataTable)
  1893. *
  1894. * Where:
  1895. *
  1896. * {Number | String} id The id of an item
  1897. * {Number[] | String{}} ids An array with ids of items
  1898. * {Object} options An Object with options. Available options:
  1899. * {String} [type] Type of data to be returned. Can
  1900. * be 'DataTable' or 'Array' (default)
  1901. * {Object.<String, String>} [fieldTypes]
  1902. * {String[]} [fields] field names to be returned
  1903. * {function} [filter] filter items
  1904. * {String | function} [order] Order the items by
  1905. * a field name or custom sort function.
  1906. * {Array | DataTable} [data] If provided, items will be appended to this
  1907. * array or table. Required in case of Google
  1908. * DataTable.
  1909. * @param args
  1910. */
  1911. DataView.prototype.get = function (args) {
  1912. var me = this;
  1913. // parse the arguments
  1914. var ids, options, data;
  1915. var firstType = util.getType(arguments[0]);
  1916. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  1917. // get(id(s) [, options] [, data])
  1918. ids = arguments[0]; // can be a single id or an array with ids
  1919. options = arguments[1];
  1920. data = arguments[2];
  1921. }
  1922. else {
  1923. // get([, options] [, data])
  1924. options = arguments[0];
  1925. data = arguments[1];
  1926. }
  1927. // extend the options with the default options and provided options
  1928. var viewOptions = util.extend({}, this.options, options);
  1929. // create a combined filter method when needed
  1930. if (this.options.filter && options && options.filter) {
  1931. viewOptions.filter = function (item) {
  1932. return me.options.filter(item) && options.filter(item);
  1933. }
  1934. }
  1935. // build up the call to the linked data set
  1936. var getArguments = [];
  1937. if (ids != undefined) {
  1938. getArguments.push(ids);
  1939. }
  1940. getArguments.push(viewOptions);
  1941. getArguments.push(data);
  1942. return this.data && this.data.get.apply(this.data, getArguments);
  1943. };
  1944. /**
  1945. * Get ids of all items or from a filtered set of items.
  1946. * @param {Object} [options] An Object with options. Available options:
  1947. * {function} [filter] filter items
  1948. * {String | function} [order] Order the items by
  1949. * a field name or custom sort function.
  1950. * @return {Array} ids
  1951. */
  1952. DataView.prototype.getIds = function (options) {
  1953. var ids;
  1954. if (this.data) {
  1955. var defaultFilter = this.options.filter;
  1956. var filter;
  1957. if (options && options.filter) {
  1958. if (defaultFilter) {
  1959. filter = function (item) {
  1960. return defaultFilter(item) && options.filter(item);
  1961. }
  1962. }
  1963. else {
  1964. filter = options.filter;
  1965. }
  1966. }
  1967. else {
  1968. filter = defaultFilter;
  1969. }
  1970. ids = this.data.getIds({
  1971. filter: filter,
  1972. order: options && options.order
  1973. });
  1974. }
  1975. else {
  1976. ids = [];
  1977. }
  1978. return ids;
  1979. };
  1980. /**
  1981. * Event listener. Will propagate all events from the connected data set to
  1982. * the subscribers of the DataView, but will filter the items and only trigger
  1983. * when there are changes in the filtered data set.
  1984. * @param {String} event
  1985. * @param {Object | null} params
  1986. * @param {String} senderId
  1987. * @private
  1988. */
  1989. DataView.prototype._onEvent = function (event, params, senderId) {
  1990. var i, len, id, item,
  1991. ids = params && params.items,
  1992. data = this.data,
  1993. added = [],
  1994. updated = [],
  1995. removed = [];
  1996. if (ids && data) {
  1997. switch (event) {
  1998. case 'add':
  1999. // filter the ids of the added items
  2000. for (i = 0, len = ids.length; i < len; i++) {
  2001. id = ids[i];
  2002. item = this.get(id);
  2003. if (item) {
  2004. this.ids[id] = true;
  2005. added.push(id);
  2006. }
  2007. }
  2008. break;
  2009. case 'update':
  2010. // determine the event from the views viewpoint: an updated
  2011. // item can be added, updated, or removed from this view.
  2012. for (i = 0, len = ids.length; i < len; i++) {
  2013. id = ids[i];
  2014. item = this.get(id);
  2015. if (item) {
  2016. if (this.ids[id]) {
  2017. updated.push(id);
  2018. }
  2019. else {
  2020. this.ids[id] = true;
  2021. added.push(id);
  2022. }
  2023. }
  2024. else {
  2025. if (this.ids[id]) {
  2026. delete this.ids[id];
  2027. removed.push(id);
  2028. }
  2029. else {
  2030. // nothing interesting for me :-(
  2031. }
  2032. }
  2033. }
  2034. break;
  2035. case 'remove':
  2036. // filter the ids of the removed items
  2037. for (i = 0, len = ids.length; i < len; i++) {
  2038. id = ids[i];
  2039. if (this.ids[id]) {
  2040. delete this.ids[id];
  2041. removed.push(id);
  2042. }
  2043. }
  2044. break;
  2045. }
  2046. if (added.length) {
  2047. this._trigger('add', {items: added}, senderId);
  2048. }
  2049. if (updated.length) {
  2050. this._trigger('update', {items: updated}, senderId);
  2051. }
  2052. if (removed.length) {
  2053. this._trigger('remove', {items: removed}, senderId);
  2054. }
  2055. }
  2056. };
  2057. // copy subscription functionality from DataSet
  2058. DataView.prototype.subscribe = DataSet.prototype.subscribe;
  2059. DataView.prototype.unsubscribe = DataSet.prototype.unsubscribe;
  2060. DataView.prototype._trigger = DataSet.prototype._trigger;
  2061. /**
  2062. * @constructor TimeStep
  2063. * The class TimeStep is an iterator for dates. You provide a start date and an
  2064. * end date. The class itself determines the best scale (step size) based on the
  2065. * provided start Date, end Date, and minimumStep.
  2066. *
  2067. * If minimumStep is provided, the step size is chosen as close as possible
  2068. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2069. * provided, the scale is set to 1 DAY.
  2070. * The minimumStep should correspond with the onscreen size of about 6 characters
  2071. *
  2072. * Alternatively, you can set a scale by hand.
  2073. * After creation, you can initialize the class by executing first(). Then you
  2074. * can iterate from the start date to the end date via next(). You can check if
  2075. * the end date is reached with the function hasNext(). After each step, you can
  2076. * retrieve the current date via getCurrent().
  2077. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  2078. * days, to years.
  2079. *
  2080. * Version: 1.2
  2081. *
  2082. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  2083. * or new Date(2010, 9, 21, 23, 45, 00)
  2084. * @param {Date} [end] The end date
  2085. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2086. */
  2087. TimeStep = function(start, end, minimumStep) {
  2088. // variables
  2089. this.current = new Date();
  2090. this._start = new Date();
  2091. this._end = new Date();
  2092. this.autoScale = true;
  2093. this.scale = TimeStep.SCALE.DAY;
  2094. this.step = 1;
  2095. // initialize the range
  2096. this.setRange(start, end, minimumStep);
  2097. };
  2098. /// enum scale
  2099. TimeStep.SCALE = {
  2100. MILLISECOND: 1,
  2101. SECOND: 2,
  2102. MINUTE: 3,
  2103. HOUR: 4,
  2104. DAY: 5,
  2105. WEEKDAY: 6,
  2106. MONTH: 7,
  2107. YEAR: 8
  2108. };
  2109. /**
  2110. * Set a new range
  2111. * If minimumStep is provided, the step size is chosen as close as possible
  2112. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2113. * provided, the scale is set to 1 DAY.
  2114. * The minimumStep should correspond with the onscreen size of about 6 characters
  2115. * @param {Date} [start] The start date and time.
  2116. * @param {Date} [end] The end date and time.
  2117. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  2118. */
  2119. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  2120. if (!(start instanceof Date) || !(end instanceof Date)) {
  2121. //throw "No legal start or end date in method setRange";
  2122. return;
  2123. }
  2124. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  2125. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  2126. if (this.autoScale) {
  2127. this.setMinimumStep(minimumStep);
  2128. }
  2129. };
  2130. /**
  2131. * Set the range iterator to the start date.
  2132. */
  2133. TimeStep.prototype.first = function() {
  2134. this.current = new Date(this._start.valueOf());
  2135. this.roundToMinor();
  2136. };
  2137. /**
  2138. * Round the current date to the first minor date value
  2139. * This must be executed once when the current date is set to start Date
  2140. */
  2141. TimeStep.prototype.roundToMinor = function() {
  2142. // round to floor
  2143. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  2144. //noinspection FallthroughInSwitchStatementJS
  2145. switch (this.scale) {
  2146. case TimeStep.SCALE.YEAR:
  2147. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  2148. this.current.setMonth(0);
  2149. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  2150. case TimeStep.SCALE.DAY: // intentional fall through
  2151. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  2152. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  2153. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  2154. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  2155. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  2156. }
  2157. if (this.step != 1) {
  2158. // round down to the first minor value that is a multiple of the current step size
  2159. switch (this.scale) {
  2160. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  2161. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  2162. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  2163. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  2164. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2165. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  2166. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  2167. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  2168. default: break;
  2169. }
  2170. }
  2171. };
  2172. /**
  2173. * Check if the there is a next step
  2174. * @return {boolean} true if the current date has not passed the end date
  2175. */
  2176. TimeStep.prototype.hasNext = function () {
  2177. return (this.current.valueOf() <= this._end.valueOf());
  2178. };
  2179. /**
  2180. * Do the next step
  2181. */
  2182. TimeStep.prototype.next = function() {
  2183. var prev = this.current.valueOf();
  2184. // Two cases, needed to prevent issues with switching daylight savings
  2185. // (end of March and end of October)
  2186. if (this.current.getMonth() < 6) {
  2187. switch (this.scale) {
  2188. case TimeStep.SCALE.MILLISECOND:
  2189. this.current = new Date(this.current.valueOf() + this.step); break;
  2190. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  2191. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  2192. case TimeStep.SCALE.HOUR:
  2193. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  2194. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  2195. var h = this.current.getHours();
  2196. this.current.setHours(h - (h % this.step));
  2197. break;
  2198. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2199. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2200. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2201. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2202. default: break;
  2203. }
  2204. }
  2205. else {
  2206. switch (this.scale) {
  2207. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  2208. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  2209. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  2210. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  2211. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2212. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2213. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2214. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2215. default: break;
  2216. }
  2217. }
  2218. if (this.step != 1) {
  2219. // round down to the correct major value
  2220. switch (this.scale) {
  2221. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  2222. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  2223. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  2224. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  2225. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2226. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  2227. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  2228. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  2229. default: break;
  2230. }
  2231. }
  2232. // safety mechanism: if current time is still unchanged, move to the end
  2233. if (this.current.valueOf() == prev) {
  2234. this.current = new Date(this._end.valueOf());
  2235. }
  2236. };
  2237. /**
  2238. * Get the current datetime
  2239. * @return {Date} current The current date
  2240. */
  2241. TimeStep.prototype.getCurrent = function() {
  2242. return this.current;
  2243. };
  2244. /**
  2245. * Set a custom scale. Autoscaling will be disabled.
  2246. * For example setScale(SCALE.MINUTES, 5) will result
  2247. * in minor steps of 5 minutes, and major steps of an hour.
  2248. *
  2249. * @param {TimeStep.SCALE} newScale
  2250. * A scale. Choose from SCALE.MILLISECOND,
  2251. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  2252. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  2253. * SCALE.YEAR.
  2254. * @param {Number} newStep A step size, by default 1. Choose for
  2255. * example 1, 2, 5, or 10.
  2256. */
  2257. TimeStep.prototype.setScale = function(newScale, newStep) {
  2258. this.scale = newScale;
  2259. if (newStep > 0) {
  2260. this.step = newStep;
  2261. }
  2262. this.autoScale = false;
  2263. };
  2264. /**
  2265. * Enable or disable autoscaling
  2266. * @param {boolean} enable If true, autoascaling is set true
  2267. */
  2268. TimeStep.prototype.setAutoScale = function (enable) {
  2269. this.autoScale = enable;
  2270. };
  2271. /**
  2272. * Automatically determine the scale that bests fits the provided minimum step
  2273. * @param {Number} [minimumStep] The minimum step size in milliseconds
  2274. */
  2275. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  2276. if (minimumStep == undefined) {
  2277. return;
  2278. }
  2279. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  2280. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  2281. var stepDay = (1000 * 60 * 60 * 24);
  2282. var stepHour = (1000 * 60 * 60);
  2283. var stepMinute = (1000 * 60);
  2284. var stepSecond = (1000);
  2285. var stepMillisecond= (1);
  2286. // find the smallest step that is larger than the provided minimumStep
  2287. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  2288. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  2289. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  2290. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  2291. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  2292. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  2293. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  2294. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  2295. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  2296. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  2297. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  2298. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  2299. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  2300. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  2301. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  2302. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  2303. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  2304. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  2305. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  2306. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  2307. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  2308. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  2309. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  2310. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  2311. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  2312. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  2313. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  2314. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  2315. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  2316. };
  2317. /**
  2318. * Snap a date to a rounded value. The snap intervals are dependent on the
  2319. * current scale and step.
  2320. * @param {Date} date the date to be snapped
  2321. */
  2322. TimeStep.prototype.snap = function(date) {
  2323. if (this.scale == TimeStep.SCALE.YEAR) {
  2324. var year = date.getFullYear() + Math.round(date.getMonth() / 12);
  2325. date.setFullYear(Math.round(year / this.step) * this.step);
  2326. date.setMonth(0);
  2327. date.setDate(0);
  2328. date.setHours(0);
  2329. date.setMinutes(0);
  2330. date.setSeconds(0);
  2331. date.setMilliseconds(0);
  2332. }
  2333. else if (this.scale == TimeStep.SCALE.MONTH) {
  2334. if (date.getDate() > 15) {
  2335. date.setDate(1);
  2336. date.setMonth(date.getMonth() + 1);
  2337. // important: first set Date to 1, after that change the month.
  2338. }
  2339. else {
  2340. date.setDate(1);
  2341. }
  2342. date.setHours(0);
  2343. date.setMinutes(0);
  2344. date.setSeconds(0);
  2345. date.setMilliseconds(0);
  2346. }
  2347. else if (this.scale == TimeStep.SCALE.DAY ||
  2348. this.scale == TimeStep.SCALE.WEEKDAY) {
  2349. //noinspection FallthroughInSwitchStatementJS
  2350. switch (this.step) {
  2351. case 5:
  2352. case 2:
  2353. date.setHours(Math.round(date.getHours() / 24) * 24); break;
  2354. default:
  2355. date.setHours(Math.round(date.getHours() / 12) * 12); break;
  2356. }
  2357. date.setMinutes(0);
  2358. date.setSeconds(0);
  2359. date.setMilliseconds(0);
  2360. }
  2361. else if (this.scale == TimeStep.SCALE.HOUR) {
  2362. switch (this.step) {
  2363. case 4:
  2364. date.setMinutes(Math.round(date.getMinutes() / 60) * 60); break;
  2365. default:
  2366. date.setMinutes(Math.round(date.getMinutes() / 30) * 30); break;
  2367. }
  2368. date.setSeconds(0);
  2369. date.setMilliseconds(0);
  2370. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  2371. //noinspection FallthroughInSwitchStatementJS
  2372. switch (this.step) {
  2373. case 15:
  2374. case 10:
  2375. date.setMinutes(Math.round(date.getMinutes() / 5) * 5);
  2376. date.setSeconds(0);
  2377. break;
  2378. case 5:
  2379. date.setSeconds(Math.round(date.getSeconds() / 60) * 60); break;
  2380. default:
  2381. date.setSeconds(Math.round(date.getSeconds() / 30) * 30); break;
  2382. }
  2383. date.setMilliseconds(0);
  2384. }
  2385. else if (this.scale == TimeStep.SCALE.SECOND) {
  2386. //noinspection FallthroughInSwitchStatementJS
  2387. switch (this.step) {
  2388. case 15:
  2389. case 10:
  2390. date.setSeconds(Math.round(date.getSeconds() / 5) * 5);
  2391. date.setMilliseconds(0);
  2392. break;
  2393. case 5:
  2394. date.setMilliseconds(Math.round(date.getMilliseconds() / 1000) * 1000); break;
  2395. default:
  2396. date.setMilliseconds(Math.round(date.getMilliseconds() / 500) * 500); break;
  2397. }
  2398. }
  2399. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  2400. var step = this.step > 5 ? this.step / 2 : 1;
  2401. date.setMilliseconds(Math.round(date.getMilliseconds() / step) * step);
  2402. }
  2403. };
  2404. /**
  2405. * Check if the current value is a major value (for example when the step
  2406. * is DAY, a major value is each first day of the MONTH)
  2407. * @return {boolean} true if current date is major, else false.
  2408. */
  2409. TimeStep.prototype.isMajor = function() {
  2410. switch (this.scale) {
  2411. case TimeStep.SCALE.MILLISECOND:
  2412. return (this.current.getMilliseconds() == 0);
  2413. case TimeStep.SCALE.SECOND:
  2414. return (this.current.getSeconds() == 0);
  2415. case TimeStep.SCALE.MINUTE:
  2416. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  2417. // Note: this is no bug. Major label is equal for both minute and hour scale
  2418. case TimeStep.SCALE.HOUR:
  2419. return (this.current.getHours() == 0);
  2420. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2421. case TimeStep.SCALE.DAY:
  2422. return (this.current.getDate() == 1);
  2423. case TimeStep.SCALE.MONTH:
  2424. return (this.current.getMonth() == 0);
  2425. case TimeStep.SCALE.YEAR:
  2426. return false;
  2427. default:
  2428. return false;
  2429. }
  2430. };
  2431. /**
  2432. * Returns formatted text for the minor axislabel, depending on the current
  2433. * date and the scale. For example when scale is MINUTE, the current time is
  2434. * formatted as "hh:mm".
  2435. * @param {Date} [date] custom date. if not provided, current date is taken
  2436. */
  2437. TimeStep.prototype.getLabelMinor = function(date) {
  2438. if (date == undefined) {
  2439. date = this.current;
  2440. }
  2441. switch (this.scale) {
  2442. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  2443. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  2444. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  2445. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  2446. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  2447. case TimeStep.SCALE.DAY: return moment(date).format('D');
  2448. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  2449. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  2450. default: return '';
  2451. }
  2452. };
  2453. /**
  2454. * Returns formatted text for the major axis label, depending on the current
  2455. * date and the scale. For example when scale is MINUTE, the major scale is
  2456. * hours, and the hour will be formatted as "hh".
  2457. * @param {Date} [date] custom date. if not provided, current date is taken
  2458. */
  2459. TimeStep.prototype.getLabelMajor = function(date) {
  2460. if (date == undefined) {
  2461. date = this.current;
  2462. }
  2463. //noinspection FallthroughInSwitchStatementJS
  2464. switch (this.scale) {
  2465. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  2466. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  2467. case TimeStep.SCALE.MINUTE:
  2468. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  2469. case TimeStep.SCALE.WEEKDAY:
  2470. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  2471. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  2472. case TimeStep.SCALE.YEAR: return '';
  2473. default: return '';
  2474. }
  2475. };
  2476. /**
  2477. * @constructor Stack
  2478. * Stacks items on top of each other.
  2479. * @param {ItemSet} parent
  2480. * @param {Object} [options]
  2481. */
  2482. function Stack (parent, options) {
  2483. this.parent = parent;
  2484. this.options = options || {};
  2485. this.defaultOptions = {
  2486. order: function (a, b) {
  2487. //return (b.width - a.width) || (a.left - b.left); // TODO: cleanup
  2488. // Order: ranges over non-ranges, ranged ordered by width, and
  2489. // lastly ordered by start.
  2490. if (a instanceof ItemRange) {
  2491. if (b instanceof ItemRange) {
  2492. var aInt = (a.data.end - a.data.start);
  2493. var bInt = (b.data.end - b.data.start);
  2494. return (aInt - bInt) || (a.data.start - b.data.start);
  2495. }
  2496. else {
  2497. return -1;
  2498. }
  2499. }
  2500. else {
  2501. if (b instanceof ItemRange) {
  2502. return 1;
  2503. }
  2504. else {
  2505. return (a.data.start - b.data.start);
  2506. }
  2507. }
  2508. },
  2509. margin: {
  2510. item: 10
  2511. }
  2512. };
  2513. this.ordered = []; // ordered items
  2514. }
  2515. /**
  2516. * Set options for the stack
  2517. * @param {Object} options Available options:
  2518. * {ItemSet} parent
  2519. * {Number} margin
  2520. * {function} order Stacking order
  2521. */
  2522. Stack.prototype.setOptions = function setOptions (options) {
  2523. util.extend(this.options, options);
  2524. // TODO: register on data changes at the connected parent itemset, and update the changed part only and immediately
  2525. };
  2526. /**
  2527. * Stack the items such that they don't overlap. The items will have a minimal
  2528. * distance equal to options.margin.item.
  2529. */
  2530. Stack.prototype.update = function update() {
  2531. this._order();
  2532. this._stack();
  2533. };
  2534. /**
  2535. * Order the items. The items are ordered by width first, and by left position
  2536. * second.
  2537. * If a custom order function has been provided via the options, then this will
  2538. * be used.
  2539. * @private
  2540. */
  2541. Stack.prototype._order = function _order () {
  2542. var items = this.parent.items;
  2543. if (!items) {
  2544. throw new Error('Cannot stack items: parent does not contain items');
  2545. }
  2546. // TODO: store the sorted items, to have less work later on
  2547. var ordered = [];
  2548. var index = 0;
  2549. // items is a map (no array)
  2550. util.forEach(items, function (item) {
  2551. if (item.visible) {
  2552. ordered[index] = item;
  2553. index++;
  2554. }
  2555. });
  2556. //if a customer stack order function exists, use it.
  2557. var order = this.options.order || this.defaultOptions.order;
  2558. if (!(typeof order === 'function')) {
  2559. throw new Error('Option order must be a function');
  2560. }
  2561. ordered.sort(order);
  2562. this.ordered = ordered;
  2563. };
  2564. /**
  2565. * Adjust vertical positions of the events such that they don't overlap each
  2566. * other.
  2567. * @private
  2568. */
  2569. Stack.prototype._stack = function _stack () {
  2570. var i,
  2571. iMax,
  2572. ordered = this.ordered,
  2573. options = this.options,
  2574. orientation = options.orientation || this.defaultOptions.orientation,
  2575. axisOnTop = (orientation == 'top'),
  2576. margin;
  2577. if (options.margin && options.margin.item !== undefined) {
  2578. margin = options.margin.item;
  2579. }
  2580. else {
  2581. margin = this.defaultOptions.margin.item
  2582. }
  2583. // calculate new, non-overlapping positions
  2584. for (i = 0, iMax = ordered.length; i < iMax; i++) {
  2585. var item = ordered[i];
  2586. var collidingItem = null;
  2587. do {
  2588. // TODO: optimize checking for overlap. when there is a gap without items,
  2589. // you only need to check for items from the next item on, not from zero
  2590. collidingItem = this.checkOverlap(ordered, i, 0, i - 1, margin);
  2591. if (collidingItem != null) {
  2592. // There is a collision. Reposition the event above the colliding element
  2593. if (axisOnTop) {
  2594. item.top = collidingItem.top + collidingItem.height + margin;
  2595. }
  2596. else {
  2597. item.top = collidingItem.top - item.height - margin;
  2598. }
  2599. }
  2600. } while (collidingItem);
  2601. }
  2602. };
  2603. /**
  2604. * Check if the destiny position of given item overlaps with any
  2605. * of the other items from index itemStart to itemEnd.
  2606. * @param {Array} items Array with items
  2607. * @param {int} itemIndex Number of the item to be checked for overlap
  2608. * @param {int} itemStart First item to be checked.
  2609. * @param {int} itemEnd Last item to be checked.
  2610. * @return {Object | null} colliding item, or undefined when no collisions
  2611. * @param {Number} margin A minimum required margin.
  2612. * If margin is provided, the two items will be
  2613. * marked colliding when they overlap or
  2614. * when the margin between the two is smaller than
  2615. * the requested margin.
  2616. */
  2617. Stack.prototype.checkOverlap = function checkOverlap (items, itemIndex,
  2618. itemStart, itemEnd, margin) {
  2619. var collision = this.collision;
  2620. // we loop from end to start, as we suppose that the chance of a
  2621. // collision is larger for items at the end, so check these first.
  2622. var a = items[itemIndex];
  2623. for (var i = itemEnd; i >= itemStart; i--) {
  2624. var b = items[i];
  2625. if (collision(a, b, margin)) {
  2626. if (i != itemIndex) {
  2627. return b;
  2628. }
  2629. }
  2630. }
  2631. return null;
  2632. };
  2633. /**
  2634. * Test if the two provided items collide
  2635. * The items must have parameters left, width, top, and height.
  2636. * @param {Component} a The first item
  2637. * @param {Component} b The second item
  2638. * @param {Number} margin A minimum required margin.
  2639. * If margin is provided, the two items will be
  2640. * marked colliding when they overlap or
  2641. * when the margin between the two is smaller than
  2642. * the requested margin.
  2643. * @return {boolean} true if a and b collide, else false
  2644. */
  2645. Stack.prototype.collision = function collision (a, b, margin) {
  2646. return ((a.left - margin) < (b.left + b.width) &&
  2647. (a.left + a.width + margin) > b.left &&
  2648. (a.top - margin) < (b.top + b.height) &&
  2649. (a.top + a.height + margin) > b.top);
  2650. };
  2651. /**
  2652. * @constructor Range
  2653. * A Range controls a numeric range with a start and end value.
  2654. * The Range adjusts the range based on mouse events or programmatic changes,
  2655. * and triggers events when the range is changing or has been changed.
  2656. * @param {Object} [options] See description at Range.setOptions
  2657. * @extends Controller
  2658. */
  2659. function Range(options) {
  2660. this.id = util.randomUUID();
  2661. this.start = 0; // Number
  2662. this.end = 0; // Number
  2663. this.options = {
  2664. min: null,
  2665. max: null,
  2666. zoomMin: null,
  2667. zoomMax: null
  2668. };
  2669. this.listeners = [];
  2670. this.setOptions(options);
  2671. }
  2672. /**
  2673. * Set options for the range controller
  2674. * @param {Object} options Available options:
  2675. * {Number} start Set start value of the range
  2676. * {Number} end Set end value of the range
  2677. * {Number} min Minimum value for start
  2678. * {Number} max Maximum value for end
  2679. * {Number} zoomMin Set a minimum value for
  2680. * (end - start).
  2681. * {Number} zoomMax Set a maximum value for
  2682. * (end - start).
  2683. */
  2684. Range.prototype.setOptions = function (options) {
  2685. util.extend(this.options, options);
  2686. if (options.start != null || options.end != null) {
  2687. this.setRange(options.start, options.end);
  2688. }
  2689. };
  2690. /**
  2691. * Add listeners for mouse and touch events to the component
  2692. * @param {Component} component
  2693. * @param {String} event Available events: 'move', 'zoom'
  2694. * @param {String} direction Available directions: 'horizontal', 'vertical'
  2695. */
  2696. Range.prototype.subscribe = function (component, event, direction) {
  2697. var me = this;
  2698. var listener;
  2699. if (direction != 'horizontal' && direction != 'vertical') {
  2700. throw new TypeError('Unknown direction "' + direction + '". ' +
  2701. 'Choose "horizontal" or "vertical".');
  2702. }
  2703. //noinspection FallthroughInSwitchStatementJS
  2704. if (event == 'move') {
  2705. listener = {
  2706. component: component,
  2707. event: event,
  2708. direction: direction,
  2709. callback: function (event) {
  2710. me._onMouseDown(event, listener);
  2711. },
  2712. params: {}
  2713. };
  2714. component.on('mousedown', listener.callback);
  2715. me.listeners.push(listener);
  2716. }
  2717. else if (event == 'zoom') {
  2718. listener = {
  2719. component: component,
  2720. event: event,
  2721. direction: direction,
  2722. callback: function (event) {
  2723. me._onMouseWheel(event, listener);
  2724. },
  2725. params: {}
  2726. };
  2727. component.on('mousewheel', listener.callback);
  2728. me.listeners.push(listener);
  2729. }
  2730. else {
  2731. throw new TypeError('Unknown event "' + event + '". ' +
  2732. 'Choose "move" or "zoom".');
  2733. }
  2734. };
  2735. /**
  2736. * Event handler
  2737. * @param {String} event name of the event, for example 'click', 'mousemove'
  2738. * @param {function} callback callback handler, invoked with the raw HTML Event
  2739. * as parameter.
  2740. */
  2741. Range.prototype.on = function (event, callback) {
  2742. events.addListener(this, event, callback);
  2743. };
  2744. /**
  2745. * Trigger an event
  2746. * @param {String} event name of the event, available events: 'rangechange',
  2747. * 'rangechanged'
  2748. * @private
  2749. */
  2750. Range.prototype._trigger = function (event) {
  2751. events.trigger(this, event, {
  2752. start: this.start,
  2753. end: this.end
  2754. });
  2755. };
  2756. /**
  2757. * Set a new start and end range
  2758. * @param {Number} start
  2759. * @param {Number} end
  2760. */
  2761. Range.prototype.setRange = function(start, end) {
  2762. var changed = this._applyRange(start, end);
  2763. if (changed) {
  2764. this._trigger('rangechange');
  2765. this._trigger('rangechanged');
  2766. }
  2767. };
  2768. /**
  2769. * Set a new start and end range. This method is the same as setRange, but
  2770. * does not trigger a range change and range changed event, and it returns
  2771. * true when the range is changed
  2772. * @param {Number} start
  2773. * @param {Number} end
  2774. * @return {Boolean} changed
  2775. * @private
  2776. */
  2777. Range.prototype._applyRange = function(start, end) {
  2778. var newStart = (start != null) ? util.cast(start, 'Number') : this.start;
  2779. var newEnd = (end != null) ? util.cast(end, 'Number') : this.end;
  2780. var diff;
  2781. // check for valid number
  2782. if (isNaN(newStart)) {
  2783. throw new Error('Invalid start "' + start + '"');
  2784. }
  2785. if (isNaN(newEnd)) {
  2786. throw new Error('Invalid end "' + end + '"');
  2787. }
  2788. // prevent start < end
  2789. if (newEnd < newStart) {
  2790. newEnd = newStart;
  2791. }
  2792. // prevent start < min
  2793. if (this.options.min != null) {
  2794. var min = this.options.min.valueOf();
  2795. if (newStart < min) {
  2796. diff = (min - newStart);
  2797. newStart += diff;
  2798. newEnd += diff;
  2799. }
  2800. }
  2801. // prevent end > max
  2802. if (this.options.max != null) {
  2803. var max = this.options.max.valueOf();
  2804. if (newEnd > max) {
  2805. diff = (newEnd - max);
  2806. newStart -= diff;
  2807. newEnd -= diff;
  2808. }
  2809. }
  2810. // prevent (end-start) > zoomMin
  2811. if (this.options.zoomMin != null) {
  2812. var zoomMin = this.options.zoomMin.valueOf();
  2813. if (zoomMin < 0) {
  2814. zoomMin = 0;
  2815. }
  2816. if ((newEnd - newStart) < zoomMin) {
  2817. if ((this.end - this.start) > zoomMin) {
  2818. // zoom to the minimum
  2819. diff = (zoomMin - (newEnd - newStart));
  2820. newStart -= diff / 2;
  2821. newEnd += diff / 2;
  2822. }
  2823. else {
  2824. // ingore this action, we are already zoomed to the minimum
  2825. newStart = this.start;
  2826. newEnd = this.end;
  2827. }
  2828. }
  2829. }
  2830. // prevent (end-start) > zoomMin
  2831. if (this.options.zoomMax != null) {
  2832. var zoomMax = this.options.zoomMax.valueOf();
  2833. if (zoomMax < 0) {
  2834. zoomMax = 0;
  2835. }
  2836. if ((newEnd - newStart) > zoomMax) {
  2837. if ((this.end - this.start) < zoomMax) {
  2838. // zoom to the maximum
  2839. diff = ((newEnd - newStart) - zoomMax);
  2840. newStart += diff / 2;
  2841. newEnd -= diff / 2;
  2842. }
  2843. else {
  2844. // ingore this action, we are already zoomed to the maximum
  2845. newStart = this.start;
  2846. newEnd = this.end;
  2847. }
  2848. }
  2849. }
  2850. var changed = (this.start != newStart || this.end != newEnd);
  2851. this.start = newStart;
  2852. this.end = newEnd;
  2853. return changed;
  2854. };
  2855. /**
  2856. * Retrieve the current range.
  2857. * @return {Object} An object with start and end properties
  2858. */
  2859. Range.prototype.getRange = function() {
  2860. return {
  2861. start: this.start,
  2862. end: this.end
  2863. };
  2864. };
  2865. /**
  2866. * Calculate the conversion offset and factor for current range, based on
  2867. * the provided width
  2868. * @param {Number} width
  2869. * @returns {{offset: number, factor: number}} conversion
  2870. */
  2871. Range.prototype.conversion = function (width) {
  2872. var start = this.start;
  2873. var end = this.end;
  2874. return Range.conversion(this.start, this.end, width);
  2875. };
  2876. /**
  2877. * Static method to calculate the conversion offset and factor for a range,
  2878. * based on the provided start, end, and width
  2879. * @param {Number} start
  2880. * @param {Number} end
  2881. * @param {Number} width
  2882. * @returns {{offset: number, factor: number}} conversion
  2883. */
  2884. Range.conversion = function (start, end, width) {
  2885. if (width != 0 && (end - start != 0)) {
  2886. return {
  2887. offset: start,
  2888. factor: width / (end - start)
  2889. }
  2890. }
  2891. else {
  2892. return {
  2893. offset: 0,
  2894. factor: 1
  2895. };
  2896. }
  2897. };
  2898. /**
  2899. * Start moving horizontally or vertically
  2900. * @param {Event} event
  2901. * @param {Object} listener Listener containing the component and params
  2902. * @private
  2903. */
  2904. Range.prototype._onMouseDown = function(event, listener) {
  2905. event = event || window.event;
  2906. var params = listener.params;
  2907. // only react on left mouse button down
  2908. var leftButtonDown = event.which ? (event.which == 1) : (event.button == 1);
  2909. if (!leftButtonDown) {
  2910. return;
  2911. }
  2912. // get mouse position
  2913. params.mouseX = util.getPageX(event);
  2914. params.mouseY = util.getPageY(event);
  2915. params.previousLeft = 0;
  2916. params.previousOffset = 0;
  2917. params.moved = false;
  2918. params.start = this.start;
  2919. params.end = this.end;
  2920. var frame = listener.component.frame;
  2921. if (frame) {
  2922. frame.style.cursor = 'move';
  2923. }
  2924. // add event listeners to handle moving the contents
  2925. // we store the function onmousemove and onmouseup in the timeaxis,
  2926. // so we can remove the eventlisteners lateron in the function onmouseup
  2927. var me = this;
  2928. if (!params.onMouseMove) {
  2929. params.onMouseMove = function (event) {
  2930. me._onMouseMove(event, listener);
  2931. };
  2932. util.addEventListener(document, "mousemove", params.onMouseMove);
  2933. }
  2934. if (!params.onMouseUp) {
  2935. params.onMouseUp = function (event) {
  2936. me._onMouseUp(event, listener);
  2937. };
  2938. util.addEventListener(document, "mouseup", params.onMouseUp);
  2939. }
  2940. util.preventDefault(event);
  2941. };
  2942. /**
  2943. * Perform moving operating.
  2944. * This function activated from within the funcion TimeAxis._onMouseDown().
  2945. * @param {Event} event
  2946. * @param {Object} listener
  2947. * @private
  2948. */
  2949. Range.prototype._onMouseMove = function (event, listener) {
  2950. event = event || window.event;
  2951. var params = listener.params;
  2952. // calculate change in mouse position
  2953. var mouseX = util.getPageX(event);
  2954. var mouseY = util.getPageY(event);
  2955. if (params.mouseX == undefined) {
  2956. params.mouseX = mouseX;
  2957. }
  2958. if (params.mouseY == undefined) {
  2959. params.mouseY = mouseY;
  2960. }
  2961. var diffX = mouseX - params.mouseX;
  2962. var diffY = mouseY - params.mouseY;
  2963. var diff = (listener.direction == 'horizontal') ? diffX : diffY;
  2964. // if mouse movement is big enough, register it as a "moved" event
  2965. if (Math.abs(diff) >= 1) {
  2966. params.moved = true;
  2967. }
  2968. var interval = (params.end - params.start);
  2969. var width = (listener.direction == 'horizontal') ?
  2970. listener.component.width : listener.component.height;
  2971. var diffRange = -diff / width * interval;
  2972. this._applyRange(params.start + diffRange, params.end + diffRange);
  2973. // fire a rangechange event
  2974. this._trigger('rangechange');
  2975. util.preventDefault(event);
  2976. };
  2977. /**
  2978. * Stop moving operating.
  2979. * This function activated from within the function Range._onMouseDown().
  2980. * @param {event} event
  2981. * @param {Object} listener
  2982. * @private
  2983. */
  2984. Range.prototype._onMouseUp = function (event, listener) {
  2985. event = event || window.event;
  2986. var params = listener.params;
  2987. if (listener.component.frame) {
  2988. listener.component.frame.style.cursor = 'auto';
  2989. }
  2990. // remove event listeners here, important for Safari
  2991. if (params.onMouseMove) {
  2992. util.removeEventListener(document, "mousemove", params.onMouseMove);
  2993. params.onMouseMove = null;
  2994. }
  2995. if (params.onMouseUp) {
  2996. util.removeEventListener(document, "mouseup", params.onMouseUp);
  2997. params.onMouseUp = null;
  2998. }
  2999. //util.preventDefault(event);
  3000. if (params.moved) {
  3001. // fire a rangechanged event
  3002. this._trigger('rangechanged');
  3003. }
  3004. };
  3005. /**
  3006. * Event handler for mouse wheel event, used to zoom
  3007. * Code from http://adomas.org/javascript-mouse-wheel/
  3008. * @param {Event} event
  3009. * @param {Object} listener
  3010. * @private
  3011. */
  3012. Range.prototype._onMouseWheel = function(event, listener) {
  3013. event = event || window.event;
  3014. // retrieve delta
  3015. var delta = 0;
  3016. if (event.wheelDelta) { /* IE/Opera. */
  3017. delta = event.wheelDelta / 120;
  3018. } else if (event.detail) { /* Mozilla case. */
  3019. // In Mozilla, sign of delta is different than in IE.
  3020. // Also, delta is multiple of 3.
  3021. delta = -event.detail / 3;
  3022. }
  3023. // If delta is nonzero, handle it.
  3024. // Basically, delta is now positive if wheel was scrolled up,
  3025. // and negative, if wheel was scrolled down.
  3026. if (delta) {
  3027. var me = this;
  3028. var zoom = function () {
  3029. // perform the zoom action. Delta is normally 1 or -1
  3030. var zoomFactor = delta / 5.0;
  3031. var zoomAround = null;
  3032. var frame = listener.component.frame;
  3033. if (frame) {
  3034. var size, conversion;
  3035. if (listener.direction == 'horizontal') {
  3036. size = listener.component.width;
  3037. conversion = me.conversion(size);
  3038. var frameLeft = util.getAbsoluteLeft(frame);
  3039. var mouseX = util.getPageX(event);
  3040. zoomAround = (mouseX - frameLeft) / conversion.factor + conversion.offset;
  3041. }
  3042. else {
  3043. size = listener.component.height;
  3044. conversion = me.conversion(size);
  3045. var frameTop = util.getAbsoluteTop(frame);
  3046. var mouseY = util.getPageY(event);
  3047. zoomAround = ((frameTop + size - mouseY) - frameTop) / conversion.factor + conversion.offset;
  3048. }
  3049. }
  3050. me.zoom(zoomFactor, zoomAround);
  3051. };
  3052. zoom();
  3053. }
  3054. // Prevent default actions caused by mouse wheel.
  3055. // That might be ugly, but we handle scrolls somehow
  3056. // anyway, so don't bother here...
  3057. util.preventDefault(event);
  3058. };
  3059. /**
  3060. * Zoom the range the given zoomfactor in or out. Start and end date will
  3061. * be adjusted, and the timeline will be redrawn. You can optionally give a
  3062. * date around which to zoom.
  3063. * For example, try zoomfactor = 0.1 or -0.1
  3064. * @param {Number} zoomFactor Zooming amount. Positive value will zoom in,
  3065. * negative value will zoom out
  3066. * @param {Number} zoomAround Value around which will be zoomed. Optional
  3067. */
  3068. Range.prototype.zoom = function(zoomFactor, zoomAround) {
  3069. // if zoomAroundDate is not provided, take it half between start Date and end Date
  3070. if (zoomAround == null) {
  3071. zoomAround = (this.start + this.end) / 2;
  3072. }
  3073. // prevent zoom factor larger than 1 or smaller than -1 (larger than 1 will
  3074. // result in a start>=end )
  3075. if (zoomFactor >= 1) {
  3076. zoomFactor = 0.9;
  3077. }
  3078. if (zoomFactor <= -1) {
  3079. zoomFactor = -0.9;
  3080. }
  3081. // adjust a negative factor such that zooming in with 0.1 equals zooming
  3082. // out with a factor -0.1
  3083. if (zoomFactor < 0) {
  3084. zoomFactor = zoomFactor / (1 + zoomFactor);
  3085. }
  3086. // zoom start and end relative to the zoomAround value
  3087. var startDiff = (this.start - zoomAround);
  3088. var endDiff = (this.end - zoomAround);
  3089. // calculate new start and end
  3090. var newStart = this.start - startDiff * zoomFactor;
  3091. var newEnd = this.end - endDiff * zoomFactor;
  3092. this.setRange(newStart, newEnd);
  3093. };
  3094. /**
  3095. * Move the range with a given factor to the left or right. Start and end
  3096. * value will be adjusted. For example, try moveFactor = 0.1 or -0.1
  3097. * @param {Number} moveFactor Moving amount. Positive value will move right,
  3098. * negative value will move left
  3099. */
  3100. Range.prototype.move = function(moveFactor) {
  3101. // zoom start Date and end Date relative to the zoomAroundDate
  3102. var diff = (this.end - this.start);
  3103. // apply new values
  3104. var newStart = this.start + diff * moveFactor;
  3105. var newEnd = this.end + diff * moveFactor;
  3106. // TODO: reckon with min and max range
  3107. this.start = newStart;
  3108. this.end = newEnd;
  3109. };
  3110. /**
  3111. * @constructor Controller
  3112. *
  3113. * A Controller controls the reflows and repaints of all visual components
  3114. */
  3115. function Controller () {
  3116. this.id = util.randomUUID();
  3117. this.components = {};
  3118. this.repaintTimer = undefined;
  3119. this.reflowTimer = undefined;
  3120. }
  3121. /**
  3122. * Add a component to the controller
  3123. * @param {Component} component
  3124. */
  3125. Controller.prototype.add = function add(component) {
  3126. // validate the component
  3127. if (component.id == undefined) {
  3128. throw new Error('Component has no field id');
  3129. }
  3130. if (!(component instanceof Component) && !(component instanceof Controller)) {
  3131. throw new TypeError('Component must be an instance of ' +
  3132. 'prototype Component or Controller');
  3133. }
  3134. // add the component
  3135. component.controller = this;
  3136. this.components[component.id] = component;
  3137. };
  3138. /**
  3139. * Remove a component from the controller
  3140. * @param {Component | String} component
  3141. */
  3142. Controller.prototype.remove = function remove(component) {
  3143. var id;
  3144. for (id in this.components) {
  3145. if (this.components.hasOwnProperty(id)) {
  3146. if (id == component || this.components[id] == component) {
  3147. break;
  3148. }
  3149. }
  3150. }
  3151. if (id) {
  3152. delete this.components[id];
  3153. }
  3154. };
  3155. /**
  3156. * Request a reflow. The controller will schedule a reflow
  3157. * @param {Boolean} [force] If true, an immediate reflow is forced. Default
  3158. * is false.
  3159. */
  3160. Controller.prototype.requestReflow = function requestReflow(force) {
  3161. if (force) {
  3162. this.reflow();
  3163. }
  3164. else {
  3165. if (!this.reflowTimer) {
  3166. var me = this;
  3167. this.reflowTimer = setTimeout(function () {
  3168. me.reflowTimer = undefined;
  3169. me.reflow();
  3170. }, 0);
  3171. }
  3172. }
  3173. };
  3174. /**
  3175. * Request a repaint. The controller will schedule a repaint
  3176. * @param {Boolean} [force] If true, an immediate repaint is forced. Default
  3177. * is false.
  3178. */
  3179. Controller.prototype.requestRepaint = function requestRepaint(force) {
  3180. if (force) {
  3181. this.repaint();
  3182. }
  3183. else {
  3184. if (!this.repaintTimer) {
  3185. var me = this;
  3186. this.repaintTimer = setTimeout(function () {
  3187. me.repaintTimer = undefined;
  3188. me.repaint();
  3189. }, 0);
  3190. }
  3191. }
  3192. };
  3193. /**
  3194. * Repaint all components
  3195. */
  3196. Controller.prototype.repaint = function repaint() {
  3197. var changed = false;
  3198. // cancel any running repaint request
  3199. if (this.repaintTimer) {
  3200. clearTimeout(this.repaintTimer);
  3201. this.repaintTimer = undefined;
  3202. }
  3203. var done = {};
  3204. function repaint(component, id) {
  3205. if (!(id in done)) {
  3206. // first repaint the components on which this component is dependent
  3207. if (component.depends) {
  3208. component.depends.forEach(function (dep) {
  3209. repaint(dep, dep.id);
  3210. });
  3211. }
  3212. if (component.parent) {
  3213. repaint(component.parent, component.parent.id);
  3214. }
  3215. // repaint the component itself and mark as done
  3216. changed = component.repaint() || changed;
  3217. done[id] = true;
  3218. }
  3219. }
  3220. util.forEach(this.components, repaint);
  3221. // immediately reflow when needed
  3222. if (changed) {
  3223. this.reflow();
  3224. }
  3225. // TODO: limit the number of nested reflows/repaints, prevent loop
  3226. };
  3227. /**
  3228. * Reflow all components
  3229. */
  3230. Controller.prototype.reflow = function reflow() {
  3231. var resized = false;
  3232. // cancel any running repaint request
  3233. if (this.reflowTimer) {
  3234. clearTimeout(this.reflowTimer);
  3235. this.reflowTimer = undefined;
  3236. }
  3237. var done = {};
  3238. function reflow(component, id) {
  3239. if (!(id in done)) {
  3240. // first reflow the components on which this component is dependent
  3241. if (component.depends) {
  3242. component.depends.forEach(function (dep) {
  3243. reflow(dep, dep.id);
  3244. });
  3245. }
  3246. if (component.parent) {
  3247. reflow(component.parent, component.parent.id);
  3248. }
  3249. // reflow the component itself and mark as done
  3250. resized = component.reflow() || resized;
  3251. done[id] = true;
  3252. }
  3253. }
  3254. util.forEach(this.components, reflow);
  3255. // immediately repaint when needed
  3256. if (resized) {
  3257. this.repaint();
  3258. }
  3259. // TODO: limit the number of nested reflows/repaints, prevent loop
  3260. };
  3261. /**
  3262. * Prototype for visual components
  3263. */
  3264. function Component () {
  3265. this.id = null;
  3266. this.parent = null;
  3267. this.depends = null;
  3268. this.controller = null;
  3269. this.options = null;
  3270. this.frame = null; // main DOM element
  3271. this.top = 0;
  3272. this.left = 0;
  3273. this.width = 0;
  3274. this.height = 0;
  3275. }
  3276. /**
  3277. * Set parameters for the frame. Parameters will be merged in current parameter
  3278. * set.
  3279. * @param {Object} options Available parameters:
  3280. * {String | function} [className]
  3281. * {EventBus} [eventBus]
  3282. * {String | Number | function} [left]
  3283. * {String | Number | function} [top]
  3284. * {String | Number | function} [width]
  3285. * {String | Number | function} [height]
  3286. */
  3287. Component.prototype.setOptions = function setOptions(options) {
  3288. if (options) {
  3289. util.extend(this.options, options);
  3290. if (this.controller) {
  3291. this.requestRepaint();
  3292. this.requestReflow();
  3293. }
  3294. }
  3295. };
  3296. /**
  3297. * Get an option value by name
  3298. * The function will first check this.options object, and else will check
  3299. * this.defaultOptions.
  3300. * @param {String} name
  3301. * @return {*} value
  3302. */
  3303. Component.prototype.getOption = function getOption(name) {
  3304. var value;
  3305. if (this.options) {
  3306. value = this.options[name];
  3307. }
  3308. if (value === undefined && this.defaultOptions) {
  3309. value = this.defaultOptions[name];
  3310. }
  3311. return value;
  3312. };
  3313. /**
  3314. * Get the container element of the component, which can be used by a child to
  3315. * add its own widgets. Not all components do have a container for childs, in
  3316. * that case null is returned.
  3317. * @returns {HTMLElement | null} container
  3318. */
  3319. Component.prototype.getContainer = function getContainer() {
  3320. // should be implemented by the component
  3321. return null;
  3322. };
  3323. /**
  3324. * Get the frame element of the component, the outer HTML DOM element.
  3325. * @returns {HTMLElement | null} frame
  3326. */
  3327. Component.prototype.getFrame = function getFrame() {
  3328. return this.frame;
  3329. };
  3330. /**
  3331. * Repaint the component
  3332. * @return {Boolean} changed
  3333. */
  3334. Component.prototype.repaint = function repaint() {
  3335. // should be implemented by the component
  3336. return false;
  3337. };
  3338. /**
  3339. * Reflow the component
  3340. * @return {Boolean} resized
  3341. */
  3342. Component.prototype.reflow = function reflow() {
  3343. // should be implemented by the component
  3344. return false;
  3345. };
  3346. /**
  3347. * Hide the component from the DOM
  3348. * @return {Boolean} changed
  3349. */
  3350. Component.prototype.hide = function hide() {
  3351. if (this.frame && this.frame.parentNode) {
  3352. this.frame.parentNode.removeChild(this.frame);
  3353. return true;
  3354. }
  3355. else {
  3356. return false;
  3357. }
  3358. };
  3359. /**
  3360. * Show the component in the DOM (when not already visible).
  3361. * A repaint will be executed when the component is not visible
  3362. * @return {Boolean} changed
  3363. */
  3364. Component.prototype.show = function show() {
  3365. if (!this.frame || !this.frame.parentNode) {
  3366. return this.repaint();
  3367. }
  3368. else {
  3369. return false;
  3370. }
  3371. };
  3372. /**
  3373. * Request a repaint. The controller will schedule a repaint
  3374. */
  3375. Component.prototype.requestRepaint = function requestRepaint() {
  3376. if (this.controller) {
  3377. this.controller.requestRepaint();
  3378. }
  3379. else {
  3380. throw new Error('Cannot request a repaint: no controller configured');
  3381. // TODO: just do a repaint when no parent is configured?
  3382. }
  3383. };
  3384. /**
  3385. * Request a reflow. The controller will schedule a reflow
  3386. */
  3387. Component.prototype.requestReflow = function requestReflow() {
  3388. if (this.controller) {
  3389. this.controller.requestReflow();
  3390. }
  3391. else {
  3392. throw new Error('Cannot request a reflow: no controller configured');
  3393. // TODO: just do a reflow when no parent is configured?
  3394. }
  3395. };
  3396. /**
  3397. * A panel can contain components
  3398. * @param {Component} [parent]
  3399. * @param {Component[]} [depends] Components on which this components depends
  3400. * (except for the parent)
  3401. * @param {Object} [options] Available parameters:
  3402. * {String | Number | function} [left]
  3403. * {String | Number | function} [top]
  3404. * {String | Number | function} [width]
  3405. * {String | Number | function} [height]
  3406. * {String | function} [className]
  3407. * @constructor Panel
  3408. * @extends Component
  3409. */
  3410. function Panel(parent, depends, options) {
  3411. this.id = util.randomUUID();
  3412. this.parent = parent;
  3413. this.depends = depends;
  3414. this.options = options || {};
  3415. }
  3416. Panel.prototype = new Component();
  3417. /**
  3418. * Set options. Will extend the current options.
  3419. * @param {Object} [options] Available parameters:
  3420. * {String | function} [className]
  3421. * {String | Number | function} [left]
  3422. * {String | Number | function} [top]
  3423. * {String | Number | function} [width]
  3424. * {String | Number | function} [height]
  3425. */
  3426. Panel.prototype.setOptions = Component.prototype.setOptions;
  3427. /**
  3428. * Get the container element of the panel, which can be used by a child to
  3429. * add its own widgets.
  3430. * @returns {HTMLElement} container
  3431. */
  3432. Panel.prototype.getContainer = function () {
  3433. return this.frame;
  3434. };
  3435. /**
  3436. * Repaint the component
  3437. * @return {Boolean} changed
  3438. */
  3439. Panel.prototype.repaint = function () {
  3440. var changed = 0,
  3441. update = util.updateProperty,
  3442. asSize = util.option.asSize,
  3443. options = this.options,
  3444. frame = this.frame;
  3445. if (!frame) {
  3446. frame = document.createElement('div');
  3447. frame.className = 'panel';
  3448. var className = options.className;
  3449. if (className) {
  3450. if (typeof className == 'function') {
  3451. util.addClassName(frame, String(className()));
  3452. }
  3453. else {
  3454. util.addClassName(frame, String(className));
  3455. }
  3456. }
  3457. this.frame = frame;
  3458. changed += 1;
  3459. }
  3460. if (!frame.parentNode) {
  3461. if (!this.parent) {
  3462. throw new Error('Cannot repaint panel: no parent attached');
  3463. }
  3464. var parentContainer = this.parent.getContainer();
  3465. if (!parentContainer) {
  3466. throw new Error('Cannot repaint panel: parent has no container element');
  3467. }
  3468. parentContainer.appendChild(frame);
  3469. changed += 1;
  3470. }
  3471. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3472. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3473. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3474. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3475. return (changed > 0);
  3476. };
  3477. /**
  3478. * Reflow the component
  3479. * @return {Boolean} resized
  3480. */
  3481. Panel.prototype.reflow = function () {
  3482. var changed = 0,
  3483. update = util.updateProperty,
  3484. frame = this.frame;
  3485. if (frame) {
  3486. changed += update(this, 'top', frame.offsetTop);
  3487. changed += update(this, 'left', frame.offsetLeft);
  3488. changed += update(this, 'width', frame.offsetWidth);
  3489. changed += update(this, 'height', frame.offsetHeight);
  3490. }
  3491. else {
  3492. changed += 1;
  3493. }
  3494. return (changed > 0);
  3495. };
  3496. /**
  3497. * A root panel can hold components. The root panel must be initialized with
  3498. * a DOM element as container.
  3499. * @param {HTMLElement} container
  3500. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  3501. * @constructor RootPanel
  3502. * @extends Panel
  3503. */
  3504. function RootPanel(container, options) {
  3505. this.id = util.randomUUID();
  3506. this.container = container;
  3507. this.options = options || {};
  3508. this.defaultOptions = {
  3509. autoResize: true
  3510. };
  3511. this.listeners = {}; // event listeners
  3512. }
  3513. RootPanel.prototype = new Panel();
  3514. /**
  3515. * Set options. Will extend the current options.
  3516. * @param {Object} [options] Available parameters:
  3517. * {String | function} [className]
  3518. * {String | Number | function} [left]
  3519. * {String | Number | function} [top]
  3520. * {String | Number | function} [width]
  3521. * {String | Number | function} [height]
  3522. * {Boolean | function} [autoResize]
  3523. */
  3524. RootPanel.prototype.setOptions = Component.prototype.setOptions;
  3525. /**
  3526. * Repaint the component
  3527. * @return {Boolean} changed
  3528. */
  3529. RootPanel.prototype.repaint = function () {
  3530. var changed = 0,
  3531. update = util.updateProperty,
  3532. asSize = util.option.asSize,
  3533. options = this.options,
  3534. frame = this.frame;
  3535. if (!frame) {
  3536. frame = document.createElement('div');
  3537. frame.className = 'graph panel';
  3538. var className = options.className;
  3539. if (className) {
  3540. util.addClassName(frame, util.option.asString(className));
  3541. }
  3542. this.frame = frame;
  3543. changed += 1;
  3544. }
  3545. if (!frame.parentNode) {
  3546. if (!this.container) {
  3547. throw new Error('Cannot repaint root panel: no container attached');
  3548. }
  3549. this.container.appendChild(frame);
  3550. changed += 1;
  3551. }
  3552. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3553. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3554. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3555. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3556. this._updateEventEmitters();
  3557. this._updateWatch();
  3558. return (changed > 0);
  3559. };
  3560. /**
  3561. * Reflow the component
  3562. * @return {Boolean} resized
  3563. */
  3564. RootPanel.prototype.reflow = function () {
  3565. var changed = 0,
  3566. update = util.updateProperty,
  3567. frame = this.frame;
  3568. if (frame) {
  3569. changed += update(this, 'top', frame.offsetTop);
  3570. changed += update(this, 'left', frame.offsetLeft);
  3571. changed += update(this, 'width', frame.offsetWidth);
  3572. changed += update(this, 'height', frame.offsetHeight);
  3573. }
  3574. else {
  3575. changed += 1;
  3576. }
  3577. return (changed > 0);
  3578. };
  3579. /**
  3580. * Update watching for resize, depending on the current option
  3581. * @private
  3582. */
  3583. RootPanel.prototype._updateWatch = function () {
  3584. var autoResize = this.getOption('autoResize');
  3585. if (autoResize) {
  3586. this._watch();
  3587. }
  3588. else {
  3589. this._unwatch();
  3590. }
  3591. };
  3592. /**
  3593. * Watch for changes in the size of the frame. On resize, the Panel will
  3594. * automatically redraw itself.
  3595. * @private
  3596. */
  3597. RootPanel.prototype._watch = function () {
  3598. var me = this;
  3599. this._unwatch();
  3600. var checkSize = function () {
  3601. var autoResize = me.getOption('autoResize');
  3602. if (!autoResize) {
  3603. // stop watching when the option autoResize is changed to false
  3604. me._unwatch();
  3605. return;
  3606. }
  3607. if (me.frame) {
  3608. // check whether the frame is resized
  3609. if ((me.frame.clientWidth != me.width) ||
  3610. (me.frame.clientHeight != me.height)) {
  3611. me.requestReflow();
  3612. }
  3613. }
  3614. };
  3615. // TODO: automatically cleanup the event listener when the frame is deleted
  3616. util.addEventListener(window, 'resize', checkSize);
  3617. this.watchTimer = setInterval(checkSize, 1000);
  3618. };
  3619. /**
  3620. * Stop watching for a resize of the frame.
  3621. * @private
  3622. */
  3623. RootPanel.prototype._unwatch = function () {
  3624. if (this.watchTimer) {
  3625. clearInterval(this.watchTimer);
  3626. this.watchTimer = undefined;
  3627. }
  3628. // TODO: remove event listener on window.resize
  3629. };
  3630. /**
  3631. * Event handler
  3632. * @param {String} event name of the event, for example 'click', 'mousemove'
  3633. * @param {function} callback callback handler, invoked with the raw HTML Event
  3634. * as parameter.
  3635. */
  3636. RootPanel.prototype.on = function (event, callback) {
  3637. // register the listener at this component
  3638. var arr = this.listeners[event];
  3639. if (!arr) {
  3640. arr = [];
  3641. this.listeners[event] = arr;
  3642. }
  3643. arr.push(callback);
  3644. this._updateEventEmitters();
  3645. };
  3646. /**
  3647. * Update the event listeners for all event emitters
  3648. * @private
  3649. */
  3650. RootPanel.prototype._updateEventEmitters = function () {
  3651. if (this.listeners) {
  3652. var me = this;
  3653. util.forEach(this.listeners, function (listeners, event) {
  3654. if (!me.emitters) {
  3655. me.emitters = {};
  3656. }
  3657. if (!(event in me.emitters)) {
  3658. // create event
  3659. var frame = me.frame;
  3660. if (frame) {
  3661. //console.log('Created a listener for event ' + event + ' on component ' + me.id); // TODO: cleanup logging
  3662. var callback = function(event) {
  3663. listeners.forEach(function (listener) {
  3664. // TODO: filter on event target!
  3665. listener(event);
  3666. });
  3667. };
  3668. me.emitters[event] = callback;
  3669. util.addEventListener(frame, event, callback);
  3670. }
  3671. }
  3672. });
  3673. // TODO: be able to delete event listeners
  3674. // TODO: be able to move event listeners to a parent when available
  3675. }
  3676. };
  3677. /**
  3678. * A horizontal time axis
  3679. * @param {Component} parent
  3680. * @param {Component[]} [depends] Components on which this components depends
  3681. * (except for the parent)
  3682. * @param {Object} [options] See TimeAxis.setOptions for the available
  3683. * options.
  3684. * @constructor TimeAxis
  3685. * @extends Component
  3686. */
  3687. function TimeAxis (parent, depends, options) {
  3688. this.id = util.randomUUID();
  3689. this.parent = parent;
  3690. this.depends = depends;
  3691. this.dom = {
  3692. majorLines: [],
  3693. majorTexts: [],
  3694. minorLines: [],
  3695. minorTexts: [],
  3696. redundant: {
  3697. majorLines: [],
  3698. majorTexts: [],
  3699. minorLines: [],
  3700. minorTexts: []
  3701. }
  3702. };
  3703. this.props = {
  3704. range: {
  3705. start: 0,
  3706. end: 0,
  3707. minimumStep: 0
  3708. },
  3709. lineTop: 0
  3710. };
  3711. this.options = options || {};
  3712. this.defaultOptions = {
  3713. orientation: 'bottom', // supported: 'top', 'bottom'
  3714. // TODO: implement timeaxis orientations 'left' and 'right'
  3715. showMinorLabels: true,
  3716. showMajorLabels: true
  3717. };
  3718. this.conversion = null;
  3719. this.range = null;
  3720. }
  3721. TimeAxis.prototype = new Component();
  3722. // TODO: comment options
  3723. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  3724. /**
  3725. * Set a range (start and end)
  3726. * @param {Range | Object} range A Range or an object containing start and end.
  3727. */
  3728. TimeAxis.prototype.setRange = function (range) {
  3729. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  3730. throw new TypeError('Range must be an instance of Range, ' +
  3731. 'or an object containing start and end.');
  3732. }
  3733. this.range = range;
  3734. };
  3735. /**
  3736. * Convert a position on screen (pixels) to a datetime
  3737. * @param {int} x Position on the screen in pixels
  3738. * @return {Date} time The datetime the corresponds with given position x
  3739. */
  3740. TimeAxis.prototype.toTime = function(x) {
  3741. var conversion = this.conversion;
  3742. return new Date(x / conversion.factor + conversion.offset);
  3743. };
  3744. /**
  3745. * Convert a datetime (Date object) into a position on the screen
  3746. * @param {Date} time A date
  3747. * @return {int} x The position on the screen in pixels which corresponds
  3748. * with the given date.
  3749. * @private
  3750. */
  3751. TimeAxis.prototype.toScreen = function(time) {
  3752. var conversion = this.conversion;
  3753. return (time.valueOf() - conversion.offset) * conversion.factor;
  3754. };
  3755. /**
  3756. * Repaint the component
  3757. * @return {Boolean} changed
  3758. */
  3759. TimeAxis.prototype.repaint = function () {
  3760. var changed = 0,
  3761. update = util.updateProperty,
  3762. asSize = util.option.asSize,
  3763. options = this.options,
  3764. orientation = this.getOption('orientation'),
  3765. props = this.props,
  3766. step = this.step;
  3767. var frame = this.frame;
  3768. if (!frame) {
  3769. frame = document.createElement('div');
  3770. this.frame = frame;
  3771. changed += 1;
  3772. }
  3773. frame.className = 'axis ' + orientation;
  3774. // TODO: custom className?
  3775. if (!frame.parentNode) {
  3776. if (!this.parent) {
  3777. throw new Error('Cannot repaint time axis: no parent attached');
  3778. }
  3779. var parentContainer = this.parent.getContainer();
  3780. if (!parentContainer) {
  3781. throw new Error('Cannot repaint time axis: parent has no container element');
  3782. }
  3783. parentContainer.appendChild(frame);
  3784. changed += 1;
  3785. }
  3786. var parent = frame.parentNode;
  3787. if (parent) {
  3788. var beforeChild = frame.nextSibling;
  3789. parent.removeChild(frame); // take frame offline while updating (is almost twice as fast)
  3790. var defaultTop = (orientation == 'bottom' && this.props.parentHeight && this.height) ?
  3791. (this.props.parentHeight - this.height) + 'px' :
  3792. '0px';
  3793. changed += update(frame.style, 'top', asSize(options.top, defaultTop));
  3794. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3795. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3796. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  3797. // get characters width and height
  3798. this._repaintMeasureChars();
  3799. if (this.step) {
  3800. this._repaintStart();
  3801. step.first();
  3802. var xFirstMajorLabel = undefined;
  3803. var max = 0;
  3804. while (step.hasNext() && max < 1000) {
  3805. max++;
  3806. var cur = step.getCurrent(),
  3807. x = this.toScreen(cur),
  3808. isMajor = step.isMajor();
  3809. // TODO: lines must have a width, such that we can create css backgrounds
  3810. if (this.getOption('showMinorLabels')) {
  3811. this._repaintMinorText(x, step.getLabelMinor());
  3812. }
  3813. if (isMajor && this.getOption('showMajorLabels')) {
  3814. if (x > 0) {
  3815. if (xFirstMajorLabel == undefined) {
  3816. xFirstMajorLabel = x;
  3817. }
  3818. this._repaintMajorText(x, step.getLabelMajor());
  3819. }
  3820. this._repaintMajorLine(x);
  3821. }
  3822. else {
  3823. this._repaintMinorLine(x);
  3824. }
  3825. step.next();
  3826. }
  3827. // create a major label on the left when needed
  3828. if (this.getOption('showMajorLabels')) {
  3829. var leftTime = this.toTime(0),
  3830. leftText = step.getLabelMajor(leftTime),
  3831. widthText = leftText.length * (props.majorCharWidth || 10) + 10; // upper bound estimation
  3832. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3833. this._repaintMajorText(0, leftText);
  3834. }
  3835. }
  3836. this._repaintEnd();
  3837. }
  3838. this._repaintLine();
  3839. // put frame online again
  3840. if (beforeChild) {
  3841. parent.insertBefore(frame, beforeChild);
  3842. }
  3843. else {
  3844. parent.appendChild(frame)
  3845. }
  3846. }
  3847. return (changed > 0);
  3848. };
  3849. /**
  3850. * Start a repaint. Move all DOM elements to a redundant list, where they
  3851. * can be picked for re-use, or can be cleaned up in the end
  3852. * @private
  3853. */
  3854. TimeAxis.prototype._repaintStart = function () {
  3855. var dom = this.dom,
  3856. redundant = dom.redundant;
  3857. redundant.majorLines = dom.majorLines;
  3858. redundant.majorTexts = dom.majorTexts;
  3859. redundant.minorLines = dom.minorLines;
  3860. redundant.minorTexts = dom.minorTexts;
  3861. dom.majorLines = [];
  3862. dom.majorTexts = [];
  3863. dom.minorLines = [];
  3864. dom.minorTexts = [];
  3865. };
  3866. /**
  3867. * End a repaint. Cleanup leftover DOM elements in the redundant list
  3868. * @private
  3869. */
  3870. TimeAxis.prototype._repaintEnd = function () {
  3871. util.forEach(this.dom.redundant, function (arr) {
  3872. while (arr.length) {
  3873. var elem = arr.pop();
  3874. if (elem && elem.parentNode) {
  3875. elem.parentNode.removeChild(elem);
  3876. }
  3877. }
  3878. });
  3879. };
  3880. /**
  3881. * Create a minor label for the axis at position x
  3882. * @param {Number} x
  3883. * @param {String} text
  3884. * @private
  3885. */
  3886. TimeAxis.prototype._repaintMinorText = function (x, text) {
  3887. // reuse redundant label
  3888. var label = this.dom.redundant.minorTexts.shift();
  3889. if (!label) {
  3890. // create new label
  3891. var content = document.createTextNode('');
  3892. label = document.createElement('div');
  3893. label.appendChild(content);
  3894. label.className = 'text minor';
  3895. this.frame.appendChild(label);
  3896. }
  3897. this.dom.minorTexts.push(label);
  3898. label.childNodes[0].nodeValue = text;
  3899. label.style.left = x + 'px';
  3900. label.style.top = this.props.minorLabelTop + 'px';
  3901. //label.title = title; // TODO: this is a heavy operation
  3902. };
  3903. /**
  3904. * Create a Major label for the axis at position x
  3905. * @param {Number} x
  3906. * @param {String} text
  3907. * @private
  3908. */
  3909. TimeAxis.prototype._repaintMajorText = function (x, text) {
  3910. // reuse redundant label
  3911. var label = this.dom.redundant.majorTexts.shift();
  3912. if (!label) {
  3913. // create label
  3914. var content = document.createTextNode(text);
  3915. label = document.createElement('div');
  3916. label.className = 'text major';
  3917. label.appendChild(content);
  3918. this.frame.appendChild(label);
  3919. }
  3920. this.dom.majorTexts.push(label);
  3921. label.childNodes[0].nodeValue = text;
  3922. label.style.top = this.props.majorLabelTop + 'px';
  3923. label.style.left = x + 'px';
  3924. //label.title = title; // TODO: this is a heavy operation
  3925. };
  3926. /**
  3927. * Create a minor line for the axis at position x
  3928. * @param {Number} x
  3929. * @private
  3930. */
  3931. TimeAxis.prototype._repaintMinorLine = function (x) {
  3932. // reuse redundant line
  3933. var line = this.dom.redundant.minorLines.shift();
  3934. if (!line) {
  3935. // create vertical line
  3936. line = document.createElement('div');
  3937. line.className = 'grid vertical minor';
  3938. this.frame.appendChild(line);
  3939. }
  3940. this.dom.minorLines.push(line);
  3941. var props = this.props;
  3942. line.style.top = props.minorLineTop + 'px';
  3943. line.style.height = props.minorLineHeight + 'px';
  3944. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  3945. };
  3946. /**
  3947. * Create a Major line for the axis at position x
  3948. * @param {Number} x
  3949. * @private
  3950. */
  3951. TimeAxis.prototype._repaintMajorLine = function (x) {
  3952. // reuse redundant line
  3953. var line = this.dom.redundant.majorLines.shift();
  3954. if (!line) {
  3955. // create vertical line
  3956. line = document.createElement('DIV');
  3957. line.className = 'grid vertical major';
  3958. this.frame.appendChild(line);
  3959. }
  3960. this.dom.majorLines.push(line);
  3961. var props = this.props;
  3962. line.style.top = props.majorLineTop + 'px';
  3963. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  3964. line.style.height = props.majorLineHeight + 'px';
  3965. };
  3966. /**
  3967. * Repaint the horizontal line for the axis
  3968. * @private
  3969. */
  3970. TimeAxis.prototype._repaintLine = function() {
  3971. var line = this.dom.line,
  3972. frame = this.frame,
  3973. options = this.options;
  3974. // line before all axis elements
  3975. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  3976. if (line) {
  3977. // put this line at the end of all childs
  3978. frame.removeChild(line);
  3979. frame.appendChild(line);
  3980. }
  3981. else {
  3982. // create the axis line
  3983. line = document.createElement('div');
  3984. line.className = 'grid horizontal major';
  3985. frame.appendChild(line);
  3986. this.dom.line = line;
  3987. }
  3988. line.style.top = this.props.lineTop + 'px';
  3989. }
  3990. else {
  3991. if (line && axis.parentElement) {
  3992. frame.removeChild(axis.line);
  3993. delete this.dom.line;
  3994. }
  3995. }
  3996. };
  3997. /**
  3998. * Create characters used to determine the size of text on the axis
  3999. * @private
  4000. */
  4001. TimeAxis.prototype._repaintMeasureChars = function () {
  4002. // calculate the width and height of a single character
  4003. // this is used to calculate the step size, and also the positioning of the
  4004. // axis
  4005. var dom = this.dom,
  4006. text;
  4007. if (!dom.measureCharMinor) {
  4008. text = document.createTextNode('0');
  4009. var measureCharMinor = document.createElement('DIV');
  4010. measureCharMinor.className = 'text minor measure';
  4011. measureCharMinor.appendChild(text);
  4012. this.frame.appendChild(measureCharMinor);
  4013. dom.measureCharMinor = measureCharMinor;
  4014. }
  4015. if (!dom.measureCharMajor) {
  4016. text = document.createTextNode('0');
  4017. var measureCharMajor = document.createElement('DIV');
  4018. measureCharMajor.className = 'text major measure';
  4019. measureCharMajor.appendChild(text);
  4020. this.frame.appendChild(measureCharMajor);
  4021. dom.measureCharMajor = measureCharMajor;
  4022. }
  4023. };
  4024. /**
  4025. * Reflow the component
  4026. * @return {Boolean} resized
  4027. */
  4028. TimeAxis.prototype.reflow = function () {
  4029. var changed = 0,
  4030. update = util.updateProperty,
  4031. frame = this.frame,
  4032. range = this.range;
  4033. if (!range) {
  4034. throw new Error('Cannot repaint time axis: no range configured');
  4035. }
  4036. if (frame) {
  4037. changed += update(this, 'top', frame.offsetTop);
  4038. changed += update(this, 'left', frame.offsetLeft);
  4039. // calculate size of a character
  4040. var props = this.props,
  4041. showMinorLabels = this.getOption('showMinorLabels'),
  4042. showMajorLabels = this.getOption('showMajorLabels'),
  4043. measureCharMinor = this.dom.measureCharMinor,
  4044. measureCharMajor = this.dom.measureCharMajor;
  4045. if (measureCharMinor) {
  4046. props.minorCharHeight = measureCharMinor.clientHeight;
  4047. props.minorCharWidth = measureCharMinor.clientWidth;
  4048. }
  4049. if (measureCharMajor) {
  4050. props.majorCharHeight = measureCharMajor.clientHeight;
  4051. props.majorCharWidth = measureCharMajor.clientWidth;
  4052. }
  4053. var parentHeight = frame.parentNode ? frame.parentNode.offsetHeight : 0;
  4054. if (parentHeight != props.parentHeight) {
  4055. props.parentHeight = parentHeight;
  4056. changed += 1;
  4057. }
  4058. switch (this.getOption('orientation')) {
  4059. case 'bottom':
  4060. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4061. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4062. props.minorLabelTop = 0;
  4063. props.majorLabelTop = props.minorLabelTop + props.minorLabelHeight;
  4064. props.minorLineTop = -this.top;
  4065. props.minorLineHeight = Math.max(this.top + props.majorLabelHeight, 0);
  4066. props.minorLineWidth = 1; // TODO: really calculate width
  4067. props.majorLineTop = -this.top;
  4068. props.majorLineHeight = Math.max(this.top + props.minorLabelHeight + props.majorLabelHeight, 0);
  4069. props.majorLineWidth = 1; // TODO: really calculate width
  4070. props.lineTop = 0;
  4071. break;
  4072. case 'top':
  4073. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4074. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4075. props.majorLabelTop = 0;
  4076. props.minorLabelTop = props.majorLabelTop + props.majorLabelHeight;
  4077. props.minorLineTop = props.minorLabelTop;
  4078. props.minorLineHeight = Math.max(parentHeight - props.majorLabelHeight - this.top);
  4079. props.minorLineWidth = 1; // TODO: really calculate width
  4080. props.majorLineTop = 0;
  4081. props.majorLineHeight = Math.max(parentHeight - this.top);
  4082. props.majorLineWidth = 1; // TODO: really calculate width
  4083. props.lineTop = props.majorLabelHeight + props.minorLabelHeight;
  4084. break;
  4085. default:
  4086. throw new Error('Unkown orientation "' + this.getOption('orientation') + '"');
  4087. }
  4088. var height = props.minorLabelHeight + props.majorLabelHeight;
  4089. changed += update(this, 'width', frame.offsetWidth);
  4090. changed += update(this, 'height', height);
  4091. // calculate range and step
  4092. this._updateConversion();
  4093. var start = util.cast(range.start, 'Date'),
  4094. end = util.cast(range.end, 'Date'),
  4095. minimumStep = this.toTime((props.minorCharWidth || 10) * 5) - this.toTime(0);
  4096. this.step = new TimeStep(start, end, minimumStep);
  4097. changed += update(props.range, 'start', start.valueOf());
  4098. changed += update(props.range, 'end', end.valueOf());
  4099. changed += update(props.range, 'minimumStep', minimumStep.valueOf());
  4100. }
  4101. return (changed > 0);
  4102. };
  4103. /**
  4104. * Calculate the factor and offset to convert a position on screen to the
  4105. * corresponding date and vice versa.
  4106. * After the method _updateConversion is executed once, the methods toTime
  4107. * and toScreen can be used.
  4108. * @private
  4109. */
  4110. TimeAxis.prototype._updateConversion = function() {
  4111. var range = this.range;
  4112. if (!range) {
  4113. throw new Error('No range configured');
  4114. }
  4115. if (range.conversion) {
  4116. this.conversion = range.conversion(this.width);
  4117. }
  4118. else {
  4119. this.conversion = Range.conversion(range.start, range.end, this.width);
  4120. }
  4121. };
  4122. /**
  4123. * An ItemSet holds a set of items and ranges which can be displayed in a
  4124. * range. The width is determined by the parent of the ItemSet, and the height
  4125. * is determined by the size of the items.
  4126. * @param {Component} parent
  4127. * @param {Component[]} [depends] Components on which this components depends
  4128. * (except for the parent)
  4129. * @param {Object} [options] See ItemSet.setOptions for the available
  4130. * options.
  4131. * @constructor ItemSet
  4132. * @extends Panel
  4133. */
  4134. // TODO: improve performance by replacing all Array.forEach with a for loop
  4135. function ItemSet(parent, depends, options) {
  4136. this.id = util.randomUUID();
  4137. this.parent = parent;
  4138. this.depends = depends;
  4139. // one options object is shared by this itemset and all its items
  4140. this.options = options || {};
  4141. this.defaultOptions = {
  4142. type: 'box',
  4143. align: 'center',
  4144. orientation: 'bottom',
  4145. margin: {
  4146. axis: 20,
  4147. item: 10
  4148. },
  4149. padding: 5
  4150. };
  4151. this.dom = {};
  4152. var me = this;
  4153. this.itemsData = null; // DataSet
  4154. this.range = null; // Range or Object {start: number, end: number}
  4155. this.listeners = {
  4156. 'add': function (event, params, senderId) {
  4157. if (senderId != me.id) {
  4158. me._onAdd(params.items);
  4159. }
  4160. },
  4161. 'update': function (event, params, senderId) {
  4162. if (senderId != me.id) {
  4163. me._onUpdate(params.items);
  4164. }
  4165. },
  4166. 'remove': function (event, params, senderId) {
  4167. if (senderId != me.id) {
  4168. me._onRemove(params.items);
  4169. }
  4170. }
  4171. };
  4172. this.items = {}; // object with an Item for every data item
  4173. this.queue = {}; // queue with id/actions: 'add', 'update', 'delete'
  4174. this.stack = new Stack(this, Object.create(this.options));
  4175. this.conversion = null;
  4176. // TODO: ItemSet should also attach event listeners for rangechange and rangechanged, like timeaxis
  4177. }
  4178. ItemSet.prototype = new Panel();
  4179. // available item types will be registered here
  4180. ItemSet.types = {
  4181. box: ItemBox,
  4182. range: ItemRange,
  4183. point: ItemPoint
  4184. };
  4185. /**
  4186. * Set options for the ItemSet. Existing options will be extended/overwritten.
  4187. * @param {Object} [options] The following options are available:
  4188. * {String | function} [className]
  4189. * class name for the itemset
  4190. * {String} [type]
  4191. * Default type for the items. Choose from 'box'
  4192. * (default), 'point', or 'range'. The default
  4193. * Style can be overwritten by individual items.
  4194. * {String} align
  4195. * Alignment for the items, only applicable for
  4196. * ItemBox. Choose 'center' (default), 'left', or
  4197. * 'right'.
  4198. * {String} orientation
  4199. * Orientation of the item set. Choose 'top' or
  4200. * 'bottom' (default).
  4201. * {Number} margin.axis
  4202. * Margin between the axis and the items in pixels.
  4203. * Default is 20.
  4204. * {Number} margin.item
  4205. * Margin between items in pixels. Default is 10.
  4206. * {Number} padding
  4207. * Padding of the contents of an item in pixels.
  4208. * Must correspond with the items css. Default is 5.
  4209. */
  4210. ItemSet.prototype.setOptions = Component.prototype.setOptions;
  4211. /**
  4212. * Set range (start and end).
  4213. * @param {Range | Object} range A Range or an object containing start and end.
  4214. */
  4215. ItemSet.prototype.setRange = function setRange(range) {
  4216. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4217. throw new TypeError('Range must be an instance of Range, ' +
  4218. 'or an object containing start and end.');
  4219. }
  4220. this.range = range;
  4221. };
  4222. /**
  4223. * Repaint the component
  4224. * @return {Boolean} changed
  4225. */
  4226. ItemSet.prototype.repaint = function repaint() {
  4227. var changed = 0,
  4228. update = util.updateProperty,
  4229. asSize = util.option.asSize,
  4230. options = this.options,
  4231. orientation = this.getOption('orientation'),
  4232. defaultOptions = this.defaultOptions,
  4233. frame = this.frame;
  4234. if (!frame) {
  4235. frame = document.createElement('div');
  4236. frame.className = 'itemset';
  4237. var className = options.className;
  4238. if (className) {
  4239. util.addClassName(frame, util.option.asString(className));
  4240. }
  4241. // create background panel
  4242. var background = document.createElement('div');
  4243. background.className = 'background';
  4244. frame.appendChild(background);
  4245. this.dom.background = background;
  4246. // create foreground panel
  4247. var foreground = document.createElement('div');
  4248. foreground.className = 'foreground';
  4249. frame.appendChild(foreground);
  4250. this.dom.foreground = foreground;
  4251. // create axis panel
  4252. var axis = document.createElement('div');
  4253. axis.className = 'itemset-axis';
  4254. //frame.appendChild(axis);
  4255. this.dom.axis = axis;
  4256. this.frame = frame;
  4257. changed += 1;
  4258. }
  4259. if (!this.parent) {
  4260. throw new Error('Cannot repaint itemset: no parent attached');
  4261. }
  4262. var parentContainer = this.parent.getContainer();
  4263. if (!parentContainer) {
  4264. throw new Error('Cannot repaint itemset: parent has no container element');
  4265. }
  4266. if (!frame.parentNode) {
  4267. parentContainer.appendChild(frame);
  4268. changed += 1;
  4269. }
  4270. if (!this.dom.axis.parentNode) {
  4271. parentContainer.appendChild(this.dom.axis);
  4272. changed += 1;
  4273. }
  4274. // reposition frame
  4275. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  4276. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  4277. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  4278. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  4279. // reposition axis
  4280. changed += update(this.dom.axis.style, 'left', asSize(options.left, '0px'));
  4281. changed += update(this.dom.axis.style, 'width', asSize(options.width, '100%'));
  4282. if (orientation == 'bottom') {
  4283. changed += update(this.dom.axis.style, 'top', (this.height + this.top) + 'px');
  4284. }
  4285. else { // orientation == 'top'
  4286. changed += update(this.dom.axis.style, 'top', this.top + 'px');
  4287. }
  4288. this._updateConversion();
  4289. var me = this,
  4290. queue = this.queue,
  4291. itemsData = this.itemsData,
  4292. items = this.items,
  4293. dataOptions = {
  4294. fields: [(itemsData && itemsData.fieldId || 'id'), 'start', 'end', 'content', 'type']
  4295. };
  4296. // TODO: copy options from the itemset itself?
  4297. // show/hide added/changed/removed items
  4298. Object.keys(queue).forEach(function (id) {
  4299. //var entry = queue[id];
  4300. var action = queue[id];
  4301. var item = items[id];
  4302. //var item = entry.item;
  4303. //noinspection FallthroughInSwitchStatementJS
  4304. switch (action) {
  4305. case 'add':
  4306. case 'update':
  4307. var itemData = itemsData && itemsData.get(id, dataOptions);
  4308. if (itemData) {
  4309. var type = itemData.type ||
  4310. (itemData.start && itemData.end && 'range') ||
  4311. options.type ||
  4312. 'box';
  4313. var constructor = ItemSet.types[type];
  4314. // TODO: how to handle items with invalid data? hide them and give a warning? or throw an error?
  4315. if (item) {
  4316. // update item
  4317. if (!constructor || !(item instanceof constructor)) {
  4318. // item type has changed, hide and delete the item
  4319. changed += item.hide();
  4320. item = null;
  4321. }
  4322. else {
  4323. item.data = itemData; // TODO: create a method item.setData ?
  4324. changed++;
  4325. }
  4326. }
  4327. if (!item) {
  4328. // create item
  4329. if (constructor) {
  4330. item = new constructor(me, itemData, options, defaultOptions);
  4331. changed++;
  4332. }
  4333. else {
  4334. throw new TypeError('Unknown item type "' + type + '"');
  4335. }
  4336. }
  4337. // force a repaint (not only a reposition)
  4338. item.repaint();
  4339. items[id] = item;
  4340. }
  4341. // update queue
  4342. delete queue[id];
  4343. break;
  4344. case 'remove':
  4345. if (item) {
  4346. // remove DOM of the item
  4347. changed += item.hide();
  4348. }
  4349. // update lists
  4350. delete items[id];
  4351. delete queue[id];
  4352. break;
  4353. default:
  4354. console.log('Error: unknown action "' + action + '"');
  4355. }
  4356. });
  4357. // reposition all items. Show items only when in the visible area
  4358. util.forEach(this.items, function (item) {
  4359. if (item.visible) {
  4360. changed += item.show();
  4361. item.reposition();
  4362. }
  4363. else {
  4364. changed += item.hide();
  4365. }
  4366. });
  4367. return (changed > 0);
  4368. };
  4369. /**
  4370. * Get the foreground container element
  4371. * @return {HTMLElement} foreground
  4372. */
  4373. ItemSet.prototype.getForeground = function getForeground() {
  4374. return this.dom.foreground;
  4375. };
  4376. /**
  4377. * Get the background container element
  4378. * @return {HTMLElement} background
  4379. */
  4380. ItemSet.prototype.getBackground = function getBackground() {
  4381. return this.dom.background;
  4382. };
  4383. /**
  4384. * Get the axis container element
  4385. * @return {HTMLElement} axis
  4386. */
  4387. ItemSet.prototype.getAxis = function getAxis() {
  4388. return this.dom.axis;
  4389. };
  4390. /**
  4391. * Reflow the component
  4392. * @return {Boolean} resized
  4393. */
  4394. ItemSet.prototype.reflow = function reflow () {
  4395. var changed = 0,
  4396. options = this.options,
  4397. marginAxis = options.margin && options.margin.axis || this.defaultOptions.margin.axis,
  4398. marginItem = options.margin && options.margin.item || this.defaultOptions.margin.item,
  4399. update = util.updateProperty,
  4400. asNumber = util.option.asNumber,
  4401. asSize = util.option.asSize,
  4402. frame = this.frame;
  4403. if (frame) {
  4404. this._updateConversion();
  4405. util.forEach(this.items, function (item) {
  4406. changed += item.reflow();
  4407. });
  4408. // TODO: stack.update should be triggered via an event, in stack itself
  4409. // TODO: only update the stack when there are changed items
  4410. this.stack.update();
  4411. var maxHeight = asNumber(options.maxHeight);
  4412. var fixedHeight = (asSize(options.height) != null);
  4413. var height;
  4414. if (fixedHeight) {
  4415. height = frame.offsetHeight;
  4416. }
  4417. else {
  4418. // height is not specified, determine the height from the height and positioned items
  4419. var visibleItems = this.stack.ordered; // TODO: not so nice way to get the filtered items
  4420. if (visibleItems.length) {
  4421. var min = visibleItems[0].top;
  4422. var max = visibleItems[0].top + visibleItems[0].height;
  4423. util.forEach(visibleItems, function (item) {
  4424. min = Math.min(min, item.top);
  4425. max = Math.max(max, (item.top + item.height));
  4426. });
  4427. height = (max - min) + marginAxis + marginItem;
  4428. }
  4429. else {
  4430. height = marginAxis + marginItem;
  4431. }
  4432. }
  4433. if (maxHeight != null) {
  4434. height = Math.min(height, maxHeight);
  4435. }
  4436. changed += update(this, 'height', height);
  4437. // calculate height from items
  4438. changed += update(this, 'top', frame.offsetTop);
  4439. changed += update(this, 'left', frame.offsetLeft);
  4440. changed += update(this, 'width', frame.offsetWidth);
  4441. }
  4442. else {
  4443. changed += 1;
  4444. }
  4445. return (changed > 0);
  4446. };
  4447. /**
  4448. * Hide this component from the DOM
  4449. * @return {Boolean} changed
  4450. */
  4451. ItemSet.prototype.hide = function hide() {
  4452. var changed = false;
  4453. // remove the DOM
  4454. if (this.frame && this.frame.parentNode) {
  4455. this.frame.parentNode.removeChild(this.frame);
  4456. changed = true;
  4457. }
  4458. if (this.dom.axis && this.dom.axis.parentNode) {
  4459. this.dom.axis.parentNode.removeChild(this.dom.axis);
  4460. changed = true;
  4461. }
  4462. return changed;
  4463. };
  4464. /**
  4465. * Set items
  4466. * @param {vis.DataSet | null} items
  4467. */
  4468. ItemSet.prototype.setItems = function setItems(items) {
  4469. var me = this,
  4470. ids;
  4471. // unsubscribe from current dataset
  4472. var current = this.itemsData;
  4473. if (current) {
  4474. util.forEach(this.listeners, function (callback, event) {
  4475. current.unsubscribe(event, callback);
  4476. });
  4477. // remove all drawn items
  4478. ids = current.getIds();
  4479. this._onRemove(ids);
  4480. }
  4481. // replace the dataset
  4482. if (!items) {
  4483. this.itemsData = null;
  4484. }
  4485. else if (items instanceof DataSet || items instanceof DataView) {
  4486. this.itemsData = items;
  4487. }
  4488. else {
  4489. throw new TypeError('Data must be an instance of DataSet');
  4490. }
  4491. if (this.itemsData) {
  4492. // subscribe to new dataset
  4493. var id = this.id;
  4494. util.forEach(this.listeners, function (callback, event) {
  4495. me.itemsData.subscribe(event, callback, id);
  4496. });
  4497. // draw all new items
  4498. ids = this.itemsData.getIds();
  4499. this._onAdd(ids);
  4500. }
  4501. };
  4502. /**
  4503. * Get the current items items
  4504. * @returns {vis.DataSet | null}
  4505. */
  4506. ItemSet.prototype.getItems = function getItems() {
  4507. return this.itemsData;
  4508. };
  4509. /**
  4510. * Handle updated items
  4511. * @param {Number[]} ids
  4512. * @private
  4513. */
  4514. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  4515. this._toQueue('update', ids);
  4516. };
  4517. /**
  4518. * Handle changed items
  4519. * @param {Number[]} ids
  4520. * @private
  4521. */
  4522. ItemSet.prototype._onAdd = function _onAdd(ids) {
  4523. this._toQueue('add', ids);
  4524. };
  4525. /**
  4526. * Handle removed items
  4527. * @param {Number[]} ids
  4528. * @private
  4529. */
  4530. ItemSet.prototype._onRemove = function _onRemove(ids) {
  4531. this._toQueue('remove', ids);
  4532. };
  4533. /**
  4534. * Put items in the queue to be added/updated/remove
  4535. * @param {String} action can be 'add', 'update', 'remove'
  4536. * @param {Number[]} ids
  4537. */
  4538. ItemSet.prototype._toQueue = function _toQueue(action, ids) {
  4539. var queue = this.queue;
  4540. ids.forEach(function (id) {
  4541. queue[id] = action;
  4542. });
  4543. if (this.controller) {
  4544. //this.requestReflow();
  4545. this.requestRepaint();
  4546. }
  4547. };
  4548. /**
  4549. * Calculate the factor and offset to convert a position on screen to the
  4550. * corresponding date and vice versa.
  4551. * After the method _updateConversion is executed once, the methods toTime
  4552. * and toScreen can be used.
  4553. * @private
  4554. */
  4555. ItemSet.prototype._updateConversion = function _updateConversion() {
  4556. var range = this.range;
  4557. if (!range) {
  4558. throw new Error('No range configured');
  4559. }
  4560. if (range.conversion) {
  4561. this.conversion = range.conversion(this.width);
  4562. }
  4563. else {
  4564. this.conversion = Range.conversion(range.start, range.end, this.width);
  4565. }
  4566. };
  4567. /**
  4568. * Convert a position on screen (pixels) to a datetime
  4569. * Before this method can be used, the method _updateConversion must be
  4570. * executed once.
  4571. * @param {int} x Position on the screen in pixels
  4572. * @return {Date} time The datetime the corresponds with given position x
  4573. */
  4574. ItemSet.prototype.toTime = function toTime(x) {
  4575. var conversion = this.conversion;
  4576. return new Date(x / conversion.factor + conversion.offset);
  4577. };
  4578. /**
  4579. * Convert a datetime (Date object) into a position on the screen
  4580. * Before this method can be used, the method _updateConversion must be
  4581. * executed once.
  4582. * @param {Date} time A date
  4583. * @return {int} x The position on the screen in pixels which corresponds
  4584. * with the given date.
  4585. */
  4586. ItemSet.prototype.toScreen = function toScreen(time) {
  4587. var conversion = this.conversion;
  4588. return (time.valueOf() - conversion.offset) * conversion.factor;
  4589. };
  4590. /**
  4591. * @constructor Item
  4592. * @param {ItemSet} parent
  4593. * @param {Object} data Object containing (optional) parameters type,
  4594. * start, end, content, group, className.
  4595. * @param {Object} [options] Options to set initial property values
  4596. * @param {Object} [defaultOptions] default options
  4597. * // TODO: describe available options
  4598. */
  4599. function Item (parent, data, options, defaultOptions) {
  4600. this.parent = parent;
  4601. this.data = data;
  4602. this.dom = null;
  4603. this.options = options || {};
  4604. this.defaultOptions = defaultOptions || {};
  4605. this.selected = false;
  4606. this.visible = false;
  4607. this.top = 0;
  4608. this.left = 0;
  4609. this.width = 0;
  4610. this.height = 0;
  4611. }
  4612. /**
  4613. * Select current item
  4614. */
  4615. Item.prototype.select = function select() {
  4616. this.selected = true;
  4617. };
  4618. /**
  4619. * Unselect current item
  4620. */
  4621. Item.prototype.unselect = function unselect() {
  4622. this.selected = false;
  4623. };
  4624. /**
  4625. * Show the Item in the DOM (when not already visible)
  4626. * @return {Boolean} changed
  4627. */
  4628. Item.prototype.show = function show() {
  4629. return false;
  4630. };
  4631. /**
  4632. * Hide the Item from the DOM (when visible)
  4633. * @return {Boolean} changed
  4634. */
  4635. Item.prototype.hide = function hide() {
  4636. return false;
  4637. };
  4638. /**
  4639. * Repaint the item
  4640. * @return {Boolean} changed
  4641. */
  4642. Item.prototype.repaint = function repaint() {
  4643. // should be implemented by the item
  4644. return false;
  4645. };
  4646. /**
  4647. * Reflow the item
  4648. * @return {Boolean} resized
  4649. */
  4650. Item.prototype.reflow = function reflow() {
  4651. // should be implemented by the item
  4652. return false;
  4653. };
  4654. /**
  4655. * @constructor ItemBox
  4656. * @extends Item
  4657. * @param {ItemSet} parent
  4658. * @param {Object} data Object containing parameters start
  4659. * content, className.
  4660. * @param {Object} [options] Options to set initial property values
  4661. * @param {Object} [defaultOptions] default options
  4662. * // TODO: describe available options
  4663. */
  4664. function ItemBox (parent, data, options, defaultOptions) {
  4665. this.props = {
  4666. dot: {
  4667. left: 0,
  4668. top: 0,
  4669. width: 0,
  4670. height: 0
  4671. },
  4672. line: {
  4673. top: 0,
  4674. left: 0,
  4675. width: 0,
  4676. height: 0
  4677. }
  4678. };
  4679. Item.call(this, parent, data, options, defaultOptions);
  4680. }
  4681. ItemBox.prototype = new Item (null, null);
  4682. /**
  4683. * Select the item
  4684. * @override
  4685. */
  4686. ItemBox.prototype.select = function select() {
  4687. this.selected = true;
  4688. // TODO: select and unselect
  4689. };
  4690. /**
  4691. * Unselect the item
  4692. * @override
  4693. */
  4694. ItemBox.prototype.unselect = function unselect() {
  4695. this.selected = false;
  4696. // TODO: select and unselect
  4697. };
  4698. /**
  4699. * Repaint the item
  4700. * @return {Boolean} changed
  4701. */
  4702. ItemBox.prototype.repaint = function repaint() {
  4703. // TODO: make an efficient repaint
  4704. var changed = false;
  4705. var dom = this.dom;
  4706. if (!dom) {
  4707. this._create();
  4708. dom = this.dom;
  4709. changed = true;
  4710. }
  4711. if (dom) {
  4712. if (!this.parent) {
  4713. throw new Error('Cannot repaint item: no parent attached');
  4714. }
  4715. var foreground = this.parent.getForeground();
  4716. if (!foreground) {
  4717. throw new Error('Cannot repaint time axis: ' +
  4718. 'parent has no foreground container element');
  4719. }
  4720. var background = this.parent.getBackground();
  4721. if (!background) {
  4722. throw new Error('Cannot repaint time axis: ' +
  4723. 'parent has no background container element');
  4724. }
  4725. var axis = this.parent.getAxis();
  4726. if (!background) {
  4727. throw new Error('Cannot repaint time axis: ' +
  4728. 'parent has no axis container element');
  4729. }
  4730. if (!dom.box.parentNode) {
  4731. foreground.appendChild(dom.box);
  4732. changed = true;
  4733. }
  4734. if (!dom.line.parentNode) {
  4735. background.appendChild(dom.line);
  4736. changed = true;
  4737. }
  4738. if (!dom.dot.parentNode) {
  4739. axis.appendChild(dom.dot);
  4740. changed = true;
  4741. }
  4742. // update contents
  4743. if (this.data.content != this.content) {
  4744. this.content = this.data.content;
  4745. if (this.content instanceof Element) {
  4746. dom.content.innerHTML = '';
  4747. dom.content.appendChild(this.content);
  4748. }
  4749. else if (this.data.content != undefined) {
  4750. dom.content.innerHTML = this.content;
  4751. }
  4752. else {
  4753. throw new Error('Property "content" missing in item ' + this.data.id);
  4754. }
  4755. changed = true;
  4756. }
  4757. // update class
  4758. var className = (this.data.className? ' ' + this.data.className : '') +
  4759. (this.selected ? ' selected' : '');
  4760. if (this.className != className) {
  4761. this.className = className;
  4762. dom.box.className = 'item box' + className;
  4763. dom.line.className = 'item line' + className;
  4764. dom.dot.className = 'item dot' + className;
  4765. changed = true;
  4766. }
  4767. }
  4768. return changed;
  4769. };
  4770. /**
  4771. * Show the item in the DOM (when not already visible). The items DOM will
  4772. * be created when needed.
  4773. * @return {Boolean} changed
  4774. */
  4775. ItemBox.prototype.show = function show() {
  4776. if (!this.dom || !this.dom.box.parentNode) {
  4777. return this.repaint();
  4778. }
  4779. else {
  4780. return false;
  4781. }
  4782. };
  4783. /**
  4784. * Hide the item from the DOM (when visible)
  4785. * @return {Boolean} changed
  4786. */
  4787. ItemBox.prototype.hide = function hide() {
  4788. var changed = false,
  4789. dom = this.dom;
  4790. if (dom) {
  4791. if (dom.box.parentNode) {
  4792. dom.box.parentNode.removeChild(dom.box);
  4793. changed = true;
  4794. }
  4795. if (dom.line.parentNode) {
  4796. dom.line.parentNode.removeChild(dom.line);
  4797. }
  4798. if (dom.dot.parentNode) {
  4799. dom.dot.parentNode.removeChild(dom.dot);
  4800. }
  4801. }
  4802. return changed;
  4803. };
  4804. /**
  4805. * Reflow the item: calculate its actual size and position from the DOM
  4806. * @return {boolean} resized returns true if the axis is resized
  4807. * @override
  4808. */
  4809. ItemBox.prototype.reflow = function reflow() {
  4810. var changed = 0,
  4811. update,
  4812. dom,
  4813. props,
  4814. options,
  4815. margin,
  4816. start,
  4817. align,
  4818. orientation,
  4819. top,
  4820. left,
  4821. data,
  4822. range;
  4823. if (this.data.start == undefined) {
  4824. throw new Error('Property "start" missing in item ' + this.data.id);
  4825. }
  4826. data = this.data;
  4827. range = this.parent && this.parent.range;
  4828. if (data && range) {
  4829. // TODO: account for the width of the item. Take some margin
  4830. this.visible = (data.start > range.start) && (data.start < range.end);
  4831. }
  4832. else {
  4833. this.visible = false;
  4834. }
  4835. if (this.visible) {
  4836. dom = this.dom;
  4837. if (dom) {
  4838. update = util.updateProperty;
  4839. props = this.props;
  4840. options = this.options;
  4841. start = this.parent.toScreen(this.data.start);
  4842. align = options.align || this.defaultOptions.align;
  4843. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  4844. orientation = options.orientation || this.defaultOptions.orientation;
  4845. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  4846. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  4847. changed += update(props.line, 'width', dom.line.offsetWidth);
  4848. changed += update(props.line, 'height', dom.line.offsetHeight);
  4849. changed += update(props.line, 'top', dom.line.offsetTop);
  4850. changed += update(this, 'width', dom.box.offsetWidth);
  4851. changed += update(this, 'height', dom.box.offsetHeight);
  4852. if (align == 'right') {
  4853. left = start - this.width;
  4854. }
  4855. else if (align == 'left') {
  4856. left = start;
  4857. }
  4858. else {
  4859. // default or 'center'
  4860. left = start - this.width / 2;
  4861. }
  4862. changed += update(this, 'left', left);
  4863. changed += update(props.line, 'left', start - props.line.width / 2);
  4864. changed += update(props.dot, 'left', start - props.dot.width / 2);
  4865. changed += update(props.dot, 'top', -props.dot.height / 2);
  4866. if (orientation == 'top') {
  4867. top = margin;
  4868. changed += update(this, 'top', top);
  4869. }
  4870. else {
  4871. // default or 'bottom'
  4872. var parentHeight = this.parent.height;
  4873. top = parentHeight - this.height - margin;
  4874. changed += update(this, 'top', top);
  4875. }
  4876. }
  4877. else {
  4878. changed += 1;
  4879. }
  4880. }
  4881. return (changed > 0);
  4882. };
  4883. /**
  4884. * Create an items DOM
  4885. * @private
  4886. */
  4887. ItemBox.prototype._create = function _create() {
  4888. var dom = this.dom;
  4889. if (!dom) {
  4890. this.dom = dom = {};
  4891. // create the box
  4892. dom.box = document.createElement('DIV');
  4893. // className is updated in repaint()
  4894. // contents box (inside the background box). used for making margins
  4895. dom.content = document.createElement('DIV');
  4896. dom.content.className = 'content';
  4897. dom.box.appendChild(dom.content);
  4898. // line to axis
  4899. dom.line = document.createElement('DIV');
  4900. dom.line.className = 'line';
  4901. // dot on axis
  4902. dom.dot = document.createElement('DIV');
  4903. dom.dot.className = 'dot';
  4904. }
  4905. };
  4906. /**
  4907. * Reposition the item, recalculate its left, top, and width, using the current
  4908. * range and size of the items itemset
  4909. * @override
  4910. */
  4911. ItemBox.prototype.reposition = function reposition() {
  4912. var dom = this.dom,
  4913. props = this.props,
  4914. orientation = this.options.orientation || this.defaultOptions.orientation;
  4915. if (dom) {
  4916. var box = dom.box,
  4917. line = dom.line,
  4918. dot = dom.dot;
  4919. box.style.left = this.left + 'px';
  4920. box.style.top = this.top + 'px';
  4921. line.style.left = props.line.left + 'px';
  4922. if (orientation == 'top') {
  4923. line.style.top = 0 + 'px';
  4924. line.style.height = this.top + 'px';
  4925. }
  4926. else {
  4927. // orientation 'bottom'
  4928. line.style.top = (this.top + this.height) + 'px';
  4929. line.style.height = Math.max(this.parent.height - this.top - this.height +
  4930. this.props.dot.height / 2, 0) + 'px';
  4931. }
  4932. dot.style.left = props.dot.left + 'px';
  4933. dot.style.top = props.dot.top + 'px';
  4934. }
  4935. };
  4936. /**
  4937. * @constructor ItemPoint
  4938. * @extends Item
  4939. * @param {ItemSet} parent
  4940. * @param {Object} data Object containing parameters start
  4941. * content, className.
  4942. * @param {Object} [options] Options to set initial property values
  4943. * @param {Object} [defaultOptions] default options
  4944. * // TODO: describe available options
  4945. */
  4946. function ItemPoint (parent, data, options, defaultOptions) {
  4947. this.props = {
  4948. dot: {
  4949. top: 0,
  4950. width: 0,
  4951. height: 0
  4952. },
  4953. content: {
  4954. height: 0,
  4955. marginLeft: 0
  4956. }
  4957. };
  4958. Item.call(this, parent, data, options, defaultOptions);
  4959. }
  4960. ItemPoint.prototype = new Item (null, null);
  4961. /**
  4962. * Select the item
  4963. * @override
  4964. */
  4965. ItemPoint.prototype.select = function select() {
  4966. this.selected = true;
  4967. // TODO: select and unselect
  4968. };
  4969. /**
  4970. * Unselect the item
  4971. * @override
  4972. */
  4973. ItemPoint.prototype.unselect = function unselect() {
  4974. this.selected = false;
  4975. // TODO: select and unselect
  4976. };
  4977. /**
  4978. * Repaint the item
  4979. * @return {Boolean} changed
  4980. */
  4981. ItemPoint.prototype.repaint = function repaint() {
  4982. // TODO: make an efficient repaint
  4983. var changed = false;
  4984. var dom = this.dom;
  4985. if (!dom) {
  4986. this._create();
  4987. dom = this.dom;
  4988. changed = true;
  4989. }
  4990. if (dom) {
  4991. if (!this.parent) {
  4992. throw new Error('Cannot repaint item: no parent attached');
  4993. }
  4994. var foreground = this.parent.getForeground();
  4995. if (!foreground) {
  4996. throw new Error('Cannot repaint time axis: ' +
  4997. 'parent has no foreground container element');
  4998. }
  4999. if (!dom.point.parentNode) {
  5000. foreground.appendChild(dom.point);
  5001. foreground.appendChild(dom.point);
  5002. changed = true;
  5003. }
  5004. // update contents
  5005. if (this.data.content != this.content) {
  5006. this.content = this.data.content;
  5007. if (this.content instanceof Element) {
  5008. dom.content.innerHTML = '';
  5009. dom.content.appendChild(this.content);
  5010. }
  5011. else if (this.data.content != undefined) {
  5012. dom.content.innerHTML = this.content;
  5013. }
  5014. else {
  5015. throw new Error('Property "content" missing in item ' + this.data.id);
  5016. }
  5017. changed = true;
  5018. }
  5019. // update class
  5020. var className = (this.data.className? ' ' + this.data.className : '') +
  5021. (this.selected ? ' selected' : '');
  5022. if (this.className != className) {
  5023. this.className = className;
  5024. dom.point.className = 'item point' + className;
  5025. changed = true;
  5026. }
  5027. }
  5028. return changed;
  5029. };
  5030. /**
  5031. * Show the item in the DOM (when not already visible). The items DOM will
  5032. * be created when needed.
  5033. * @return {Boolean} changed
  5034. */
  5035. ItemPoint.prototype.show = function show() {
  5036. if (!this.dom || !this.dom.point.parentNode) {
  5037. return this.repaint();
  5038. }
  5039. else {
  5040. return false;
  5041. }
  5042. };
  5043. /**
  5044. * Hide the item from the DOM (when visible)
  5045. * @return {Boolean} changed
  5046. */
  5047. ItemPoint.prototype.hide = function hide() {
  5048. var changed = false,
  5049. dom = this.dom;
  5050. if (dom) {
  5051. if (dom.point.parentNode) {
  5052. dom.point.parentNode.removeChild(dom.point);
  5053. changed = true;
  5054. }
  5055. }
  5056. return changed;
  5057. };
  5058. /**
  5059. * Reflow the item: calculate its actual size from the DOM
  5060. * @return {boolean} resized returns true if the axis is resized
  5061. * @override
  5062. */
  5063. ItemPoint.prototype.reflow = function reflow() {
  5064. var changed = 0,
  5065. update,
  5066. dom,
  5067. props,
  5068. options,
  5069. margin,
  5070. orientation,
  5071. start,
  5072. top,
  5073. data,
  5074. range;
  5075. if (this.data.start == undefined) {
  5076. throw new Error('Property "start" missing in item ' + this.data.id);
  5077. }
  5078. data = this.data;
  5079. range = this.parent && this.parent.range;
  5080. if (data && range) {
  5081. // TODO: account for the width of the item. Take some margin
  5082. this.visible = (data.start > range.start) && (data.start < range.end);
  5083. }
  5084. else {
  5085. this.visible = false;
  5086. }
  5087. if (this.visible) {
  5088. dom = this.dom;
  5089. if (dom) {
  5090. update = util.updateProperty;
  5091. props = this.props;
  5092. options = this.options;
  5093. orientation = options.orientation || this.defaultOptions.orientation;
  5094. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5095. start = this.parent.toScreen(this.data.start);
  5096. changed += update(this, 'width', dom.point.offsetWidth);
  5097. changed += update(this, 'height', dom.point.offsetHeight);
  5098. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5099. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5100. changed += update(props.content, 'height', dom.content.offsetHeight);
  5101. if (orientation == 'top') {
  5102. top = margin;
  5103. }
  5104. else {
  5105. // default or 'bottom'
  5106. var parentHeight = this.parent.height;
  5107. top = Math.max(parentHeight - this.height - margin, 0);
  5108. }
  5109. changed += update(this, 'top', top);
  5110. changed += update(this, 'left', start - props.dot.width / 2);
  5111. changed += update(props.content, 'marginLeft', 1.5 * props.dot.width);
  5112. //changed += update(props.content, 'marginRight', 0.5 * props.dot.width); // TODO
  5113. changed += update(props.dot, 'top', (this.height - props.dot.height) / 2);
  5114. }
  5115. else {
  5116. changed += 1;
  5117. }
  5118. }
  5119. return (changed > 0);
  5120. };
  5121. /**
  5122. * Create an items DOM
  5123. * @private
  5124. */
  5125. ItemPoint.prototype._create = function _create() {
  5126. var dom = this.dom;
  5127. if (!dom) {
  5128. this.dom = dom = {};
  5129. // background box
  5130. dom.point = document.createElement('div');
  5131. // className is updated in repaint()
  5132. // contents box, right from the dot
  5133. dom.content = document.createElement('div');
  5134. dom.content.className = 'content';
  5135. dom.point.appendChild(dom.content);
  5136. // dot at start
  5137. dom.dot = document.createElement('div');
  5138. dom.dot.className = 'dot';
  5139. dom.point.appendChild(dom.dot);
  5140. }
  5141. };
  5142. /**
  5143. * Reposition the item, recalculate its left, top, and width, using the current
  5144. * range and size of the items itemset
  5145. * @override
  5146. */
  5147. ItemPoint.prototype.reposition = function reposition() {
  5148. var dom = this.dom,
  5149. props = this.props;
  5150. if (dom) {
  5151. dom.point.style.top = this.top + 'px';
  5152. dom.point.style.left = this.left + 'px';
  5153. dom.content.style.marginLeft = props.content.marginLeft + 'px';
  5154. //dom.content.style.marginRight = props.content.marginRight + 'px'; // TODO
  5155. dom.dot.style.top = props.dot.top + 'px';
  5156. }
  5157. };
  5158. /**
  5159. * @constructor ItemRange
  5160. * @extends Item
  5161. * @param {ItemSet} parent
  5162. * @param {Object} data Object containing parameters start, end
  5163. * content, className.
  5164. * @param {Object} [options] Options to set initial property values
  5165. * @param {Object} [defaultOptions] default options
  5166. * // TODO: describe available options
  5167. */
  5168. function ItemRange (parent, data, options, defaultOptions) {
  5169. this.props = {
  5170. content: {
  5171. left: 0,
  5172. width: 0
  5173. }
  5174. };
  5175. Item.call(this, parent, data, options, defaultOptions);
  5176. }
  5177. ItemRange.prototype = new Item (null, null);
  5178. /**
  5179. * Select the item
  5180. * @override
  5181. */
  5182. ItemRange.prototype.select = function select() {
  5183. this.selected = true;
  5184. // TODO: select and unselect
  5185. };
  5186. /**
  5187. * Unselect the item
  5188. * @override
  5189. */
  5190. ItemRange.prototype.unselect = function unselect() {
  5191. this.selected = false;
  5192. // TODO: select and unselect
  5193. };
  5194. /**
  5195. * Repaint the item
  5196. * @return {Boolean} changed
  5197. */
  5198. ItemRange.prototype.repaint = function repaint() {
  5199. // TODO: make an efficient repaint
  5200. var changed = false;
  5201. var dom = this.dom;
  5202. if (!dom) {
  5203. this._create();
  5204. dom = this.dom;
  5205. changed = true;
  5206. }
  5207. if (dom) {
  5208. if (!this.parent) {
  5209. throw new Error('Cannot repaint item: no parent attached');
  5210. }
  5211. var foreground = this.parent.getForeground();
  5212. if (!foreground) {
  5213. throw new Error('Cannot repaint time axis: ' +
  5214. 'parent has no foreground container element');
  5215. }
  5216. if (!dom.box.parentNode) {
  5217. foreground.appendChild(dom.box);
  5218. changed = true;
  5219. }
  5220. // update content
  5221. if (this.data.content != this.content) {
  5222. this.content = this.data.content;
  5223. if (this.content instanceof Element) {
  5224. dom.content.innerHTML = '';
  5225. dom.content.appendChild(this.content);
  5226. }
  5227. else if (this.data.content != undefined) {
  5228. dom.content.innerHTML = this.content;
  5229. }
  5230. else {
  5231. throw new Error('Property "content" missing in item ' + this.data.id);
  5232. }
  5233. changed = true;
  5234. }
  5235. // update class
  5236. var className = this.data.className ? ('' + this.data.className) : '';
  5237. if (this.className != className) {
  5238. this.className = className;
  5239. dom.box.className = 'item range' + className;
  5240. changed = true;
  5241. }
  5242. }
  5243. return changed;
  5244. };
  5245. /**
  5246. * Show the item in the DOM (when not already visible). The items DOM will
  5247. * be created when needed.
  5248. * @return {Boolean} changed
  5249. */
  5250. ItemRange.prototype.show = function show() {
  5251. if (!this.dom || !this.dom.box.parentNode) {
  5252. return this.repaint();
  5253. }
  5254. else {
  5255. return false;
  5256. }
  5257. };
  5258. /**
  5259. * Hide the item from the DOM (when visible)
  5260. * @return {Boolean} changed
  5261. */
  5262. ItemRange.prototype.hide = function hide() {
  5263. var changed = false,
  5264. dom = this.dom;
  5265. if (dom) {
  5266. if (dom.box.parentNode) {
  5267. dom.box.parentNode.removeChild(dom.box);
  5268. changed = true;
  5269. }
  5270. }
  5271. return changed;
  5272. };
  5273. /**
  5274. * Reflow the item: calculate its actual size from the DOM
  5275. * @return {boolean} resized returns true if the axis is resized
  5276. * @override
  5277. */
  5278. ItemRange.prototype.reflow = function reflow() {
  5279. var changed = 0,
  5280. dom,
  5281. props,
  5282. options,
  5283. margin,
  5284. padding,
  5285. parent,
  5286. start,
  5287. end,
  5288. data,
  5289. range,
  5290. update,
  5291. box,
  5292. parentWidth,
  5293. contentLeft,
  5294. orientation,
  5295. top;
  5296. if (this.data.start == undefined) {
  5297. throw new Error('Property "start" missing in item ' + this.data.id);
  5298. }
  5299. if (this.data.end == undefined) {
  5300. throw new Error('Property "end" missing in item ' + this.data.id);
  5301. }
  5302. data = this.data;
  5303. range = this.parent && this.parent.range;
  5304. if (data && range) {
  5305. // TODO: account for the width of the item. Take some margin
  5306. this.visible = (data.start < range.end) && (data.end > range.start);
  5307. }
  5308. else {
  5309. this.visible = false;
  5310. }
  5311. if (this.visible) {
  5312. dom = this.dom;
  5313. if (dom) {
  5314. props = this.props;
  5315. options = this.options;
  5316. parent = this.parent;
  5317. start = parent.toScreen(this.data.start);
  5318. end = parent.toScreen(this.data.end);
  5319. update = util.updateProperty;
  5320. box = dom.box;
  5321. parentWidth = parent.width;
  5322. orientation = options.orientation || this.defaultOptions.orientation;
  5323. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5324. padding = options.padding || this.defaultOptions.padding;
  5325. changed += update(props.content, 'width', dom.content.offsetWidth);
  5326. changed += update(this, 'height', box.offsetHeight);
  5327. // limit the width of the this, as browsers cannot draw very wide divs
  5328. if (start < -parentWidth) {
  5329. start = -parentWidth;
  5330. }
  5331. if (end > 2 * parentWidth) {
  5332. end = 2 * parentWidth;
  5333. }
  5334. // when range exceeds left of the window, position the contents at the left of the visible area
  5335. if (start < 0) {
  5336. contentLeft = Math.min(-start,
  5337. (end - start - props.content.width - 2 * padding));
  5338. // TODO: remove the need for options.padding. it's terrible.
  5339. }
  5340. else {
  5341. contentLeft = 0;
  5342. }
  5343. changed += update(props.content, 'left', contentLeft);
  5344. if (orientation == 'top') {
  5345. top = margin;
  5346. changed += update(this, 'top', top);
  5347. }
  5348. else {
  5349. // default or 'bottom'
  5350. top = parent.height - this.height - margin;
  5351. changed += update(this, 'top', top);
  5352. }
  5353. changed += update(this, 'left', start);
  5354. changed += update(this, 'width', Math.max(end - start, 1)); // TODO: reckon with border width;
  5355. }
  5356. else {
  5357. changed += 1;
  5358. }
  5359. }
  5360. return (changed > 0);
  5361. };
  5362. /**
  5363. * Create an items DOM
  5364. * @private
  5365. */
  5366. ItemRange.prototype._create = function _create() {
  5367. var dom = this.dom;
  5368. if (!dom) {
  5369. this.dom = dom = {};
  5370. // background box
  5371. dom.box = document.createElement('div');
  5372. // className is updated in repaint()
  5373. // contents box
  5374. dom.content = document.createElement('div');
  5375. dom.content.className = 'content';
  5376. dom.box.appendChild(dom.content);
  5377. }
  5378. };
  5379. /**
  5380. * Reposition the item, recalculate its left, top, and width, using the current
  5381. * range and size of the items itemset
  5382. * @override
  5383. */
  5384. ItemRange.prototype.reposition = function reposition() {
  5385. var dom = this.dom,
  5386. props = this.props;
  5387. if (dom) {
  5388. dom.box.style.top = this.top + 'px';
  5389. dom.box.style.left = this.left + 'px';
  5390. dom.box.style.width = this.width + 'px';
  5391. dom.content.style.left = props.content.left + 'px';
  5392. }
  5393. };
  5394. /**
  5395. * @constructor Group
  5396. * @param {GroupSet} parent
  5397. * @param {Number | String} groupId
  5398. * @param {Object} [options] Options to set initial property values
  5399. * // TODO: describe available options
  5400. * @extends Component
  5401. */
  5402. function Group (parent, groupId, options) {
  5403. this.id = util.randomUUID();
  5404. this.parent = parent;
  5405. this.groupId = groupId;
  5406. this.itemsData = null; // DataSet
  5407. this.itemset = null; // ItemSet
  5408. this.options = options || {};
  5409. this.options.top = 0;
  5410. this.top = 0;
  5411. this.left = 0;
  5412. this.width = 0;
  5413. this.height = 0;
  5414. }
  5415. Group.prototype = new Component();
  5416. // TODO: comment
  5417. Group.prototype.setOptions = Component.prototype.setOptions;
  5418. /**
  5419. * Get the container element of the panel, which can be used by a child to
  5420. * add its own widgets.
  5421. * @returns {HTMLElement} container
  5422. */
  5423. Group.prototype.getContainer = function () {
  5424. return this.parent.getContainer();
  5425. };
  5426. /**
  5427. * Set item set for the group. The group will create a view on the itemset,
  5428. * filtered by the groups id.
  5429. * @param {DataSet | DataView} items
  5430. */
  5431. Group.prototype.setItems = function setItems(items) {
  5432. if (this.itemset) {
  5433. // remove current item set
  5434. this.itemset.hide();
  5435. this.itemset.setItems();
  5436. this.parent.controller.remove(this.itemset);
  5437. this.itemset = null;
  5438. }
  5439. if (items) {
  5440. var groupId = this.groupId;
  5441. var itemsetOptions = Object.create(this.options);
  5442. this.itemset = new ItemSet(this, null, itemsetOptions);
  5443. this.itemset.setRange(this.parent.range);
  5444. this.view = new DataView(items, {
  5445. filter: function (item) {
  5446. return item.group == groupId;
  5447. }
  5448. });
  5449. this.itemset.setItems(this.view);
  5450. this.parent.controller.add(this.itemset);
  5451. }
  5452. };
  5453. /**
  5454. * Repaint the item
  5455. * @return {Boolean} changed
  5456. */
  5457. Group.prototype.repaint = function repaint() {
  5458. return false;
  5459. };
  5460. /**
  5461. * Reflow the item
  5462. * @return {Boolean} resized
  5463. */
  5464. Group.prototype.reflow = function reflow() {
  5465. var changed = 0,
  5466. update = util.updateProperty;
  5467. changed += update(this, 'top', this.itemset ? this.itemset.top : 0);
  5468. changed += update(this, 'height', this.itemset ? this.itemset.height : 0);
  5469. return (changed > 0);
  5470. };
  5471. /**
  5472. * An GroupSet holds a set of groups
  5473. * @param {Component} parent
  5474. * @param {Component[]} [depends] Components on which this components depends
  5475. * (except for the parent)
  5476. * @param {Object} [options] See GroupSet.setOptions for the available
  5477. * options.
  5478. * @constructor GroupSet
  5479. * @extends Panel
  5480. */
  5481. function GroupSet(parent, depends, options) {
  5482. this.id = util.randomUUID();
  5483. this.parent = parent;
  5484. this.depends = depends;
  5485. this.options = options || {};
  5486. this.range = null; // Range or Object {start: number, end: number}
  5487. this.itemsData = null; // DataSet with items
  5488. this.groupsData = null; // DataSet with groups
  5489. this.groups = {}; // map with groups
  5490. // changes in groups are queued key/value map containing id/action
  5491. this.queue = {};
  5492. var me = this;
  5493. this.listeners = {
  5494. 'add': function (event, params) {
  5495. me._onAdd(params.items);
  5496. },
  5497. 'update': function (event, params) {
  5498. me._onUpdate(params.items);
  5499. },
  5500. 'remove': function (event, params) {
  5501. me._onRemove(params.items);
  5502. }
  5503. };
  5504. }
  5505. GroupSet.prototype = new Panel();
  5506. /**
  5507. * Set options for the GroupSet. Existing options will be extended/overwritten.
  5508. * @param {Object} [options] The following options are available:
  5509. * {String | function} groupsOrder
  5510. * TODO: describe options
  5511. */
  5512. GroupSet.prototype.setOptions = Component.prototype.setOptions;
  5513. GroupSet.prototype.setRange = function (range) {
  5514. // TODO: implement setRange
  5515. };
  5516. /**
  5517. * Set items
  5518. * @param {vis.DataSet | null} items
  5519. */
  5520. GroupSet.prototype.setItems = function setItems(items) {
  5521. this.itemsData = items;
  5522. for (var id in this.groups) {
  5523. if (this.groups.hasOwnProperty(id)) {
  5524. var group = this.groups[id];
  5525. group.setItems(items);
  5526. }
  5527. }
  5528. };
  5529. /**
  5530. * Get items
  5531. * @return {vis.DataSet | null} items
  5532. */
  5533. GroupSet.prototype.getItems = function getItems() {
  5534. return this.itemsData;
  5535. };
  5536. /**
  5537. * Set range (start and end).
  5538. * @param {Range | Object} range A Range or an object containing start and end.
  5539. */
  5540. GroupSet.prototype.setRange = function setRange(range) {
  5541. this.range = range;
  5542. };
  5543. /**
  5544. * Set groups
  5545. * @param {vis.DataSet} groups
  5546. */
  5547. GroupSet.prototype.setGroups = function setGroups(groups) {
  5548. var me = this,
  5549. ids;
  5550. // unsubscribe from current dataset
  5551. if (this.groupsData) {
  5552. util.forEach(this.listeners, function (callback, event) {
  5553. me.groupsData.unsubscribe(event, callback);
  5554. });
  5555. // remove all drawn groups
  5556. ids = this.groupsData.getIds();
  5557. this._onRemove(ids);
  5558. }
  5559. // replace the dataset
  5560. if (!groups) {
  5561. this.groupsData = null;
  5562. }
  5563. else if (groups instanceof DataSet) {
  5564. this.groupsData = groups;
  5565. }
  5566. else {
  5567. this.groupsData = new DataSet({
  5568. fieldTypes: {
  5569. start: 'Date',
  5570. end: 'Date'
  5571. }
  5572. });
  5573. this.groupsData.add(groups);
  5574. }
  5575. if (this.groupsData) {
  5576. // subscribe to new dataset
  5577. var id = this.id;
  5578. util.forEach(this.listeners, function (callback, event) {
  5579. me.groupsData.subscribe(event, callback, id);
  5580. });
  5581. // draw all new groups
  5582. ids = this.groupsData.getIds();
  5583. this._onAdd(ids);
  5584. }
  5585. };
  5586. /**
  5587. * Get groups
  5588. * @return {vis.DataSet | null} groups
  5589. */
  5590. GroupSet.prototype.getGroups = function getGroups() {
  5591. return this.groupsData;
  5592. };
  5593. /**
  5594. * Repaint the component
  5595. * @return {Boolean} changed
  5596. */
  5597. GroupSet.prototype.repaint = function repaint() {
  5598. var changed = 0,
  5599. update = util.updateProperty,
  5600. asSize = util.option.asSize,
  5601. options = this.options,
  5602. frame = this.frame;
  5603. if (!frame) {
  5604. frame = document.createElement('div');
  5605. frame.className = 'groupset';
  5606. var className = options.className;
  5607. if (className) {
  5608. util.addClassName(frame, util.option.asString(className));
  5609. }
  5610. this.frame = frame;
  5611. changed += 1;
  5612. }
  5613. if (!this.parent) {
  5614. throw new Error('Cannot repaint groupset: no parent attached');
  5615. }
  5616. var parentContainer = this.parent.getContainer();
  5617. if (!parentContainer) {
  5618. throw new Error('Cannot repaint groupset: parent has no container element');
  5619. }
  5620. if (!frame.parentNode) {
  5621. parentContainer.appendChild(frame);
  5622. changed += 1;
  5623. }
  5624. // reposition frame
  5625. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  5626. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  5627. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  5628. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  5629. var me = this,
  5630. queue = this.queue,
  5631. groups = this.groups,
  5632. groupsData = this.groupsData;
  5633. // show/hide added/changed/removed items
  5634. var ids = Object.keys(queue);
  5635. if (ids.length) {
  5636. ids.forEach(function (id) {
  5637. var action = queue[id];
  5638. var group = groups[id];
  5639. //noinspection FallthroughInSwitchStatementJS
  5640. switch (action) {
  5641. case 'add':
  5642. case 'update':
  5643. if (!group) {
  5644. var groupOptions = Object.create(me.options);
  5645. group = new Group(me, id, groupOptions);
  5646. group.setItems(me.itemsData); // attach items data
  5647. groups[id] = group;
  5648. me.controller.add(group);
  5649. }
  5650. // TODO: update group data
  5651. group.data = groupsData.get(id);
  5652. delete queue[id];
  5653. break;
  5654. case 'remove':
  5655. if (group) {
  5656. group.setItems(); // detach items data
  5657. delete groups[id];
  5658. me.controller.remove(group);
  5659. }
  5660. // update lists
  5661. delete queue[id];
  5662. break;
  5663. default:
  5664. console.log('Error: unknown action "' + action + '"');
  5665. }
  5666. });
  5667. // the groupset depends on each of the groups
  5668. //this.depends = this.groups; // TODO: gives a circular reference through the parent
  5669. // TODO: apply dependencies of the groupset
  5670. // update the top positions of the groups in the correct order
  5671. var orderedGroups = this.groupsData.getIds({
  5672. order: this.options.groupsOrder
  5673. });
  5674. for (var i = 0; i < orderedGroups.length; i++) {
  5675. (function (group, prevGroup) {
  5676. var top = 0;
  5677. if (prevGroup) {
  5678. top = function () {
  5679. // TODO: top must reckon with options.maxHeight
  5680. return prevGroup.top + prevGroup.height;
  5681. }
  5682. }
  5683. group.setOptions({
  5684. top: top
  5685. });
  5686. })(groups[orderedGroups[i]], groups[orderedGroups[i - 1]]);
  5687. }
  5688. changed++;
  5689. }
  5690. return (changed > 0);
  5691. };
  5692. /**
  5693. * Get container element
  5694. * @return {HTMLElement} container
  5695. */
  5696. GroupSet.prototype.getContainer = function getContainer() {
  5697. // TODO: replace later on with container element for holding itemsets
  5698. return this.frame;
  5699. };
  5700. /**
  5701. * Reflow the component
  5702. * @return {Boolean} resized
  5703. */
  5704. GroupSet.prototype.reflow = function reflow() {
  5705. var changed = 0,
  5706. options = this.options,
  5707. update = util.updateProperty,
  5708. asNumber = util.option.asNumber,
  5709. asSize = util.option.asSize,
  5710. frame = this.frame;
  5711. if (frame) {
  5712. var maxHeight = asNumber(options.maxHeight);
  5713. var fixedHeight = (asSize(options.height) != null);
  5714. var height;
  5715. if (fixedHeight) {
  5716. height = frame.offsetHeight;
  5717. }
  5718. else {
  5719. // height is not specified, calculate the sum of the height of all groups
  5720. height = 0;
  5721. for (var id in this.groups) {
  5722. if (this.groups.hasOwnProperty(id)) {
  5723. var group = this.groups[id];
  5724. height += group.height;
  5725. }
  5726. }
  5727. }
  5728. if (maxHeight != null) {
  5729. height = Math.min(height, maxHeight);
  5730. }
  5731. changed += update(this, 'height', height);
  5732. changed += update(this, 'top', frame.offsetTop);
  5733. changed += update(this, 'left', frame.offsetLeft);
  5734. changed += update(this, 'width', frame.offsetWidth);
  5735. }
  5736. return (changed > 0);
  5737. };
  5738. /**
  5739. * Hide the component from the DOM
  5740. * @return {Boolean} changed
  5741. */
  5742. GroupSet.prototype.hide = function hide() {
  5743. if (this.frame && this.frame.parentNode) {
  5744. this.frame.parentNode.removeChild(this.frame);
  5745. return true;
  5746. }
  5747. else {
  5748. return false;
  5749. }
  5750. };
  5751. /**
  5752. * Show the component in the DOM (when not already visible).
  5753. * A repaint will be executed when the component is not visible
  5754. * @return {Boolean} changed
  5755. */
  5756. GroupSet.prototype.show = function show() {
  5757. if (!this.frame || !this.frame.parentNode) {
  5758. return this.repaint();
  5759. }
  5760. else {
  5761. return false;
  5762. }
  5763. };
  5764. /**
  5765. * Handle updated groups
  5766. * @param {Number[]} ids
  5767. * @private
  5768. */
  5769. GroupSet.prototype._onUpdate = function _onUpdate(ids) {
  5770. this._toQueue(ids, 'update');
  5771. };
  5772. /**
  5773. * Handle changed groups
  5774. * @param {Number[]} ids
  5775. * @private
  5776. */
  5777. GroupSet.prototype._onAdd = function _onAdd(ids) {
  5778. this._toQueue(ids, 'add');
  5779. };
  5780. /**
  5781. * Handle removed groups
  5782. * @param {Number[]} ids
  5783. * @private
  5784. */
  5785. GroupSet.prototype._onRemove = function _onRemove(ids) {
  5786. this._toQueue(ids, 'remove');
  5787. };
  5788. /**
  5789. * Put groups in the queue to be added/updated/remove
  5790. * @param {Number[]} ids
  5791. * @param {String} action can be 'add', 'update', 'remove'
  5792. */
  5793. GroupSet.prototype._toQueue = function _toQueue(ids, action) {
  5794. var queue = this.queue;
  5795. ids.forEach(function (id) {
  5796. queue[id] = action;
  5797. });
  5798. if (this.controller) {
  5799. //this.requestReflow();
  5800. this.requestRepaint();
  5801. }
  5802. };
  5803. /**
  5804. * Create a timeline visualization
  5805. * @param {HTMLElement} container
  5806. * @param {vis.DataSet | Array | DataTable} [items]
  5807. * @param {Object} [options] See Timeline.setOptions for the available options.
  5808. * @constructor
  5809. */
  5810. function Timeline (container, items, options) {
  5811. var me = this;
  5812. this.options = util.extend({
  5813. orientation: 'bottom',
  5814. min: null,
  5815. max: null,
  5816. zoomMin: 10, // milliseconds
  5817. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  5818. // moveable: true, // TODO: option moveable
  5819. // zoomable: true, // TODO: option zoomable
  5820. showMinorLabels: true,
  5821. showMajorLabels: true,
  5822. autoResize: false
  5823. }, options);
  5824. // controller
  5825. this.controller = new Controller();
  5826. // root panel
  5827. if (!container) {
  5828. throw new Error('No container element provided');
  5829. }
  5830. var mainOptions = Object.create(this.options);
  5831. mainOptions.height = function () {
  5832. if (me.options.height) {
  5833. // fixed height
  5834. return me.options.height;
  5835. }
  5836. else {
  5837. // auto height
  5838. return me.timeaxis.height + me.content.height;
  5839. }
  5840. };
  5841. this.root = new RootPanel(container, mainOptions);
  5842. this.controller.add(this.root);
  5843. // range
  5844. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  5845. this.range = new Range({
  5846. start: now.clone().add('days', -3).valueOf(),
  5847. end: now.clone().add('days', 4).valueOf()
  5848. });
  5849. // TODO: reckon with options moveable and zoomable
  5850. this.range.subscribe(this.root, 'move', 'horizontal');
  5851. this.range.subscribe(this.root, 'zoom', 'horizontal');
  5852. this.range.on('rangechange', function () {
  5853. var force = true;
  5854. me.controller.requestReflow(force);
  5855. });
  5856. this.range.on('rangechanged', function () {
  5857. var force = true;
  5858. me.controller.requestReflow(force);
  5859. });
  5860. // TODO: put the listeners in setOptions, be able to dynamically change with options moveable and zoomable
  5861. // time axis
  5862. var timeaxisOptions = Object.create(mainOptions);
  5863. timeaxisOptions.range = this.range;
  5864. this.timeaxis = new TimeAxis(this.root, [], timeaxisOptions);
  5865. this.timeaxis.setRange(this.range);
  5866. this.controller.add(this.timeaxis);
  5867. // create itemset or groupset
  5868. this.setGroups(null);
  5869. this.itemsData = null; // DataSet
  5870. this.groupsData = null; // DataSet
  5871. // set data
  5872. if (items) {
  5873. this.setItems(items);
  5874. }
  5875. }
  5876. /**
  5877. * Set options
  5878. * @param {Object} options TODO: describe the available options
  5879. */
  5880. Timeline.prototype.setOptions = function (options) {
  5881. if (options) {
  5882. util.extend(this.options, options);
  5883. }
  5884. this.controller.reflow();
  5885. this.controller.repaint();
  5886. };
  5887. /**
  5888. * Set items
  5889. * @param {vis.DataSet | Array | DataTable | null} items
  5890. */
  5891. Timeline.prototype.setItems = function(items) {
  5892. var initialLoad = (this.itemsData == null);
  5893. // convert to type DataSet when needed
  5894. var newItemSet;
  5895. if (!items) {
  5896. newItemSet = null;
  5897. }
  5898. else if (items instanceof DataSet) {
  5899. newItemSet = items;
  5900. }
  5901. if (!(items instanceof DataSet)) {
  5902. newItemSet = new DataSet({
  5903. fieldTypes: {
  5904. start: 'Date',
  5905. end: 'Date'
  5906. }
  5907. });
  5908. newItemSet.add(items);
  5909. }
  5910. // set items
  5911. this.itemsData = newItemSet;
  5912. this.content.setItems(newItemSet);
  5913. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  5914. // apply the data range as range
  5915. var dataRange = this.getItemRange();
  5916. // add 5% on both sides
  5917. var min = dataRange.min;
  5918. var max = dataRange.max;
  5919. if (min != null && max != null) {
  5920. var interval = (max.valueOf() - min.valueOf());
  5921. min = new Date(min.valueOf() - interval * 0.05);
  5922. max = new Date(max.valueOf() + interval * 0.05);
  5923. }
  5924. // override specified start and/or end date
  5925. if (this.options.start != undefined) {
  5926. min = new Date(this.options.start.valueOf());
  5927. }
  5928. if (this.options.end != undefined) {
  5929. max = new Date(this.options.end.valueOf());
  5930. }
  5931. // apply range if there is a min or max available
  5932. if (min != null || max != null) {
  5933. this.range.setRange(min, max);
  5934. }
  5935. }
  5936. };
  5937. /**
  5938. * Set groups
  5939. * @param {vis.DataSet | Array | DataTable} groups
  5940. */
  5941. Timeline.prototype.setGroups = function(groups) {
  5942. var me = this;
  5943. this.groupsData = groups;
  5944. // switch content type between ItemSet or GroupSet when needed
  5945. var type = this.groupsData ? GroupSet : ItemSet;
  5946. if (!(this.content instanceof type)) {
  5947. // remove old content set
  5948. if (this.content) {
  5949. this.content.hide();
  5950. if (this.content.setItems) {
  5951. this.content.setItems(); // disconnect from items
  5952. }
  5953. if (this.content.setGroups) {
  5954. this.content.setGroups(); // disconnect from groups
  5955. }
  5956. this.controller.remove(this.content);
  5957. }
  5958. // create new content set
  5959. var options = Object.create(this.options);
  5960. util.extend(options, {
  5961. top: function () {
  5962. if (me.options.orientation == 'top') {
  5963. return me.timeaxis.height;
  5964. }
  5965. else {
  5966. return me.root.height - me.timeaxis.height - me.content.height;
  5967. }
  5968. },
  5969. height: function () {
  5970. if (me.options.height) {
  5971. return me.root.height - me.timeaxis.height;
  5972. }
  5973. else {
  5974. return null;
  5975. }
  5976. },
  5977. maxHeight: function () {
  5978. if (me.options.maxHeight) {
  5979. if (!util.isNumber(me.options.maxHeight)) {
  5980. throw new TypeError('Number expected for property maxHeight');
  5981. }
  5982. return me.options.maxHeight - me.timeaxis.height;
  5983. }
  5984. else {
  5985. return null;
  5986. }
  5987. }
  5988. });
  5989. this.content = new type(this.root, [this.timeaxis], options);
  5990. if (this.content.setRange) {
  5991. this.content.setRange(this.range);
  5992. }
  5993. if (this.content.setItems) {
  5994. this.content.setItems(this.itemsData);
  5995. }
  5996. if (this.content.setGroups) {
  5997. this.content.setGroups(this.groupsData);
  5998. }
  5999. this.controller.add(this.content);
  6000. }
  6001. };
  6002. /**
  6003. * Get the data range of the item set.
  6004. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  6005. * When no minimum is found, min==null
  6006. * When no maximum is found, max==null
  6007. */
  6008. Timeline.prototype.getItemRange = function getItemRange() {
  6009. // calculate min from start filed
  6010. var itemsData = this.itemsData,
  6011. min = null,
  6012. max = null;
  6013. if (itemsData) {
  6014. // calculate the minimum value of the field 'start'
  6015. var minItem = itemsData.min('start');
  6016. min = minItem ? minItem.start.valueOf() : null;
  6017. // calculate maximum value of fields 'start' and 'end'
  6018. var maxStartItem = itemsData.max('start');
  6019. if (maxStartItem) {
  6020. max = maxStartItem.start.valueOf();
  6021. }
  6022. var maxEndItem = itemsData.max('end');
  6023. if (maxEndItem) {
  6024. if (max == null) {
  6025. max = maxEndItem.end.valueOf();
  6026. }
  6027. else {
  6028. max = Math.max(max, maxEndItem.end.valueOf());
  6029. }
  6030. }
  6031. }
  6032. return {
  6033. min: (min != null) ? new Date(min) : null,
  6034. max: (max != null) ? new Date(max) : null
  6035. };
  6036. };
  6037. (function(exports) {
  6038. /**
  6039. * Parse a text source containing data in DOT language into a JSON object.
  6040. * The object contains two lists: one with nodes and one with edges.
  6041. *
  6042. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  6043. *
  6044. * @param {String} data Text containing a graph in DOT-notation
  6045. * @return {Object} graph An object containing two parameters:
  6046. * {Object[]} nodes
  6047. * {Object[]} edges
  6048. */
  6049. function parseDOT (data) {
  6050. dot = data;
  6051. return parseGraph();
  6052. }
  6053. // token types enumeration
  6054. var TOKENTYPE = {
  6055. NULL : 0,
  6056. DELIMITER : 1,
  6057. IDENTIFIER: 2,
  6058. UNKNOWN : 3
  6059. };
  6060. // map with all delimiters
  6061. var DELIMITERS = {
  6062. '{': true,
  6063. '}': true,
  6064. '[': true,
  6065. ']': true,
  6066. ';': true,
  6067. '=': true,
  6068. ',': true,
  6069. '->': true,
  6070. '--': true
  6071. };
  6072. var dot = ''; // current dot file
  6073. var index = 0; // current index in dot file
  6074. var c = ''; // current token character in expr
  6075. var token = ''; // current token
  6076. var tokenType = TOKENTYPE.NULL; // type of the token
  6077. /**
  6078. * Get the first character from the dot file.
  6079. * The character is stored into the char c. If the end of the dot file is
  6080. * reached, the function puts an empty string in c.
  6081. */
  6082. function first() {
  6083. index = 0;
  6084. c = dot.charAt(0);
  6085. }
  6086. /**
  6087. * Get the next character from the dot file.
  6088. * The character is stored into the char c. If the end of the dot file is
  6089. * reached, the function puts an empty string in c.
  6090. */
  6091. function next() {
  6092. index++;
  6093. c = dot.charAt(index);
  6094. }
  6095. /**
  6096. * Preview the next character from the dot file.
  6097. * @return {String} cNext
  6098. */
  6099. function nextPreview() {
  6100. return dot.charAt(index + 1);
  6101. }
  6102. /**
  6103. * Test whether given character is alphabetic or numeric
  6104. * @param {String} c
  6105. * @return {Boolean} isAlphaNumeric
  6106. */
  6107. var regexAlphaNumeric = /[a-zA-Z_0-9.#]/;
  6108. function isAlphaNumeric(c) {
  6109. return regexAlphaNumeric.test(c);
  6110. }
  6111. /**
  6112. * Merge all properties of object b into object b
  6113. * @param {Object} a
  6114. * @param {Object} b
  6115. * @return {Object} a
  6116. */
  6117. function merge (a, b) {
  6118. if (!a) {
  6119. a = {};
  6120. }
  6121. if (b) {
  6122. for (var name in b) {
  6123. if (b.hasOwnProperty(name)) {
  6124. a[name] = b[name];
  6125. }
  6126. }
  6127. }
  6128. return a;
  6129. }
  6130. /**
  6131. * Set a value in an object, where the provided parameter name can be a
  6132. * path with nested parameters. For example:
  6133. *
  6134. * var obj = {a: 2};
  6135. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  6136. *
  6137. * @param {Object} obj
  6138. * @param {String} path A parameter name or dot-separated parameter path,
  6139. * like "color.highlight.border".
  6140. * @param {*} value
  6141. */
  6142. function setValue(obj, path, value) {
  6143. var keys = path.split('.');
  6144. var o = obj;
  6145. while (keys.length) {
  6146. var key = keys.shift();
  6147. if (keys.length) {
  6148. // this isn't the end point
  6149. if (!o[key]) {
  6150. o[key] = {};
  6151. }
  6152. o = o[key];
  6153. }
  6154. else {
  6155. // this is the end point
  6156. o[key] = value;
  6157. }
  6158. }
  6159. }
  6160. /**
  6161. * Add a node to a graph object. If there is already a node with
  6162. * the same id, their attributes will be merged.
  6163. * @param {Object} graph
  6164. * @param {Object} node
  6165. */
  6166. function addNode(graph, node) {
  6167. var nodes = graph.nodes;
  6168. if (!nodes) {
  6169. nodes = [];
  6170. graph.nodes = nodes;
  6171. }
  6172. // find existing node
  6173. var current = null;
  6174. for (var i = 0, len = nodes.length; i < len; i++) {
  6175. if (node.id === nodes[i].id) {
  6176. current = nodes[i];
  6177. break;
  6178. }
  6179. }
  6180. if (current) {
  6181. // merge attributes
  6182. if (node.attr) {
  6183. current.attr = merge(current.attr, node.attr);
  6184. }
  6185. }
  6186. else {
  6187. // add
  6188. graph.nodes.push(node);
  6189. if (graph.node) {
  6190. var attr = merge({}, graph.node); // clone global attributes
  6191. node.attr = merge(attr, node.attr); // merge attributes
  6192. }
  6193. }
  6194. }
  6195. /**
  6196. * Add an edge to a graph object
  6197. * @param {Object} graph
  6198. * @param {Object} edge
  6199. */
  6200. function addEdge(graph, edge) {
  6201. if (!graph.edges) {
  6202. graph.edges = [];
  6203. }
  6204. graph.edges.push(edge);
  6205. if (graph.edge) {
  6206. var attr = merge({}, graph.edge); // clone global attributes
  6207. edge.attr = merge(attr, edge.attr); // merge attributes
  6208. }
  6209. }
  6210. /**
  6211. * Create an edge to a graph object
  6212. * @param {Object} graph
  6213. * @param {String | Number | Object} from
  6214. * @param {String | Number | Object} to
  6215. * @param {String} type
  6216. * @param {Object | null} attr
  6217. * @return {Object} edge
  6218. */
  6219. function createEdge(graph, from, to, type, attr) {
  6220. var edge = {
  6221. from: from,
  6222. to: to,
  6223. type: type
  6224. };
  6225. if (graph.edge) {
  6226. edge.attr = merge({}, graph.edge); // clone global attributes
  6227. }
  6228. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  6229. return edge;
  6230. }
  6231. /**
  6232. * Get next token in the current dot file.
  6233. * The token and token type are available as token and tokenType
  6234. */
  6235. function getToken() {
  6236. tokenType = TOKENTYPE.NULL;
  6237. token = '';
  6238. // skip over whitespaces
  6239. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  6240. next();
  6241. }
  6242. do {
  6243. var isComment = false;
  6244. // skip comment
  6245. if (c == '#') {
  6246. // find the previous non-space character
  6247. var i = index - 1;
  6248. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  6249. i--;
  6250. }
  6251. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  6252. // the # is at the start of a line, this is indeed a line comment
  6253. while (c != '' && c != '\n') {
  6254. next();
  6255. }
  6256. isComment = true;
  6257. }
  6258. }
  6259. if (c == '/' && nextPreview() == '/') {
  6260. // skip line comment
  6261. while (c != '' && c != '\n') {
  6262. next();
  6263. }
  6264. isComment = true;
  6265. }
  6266. if (c == '/' && nextPreview() == '*') {
  6267. // skip block comment
  6268. while (c != '') {
  6269. if (c == '*' && nextPreview() == '/') {
  6270. // end of block comment found. skip these last two characters
  6271. next();
  6272. next();
  6273. break;
  6274. }
  6275. else {
  6276. next();
  6277. }
  6278. }
  6279. isComment = true;
  6280. }
  6281. // skip over whitespaces
  6282. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  6283. next();
  6284. }
  6285. }
  6286. while (isComment);
  6287. // check for end of dot file
  6288. if (c == '') {
  6289. // token is still empty
  6290. tokenType = TOKENTYPE.DELIMITER;
  6291. return;
  6292. }
  6293. // check for delimiters consisting of 2 characters
  6294. var c2 = c + nextPreview();
  6295. if (DELIMITERS[c2]) {
  6296. tokenType = TOKENTYPE.DELIMITER;
  6297. token = c2;
  6298. next();
  6299. next();
  6300. return;
  6301. }
  6302. // check for delimiters consisting of 1 character
  6303. if (DELIMITERS[c]) {
  6304. tokenType = TOKENTYPE.DELIMITER;
  6305. token = c;
  6306. next();
  6307. return;
  6308. }
  6309. // check for an identifier (number or string)
  6310. // TODO: more precise parsing of numbers/strings
  6311. if (isAlphaNumeric(c) || c == '-') {
  6312. token += c;
  6313. next();
  6314. while (isAlphaNumeric(c)) {
  6315. token += c;
  6316. next();
  6317. }
  6318. if (token == 'false') {
  6319. token = false; // cast to boolean
  6320. }
  6321. else if (token == 'true') {
  6322. token = true; // cast to boolean
  6323. }
  6324. else if (!isNaN(Number(token))) {
  6325. token = Number(token); // cast to number
  6326. }
  6327. tokenType = TOKENTYPE.IDENTIFIER;
  6328. return;
  6329. }
  6330. // check for a string enclosed by double quotes
  6331. if (c == '"') {
  6332. next();
  6333. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  6334. token += c;
  6335. if (c == '"') { // skip the escape character
  6336. next();
  6337. }
  6338. next();
  6339. }
  6340. if (c != '"') {
  6341. throw newSyntaxError('End of string " expected');
  6342. }
  6343. next();
  6344. tokenType = TOKENTYPE.IDENTIFIER;
  6345. return;
  6346. }
  6347. // something unknown is found, wrong characters, a syntax error
  6348. tokenType = TOKENTYPE.UNKNOWN;
  6349. while (c != '') {
  6350. token += c;
  6351. next();
  6352. }
  6353. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  6354. }
  6355. /**
  6356. * Parse a graph.
  6357. * @returns {Object} graph
  6358. */
  6359. function parseGraph() {
  6360. var graph = {};
  6361. first();
  6362. getToken();
  6363. // optional strict keyword
  6364. if (token == 'strict') {
  6365. graph.strict = true;
  6366. getToken();
  6367. }
  6368. // graph or digraph keyword
  6369. if (token == 'graph' || token == 'digraph') {
  6370. graph.type = token;
  6371. getToken();
  6372. }
  6373. // optional graph id
  6374. if (tokenType == TOKENTYPE.IDENTIFIER) {
  6375. graph.id = token;
  6376. getToken();
  6377. }
  6378. // open angle bracket
  6379. if (token != '{') {
  6380. throw newSyntaxError('Angle bracket { expected');
  6381. }
  6382. getToken();
  6383. // statements
  6384. parseStatements(graph);
  6385. // close angle bracket
  6386. if (token != '}') {
  6387. throw newSyntaxError('Angle bracket } expected');
  6388. }
  6389. getToken();
  6390. // end of file
  6391. if (token !== '') {
  6392. throw newSyntaxError('End of file expected');
  6393. }
  6394. getToken();
  6395. // remove temporary global properties
  6396. delete graph.node;
  6397. delete graph.edge;
  6398. return graph;
  6399. }
  6400. /**
  6401. * Parse a list with statements.
  6402. * @param {Object} graph
  6403. */
  6404. function parseStatements (graph) {
  6405. while (token !== '' && token != '}') {
  6406. parseStatement(graph);
  6407. if (token == ';') {
  6408. getToken();
  6409. }
  6410. }
  6411. }
  6412. /**
  6413. * Parse a single statement. Can be a an attribute statement, node
  6414. * statement, a series of node statements and edge statements, or a
  6415. * parameter.
  6416. * @param {Object} graph
  6417. */
  6418. function parseStatement(graph) {
  6419. // parse subgraph
  6420. var subgraph = parseSubgraph(graph);
  6421. if (subgraph) {
  6422. // edge statements
  6423. parseEdge(graph, subgraph);
  6424. return;
  6425. }
  6426. // parse an attribute statement
  6427. var attr = parseAttributeStatement(graph);
  6428. if (attr) {
  6429. return;
  6430. }
  6431. // parse node
  6432. if (tokenType != TOKENTYPE.IDENTIFIER) {
  6433. throw newSyntaxError('Identifier expected');
  6434. }
  6435. var id = token; // id can be a string or a number
  6436. getToken();
  6437. if (token == '=') {
  6438. // id statement
  6439. getToken();
  6440. if (!graph.attr) {
  6441. graph.attr = {};
  6442. }
  6443. if (tokenType != TOKENTYPE.IDENTIFIER) {
  6444. throw newSyntaxError('Identifier expected');
  6445. }
  6446. graph.attr[id] = token;
  6447. getToken();
  6448. // TODO: implement comma separated list with "ID=ID"
  6449. }
  6450. else {
  6451. parseNodeStatement(graph, id);
  6452. }
  6453. }
  6454. /**
  6455. * Parse a subgraph
  6456. * @param {Object} graph parent graph object
  6457. * @return {Object | null} subgraph
  6458. */
  6459. function parseSubgraph (graph) {
  6460. var subgraph = null;
  6461. // optional subgraph keyword
  6462. if (token == 'subgraph') {
  6463. subgraph = {};
  6464. subgraph.type = 'subgraph';
  6465. getToken();
  6466. // optional graph id
  6467. if (tokenType == TOKENTYPE.IDENTIFIER) {
  6468. subgraph.id = token;
  6469. getToken();
  6470. }
  6471. }
  6472. // open angle bracket
  6473. if (token == '{') {
  6474. getToken();
  6475. if (!subgraph) {
  6476. subgraph = {
  6477. type: 'subgraph'
  6478. };
  6479. }
  6480. // TODO: copy global node and edge attributes into subgraph or not?
  6481. // statements
  6482. parseStatements(subgraph);
  6483. // close angle bracket
  6484. if (token != '}') {
  6485. throw newSyntaxError('Angle bracket } expected');
  6486. }
  6487. getToken();
  6488. // remove temporary global properties
  6489. delete subgraph.node;
  6490. delete subgraph.edge;
  6491. // register at the parent graph
  6492. if (!graph.subgraphs) {
  6493. graph.subgraphs = [];
  6494. }
  6495. graph.subgraphs.push(subgraph);
  6496. graph.nodes = (graph.nodes || []).concat(subgraph.nodes || []);
  6497. }
  6498. return subgraph;
  6499. }
  6500. /**
  6501. * parse an attribute statement like "node [shape=circle fontSize=16]".
  6502. * Available keywords are 'node', 'edge', 'graph'
  6503. * @param {Object} graph
  6504. * @returns {Object | null} attr
  6505. */
  6506. function parseAttributeStatement (graph) {
  6507. var attr = null;
  6508. // attribute statements
  6509. if (token == 'node') {
  6510. getToken();
  6511. // node attributes
  6512. attr = parseAttributeList();
  6513. if (attr) {
  6514. graph.node = merge(graph.node, attr);
  6515. }
  6516. }
  6517. else if (token == 'edge') {
  6518. getToken();
  6519. // edge attributes
  6520. attr = parseAttributeList();
  6521. if (attr) {
  6522. graph.edge = merge(graph.edge, attr);
  6523. }
  6524. }
  6525. else if (token == 'graph') {
  6526. getToken();
  6527. // graph attributes
  6528. attr = parseAttributeList();
  6529. if (attr) {
  6530. graph.attr = merge(graph.attr, attr);
  6531. }
  6532. }
  6533. return attr;
  6534. }
  6535. /**
  6536. * parse a node statement
  6537. * @param {Object} graph
  6538. * @param {String | Number} id
  6539. */
  6540. function parseNodeStatement(graph, id) {
  6541. // node statement
  6542. var node = {
  6543. id: id
  6544. };
  6545. var attr = parseAttributeList();
  6546. if (attr) {
  6547. node.attr = attr;
  6548. }
  6549. addNode(graph, node);
  6550. // edge statements
  6551. parseEdge(graph, id);
  6552. }
  6553. /**
  6554. * Parse an edge or a series of edges
  6555. * @param {Object} graph
  6556. * @param {String | Number} from Id of the from node
  6557. */
  6558. function parseEdge(graph, from) {
  6559. while (token == '->' || token == '--') {
  6560. var to;
  6561. var type = token;
  6562. getToken();
  6563. var subgraph = parseSubgraph(graph);
  6564. if (subgraph) {
  6565. to = subgraph;
  6566. }
  6567. else {
  6568. if (tokenType != TOKENTYPE.IDENTIFIER) {
  6569. throw newSyntaxError('Identifier or subgraph expected');
  6570. }
  6571. to = token;
  6572. addNode(graph, {
  6573. id: to
  6574. });
  6575. getToken();
  6576. }
  6577. // parse edge attributes
  6578. var attr = parseAttributeList();
  6579. // create edge
  6580. var edge = createEdge(graph, from, to, type, attr);
  6581. addEdge(graph, edge);
  6582. from = to;
  6583. }
  6584. }
  6585. /**
  6586. * Parse a set with attributes,
  6587. * for example [label="1.000", shape=solid]
  6588. * @return {Object | null} attr
  6589. */
  6590. function parseAttributeList() {
  6591. var attr = null;
  6592. while (token == '[') {
  6593. getToken();
  6594. attr = {};
  6595. while (token !== '' && token != ']') {
  6596. if (tokenType != TOKENTYPE.IDENTIFIER) {
  6597. throw newSyntaxError('Attribute name expected');
  6598. }
  6599. var name = token;
  6600. getToken();
  6601. if (token != '=') {
  6602. throw newSyntaxError('Equal sign = expected');
  6603. }
  6604. getToken();
  6605. if (tokenType != TOKENTYPE.IDENTIFIER) {
  6606. throw newSyntaxError('Attribute value expected');
  6607. }
  6608. var value = token;
  6609. setValue(attr, name, value); // name can be a path
  6610. getToken();
  6611. if (token ==',') {
  6612. getToken();
  6613. }
  6614. }
  6615. if (token != ']') {
  6616. throw newSyntaxError('Bracket ] expected');
  6617. }
  6618. getToken();
  6619. }
  6620. return attr;
  6621. }
  6622. /**
  6623. * Create a syntax error with extra information on current token and index.
  6624. * @param {String} message
  6625. * @returns {SyntaxError} err
  6626. */
  6627. function newSyntaxError(message) {
  6628. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  6629. }
  6630. /**
  6631. * Chop off text after a maximum length
  6632. * @param {String} text
  6633. * @param {Number} maxLength
  6634. * @returns {String}
  6635. */
  6636. function chop (text, maxLength) {
  6637. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  6638. }
  6639. /**
  6640. * Execute a function fn for each pair of elements in two arrays
  6641. * @param {Array | *} array1
  6642. * @param {Array | *} array2
  6643. * @param {function} fn
  6644. */
  6645. function forEach2(array1, array2, fn) {
  6646. if (array1 instanceof Array) {
  6647. array1.forEach(function (elem1) {
  6648. if (array2 instanceof Array) {
  6649. array2.forEach(function (elem2) {
  6650. fn(elem1, elem2);
  6651. });
  6652. }
  6653. else {
  6654. fn(elem1, array2);
  6655. }
  6656. });
  6657. }
  6658. else {
  6659. if (array2 instanceof Array) {
  6660. array2.forEach(function (elem2) {
  6661. fn(array1, elem2);
  6662. });
  6663. }
  6664. else {
  6665. fn(array1, array2);
  6666. }
  6667. }
  6668. }
  6669. /**
  6670. * Convert a string containing a graph in DOT language into a map containing
  6671. * with nodes and edges in the format of graph.
  6672. * @param {String} data Text containing a graph in DOT-notation
  6673. * @return {Object} graphData
  6674. */
  6675. function DOTToGraph (data) {
  6676. // parse the DOT file
  6677. var dotData = parseDOT(data);
  6678. var graphData = {
  6679. nodes: [],
  6680. edges: [],
  6681. options: {}
  6682. };
  6683. // copy the nodes
  6684. if (dotData.nodes) {
  6685. dotData.nodes.forEach(function (dotNode) {
  6686. var graphNode = {
  6687. id: dotNode.id,
  6688. label: String(dotNode.label || dotNode.id)
  6689. };
  6690. merge(graphNode, dotNode.attr);
  6691. if (graphNode.image) {
  6692. graphNode.shape = 'image';
  6693. }
  6694. graphData.nodes.push(graphNode);
  6695. });
  6696. }
  6697. // copy the edges
  6698. if (dotData.edges) {
  6699. /**
  6700. * Convert an edge in DOT format to an edge with VisGraph format
  6701. * @param {Object} dotEdge
  6702. * @returns {Object} graphEdge
  6703. */
  6704. function convertEdge(dotEdge) {
  6705. var graphEdge = {
  6706. from: dotEdge.from,
  6707. to: dotEdge.to
  6708. };
  6709. merge(graphEdge, dotEdge.attr);
  6710. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  6711. return graphEdge;
  6712. }
  6713. dotData.edges.forEach(function (dotEdge) {
  6714. var from, to;
  6715. if (dotEdge.from instanceof Object) {
  6716. from = dotEdge.from.nodes;
  6717. }
  6718. else {
  6719. from = {
  6720. id: dotEdge.from
  6721. }
  6722. }
  6723. if (dotEdge.to instanceof Object) {
  6724. to = dotEdge.to.nodes;
  6725. }
  6726. else {
  6727. to = {
  6728. id: dotEdge.to
  6729. }
  6730. }
  6731. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  6732. dotEdge.from.edges.forEach(function (subEdge) {
  6733. var graphEdge = convertEdge(subEdge);
  6734. graphData.edges.push(graphEdge);
  6735. });
  6736. }
  6737. forEach2(from, to, function (from, to) {
  6738. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  6739. var graphEdge = convertEdge(subEdge);
  6740. graphData.edges.push(graphEdge);
  6741. });
  6742. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  6743. dotEdge.to.edges.forEach(function (subEdge) {
  6744. var graphEdge = convertEdge(subEdge);
  6745. graphData.edges.push(graphEdge);
  6746. });
  6747. }
  6748. });
  6749. }
  6750. // copy the options
  6751. if (dotData.attr) {
  6752. graphData.options = dotData.attr;
  6753. }
  6754. return graphData;
  6755. }
  6756. // exports
  6757. exports.parseDOT = parseDOT;
  6758. exports.DOTToGraph = DOTToGraph;
  6759. })(typeof util !== 'undefined' ? util : exports);
  6760. /**
  6761. * Canvas shapes used by the Graph
  6762. */
  6763. if (typeof CanvasRenderingContext2D !== 'undefined') {
  6764. /**
  6765. * Draw a circle shape
  6766. */
  6767. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  6768. this.beginPath();
  6769. this.arc(x, y, r, 0, 2*Math.PI, false);
  6770. };
  6771. /**
  6772. * Draw a square shape
  6773. * @param {Number} x horizontal center
  6774. * @param {Number} y vertical center
  6775. * @param {Number} r size, width and height of the square
  6776. */
  6777. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  6778. this.beginPath();
  6779. this.rect(x - r, y - r, r * 2, r * 2);
  6780. };
  6781. /**
  6782. * Draw a triangle shape
  6783. * @param {Number} x horizontal center
  6784. * @param {Number} y vertical center
  6785. * @param {Number} r radius, half the length of the sides of the triangle
  6786. */
  6787. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  6788. // http://en.wikipedia.org/wiki/Equilateral_triangle
  6789. this.beginPath();
  6790. var s = r * 2;
  6791. var s2 = s / 2;
  6792. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  6793. var h = Math.sqrt(s * s - s2 * s2); // height
  6794. this.moveTo(x, y - (h - ir));
  6795. this.lineTo(x + s2, y + ir);
  6796. this.lineTo(x - s2, y + ir);
  6797. this.lineTo(x, y - (h - ir));
  6798. this.closePath();
  6799. };
  6800. /**
  6801. * Draw a triangle shape in downward orientation
  6802. * @param {Number} x horizontal center
  6803. * @param {Number} y vertical center
  6804. * @param {Number} r radius
  6805. */
  6806. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  6807. // http://en.wikipedia.org/wiki/Equilateral_triangle
  6808. this.beginPath();
  6809. var s = r * 2;
  6810. var s2 = s / 2;
  6811. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  6812. var h = Math.sqrt(s * s - s2 * s2); // height
  6813. this.moveTo(x, y + (h - ir));
  6814. this.lineTo(x + s2, y - ir);
  6815. this.lineTo(x - s2, y - ir);
  6816. this.lineTo(x, y + (h - ir));
  6817. this.closePath();
  6818. };
  6819. /**
  6820. * Draw a star shape, a star with 5 points
  6821. * @param {Number} x horizontal center
  6822. * @param {Number} y vertical center
  6823. * @param {Number} r radius, half the length of the sides of the triangle
  6824. */
  6825. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  6826. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  6827. this.beginPath();
  6828. for (var n = 0; n < 10; n++) {
  6829. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  6830. this.lineTo(
  6831. x + radius * Math.sin(n * 2 * Math.PI / 10),
  6832. y - radius * Math.cos(n * 2 * Math.PI / 10)
  6833. );
  6834. }
  6835. this.closePath();
  6836. };
  6837. /**
  6838. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  6839. */
  6840. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  6841. var r2d = Math.PI/180;
  6842. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  6843. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  6844. this.beginPath();
  6845. this.moveTo(x+r,y);
  6846. this.lineTo(x+w-r,y);
  6847. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  6848. this.lineTo(x+w,y+h-r);
  6849. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  6850. this.lineTo(x+r,y+h);
  6851. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  6852. this.lineTo(x,y+r);
  6853. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  6854. };
  6855. /**
  6856. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  6857. */
  6858. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  6859. var kappa = .5522848,
  6860. ox = (w / 2) * kappa, // control point offset horizontal
  6861. oy = (h / 2) * kappa, // control point offset vertical
  6862. xe = x + w, // x-end
  6863. ye = y + h, // y-end
  6864. xm = x + w / 2, // x-middle
  6865. ym = y + h / 2; // y-middle
  6866. this.beginPath();
  6867. this.moveTo(x, ym);
  6868. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  6869. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  6870. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  6871. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  6872. };
  6873. /**
  6874. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  6875. */
  6876. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  6877. var f = 1/3;
  6878. var wEllipse = w;
  6879. var hEllipse = h * f;
  6880. var kappa = .5522848,
  6881. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  6882. oy = (hEllipse / 2) * kappa, // control point offset vertical
  6883. xe = x + wEllipse, // x-end
  6884. ye = y + hEllipse, // y-end
  6885. xm = x + wEllipse / 2, // x-middle
  6886. ym = y + hEllipse / 2, // y-middle
  6887. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  6888. yeb = y + h; // y-end, bottom ellipse
  6889. this.beginPath();
  6890. this.moveTo(xe, ym);
  6891. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  6892. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  6893. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  6894. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  6895. this.lineTo(xe, ymb);
  6896. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  6897. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  6898. this.lineTo(x, ym);
  6899. };
  6900. /**
  6901. * Draw an arrow point (no line)
  6902. */
  6903. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  6904. // tail
  6905. var xt = x - length * Math.cos(angle);
  6906. var yt = y - length * Math.sin(angle);
  6907. // inner tail
  6908. // TODO: allow to customize different shapes
  6909. var xi = x - length * 0.9 * Math.cos(angle);
  6910. var yi = y - length * 0.9 * Math.sin(angle);
  6911. // left
  6912. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  6913. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  6914. // right
  6915. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  6916. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  6917. this.beginPath();
  6918. this.moveTo(x, y);
  6919. this.lineTo(xl, yl);
  6920. this.lineTo(xi, yi);
  6921. this.lineTo(xr, yr);
  6922. this.closePath();
  6923. };
  6924. /**
  6925. * Sets up the dashedLine functionality for drawing
  6926. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  6927. * @author David Jordan
  6928. * @date 2012-08-08
  6929. */
  6930. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  6931. if (!dashArray) dashArray=[10,5];
  6932. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  6933. var dashCount = dashArray.length;
  6934. this.moveTo(x, y);
  6935. var dx = (x2-x), dy = (y2-y);
  6936. var slope = dy/dx;
  6937. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  6938. var dashIndex=0, draw=true;
  6939. while (distRemaining>=0.1){
  6940. var dashLength = dashArray[dashIndex++%dashCount];
  6941. if (dashLength > distRemaining) dashLength = distRemaining;
  6942. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  6943. if (dx<0) xStep = -xStep;
  6944. x += xStep;
  6945. y += slope*xStep;
  6946. this[draw ? 'lineTo' : 'moveTo'](x,y);
  6947. distRemaining -= dashLength;
  6948. draw = !draw;
  6949. }
  6950. };
  6951. // TODO: add diamond shape
  6952. }
  6953. /**
  6954. * @class Node
  6955. * A node. A node can be connected to other nodes via one or multiple edges.
  6956. * @param {object} properties An object containing properties for the node. All
  6957. * properties are optional, except for the id.
  6958. * {number} id Id of the node. Required
  6959. * {string} label Text label for the node
  6960. * {number} x Horizontal position of the node
  6961. * {number} y Vertical position of the node
  6962. * {string} shape Node shape, available:
  6963. * "database", "circle", "ellipse",
  6964. * "box", "image", "text", "dot",
  6965. * "star", "triangle", "triangleDown",
  6966. * "square"
  6967. * {string} image An image url
  6968. * {string} title An title text, can be HTML
  6969. * {anytype} group A group name or number
  6970. * @param {Graph.Images} imagelist A list with images. Only needed
  6971. * when the node has an image
  6972. * @param {Graph.Groups} grouplist A list with groups. Needed for
  6973. * retrieving group properties
  6974. * @param {Object} constants An object with default values for
  6975. * example for the color
  6976. */
  6977. function Node(properties, imagelist, grouplist, constants) {
  6978. this.selected = false;
  6979. this.edges = []; // all edges connected to this node
  6980. this.group = constants.nodes.group;
  6981. this.fontSize = constants.nodes.fontSize;
  6982. this.fontFace = constants.nodes.fontFace;
  6983. this.fontColor = constants.nodes.fontColor;
  6984. this.color = constants.nodes.color;
  6985. // set defaults for the properties
  6986. this.id = undefined;
  6987. this.shape = constants.nodes.shape;
  6988. this.image = constants.nodes.image;
  6989. this.x = 0;
  6990. this.y = 0;
  6991. this.xFixed = false;
  6992. this.yFixed = false;
  6993. this.radius = constants.nodes.radius;
  6994. this.radiusFixed = false;
  6995. this.radiusMin = constants.nodes.radiusMin;
  6996. this.radiusMax = constants.nodes.radiusMax;
  6997. this.imagelist = imagelist;
  6998. this.grouplist = grouplist;
  6999. this.setProperties(properties, constants);
  7000. // mass, force, velocity
  7001. this.mass = 50; // kg (mass is adjusted for the number of connected edges)
  7002. this.fx = 0.0; // external force x
  7003. this.fy = 0.0; // external force y
  7004. this.vx = 0.0; // velocity x
  7005. this.vy = 0.0; // velocity y
  7006. this.minForce = constants.minForce;
  7007. this.damping = 0.9; // damping factor
  7008. };
  7009. /**
  7010. * Attach a edge to the node
  7011. * @param {Edge} edge
  7012. */
  7013. Node.prototype.attachEdge = function(edge) {
  7014. this.edges.push(edge);
  7015. this._updateMass();
  7016. };
  7017. /**
  7018. * Detach a edge from the node
  7019. * @param {Edge} edge
  7020. */
  7021. Node.prototype.detachEdge = function(edge) {
  7022. var index = this.edges.indexOf(edge);
  7023. if (index != -1) {
  7024. this.edges.splice(index, 1);
  7025. }
  7026. this._updateMass();
  7027. };
  7028. /**
  7029. * Update the nodes mass, which is determined by the number of edges connecting
  7030. * to it (more edges -> heavier node).
  7031. * @private
  7032. */
  7033. Node.prototype._updateMass = function() {
  7034. this.mass = 50 + 20 * this.edges.length; // kg
  7035. };
  7036. /**
  7037. * Set or overwrite properties for the node
  7038. * @param {Object} properties an object with properties
  7039. * @param {Object} constants and object with default, global properties
  7040. */
  7041. Node.prototype.setProperties = function(properties, constants) {
  7042. if (!properties) {
  7043. return;
  7044. }
  7045. // basic properties
  7046. if (properties.id != undefined) {this.id = properties.id;}
  7047. if (properties.label != undefined) {this.label = properties.label;}
  7048. if (properties.title != undefined) {this.title = properties.title;}
  7049. if (properties.group != undefined) {this.group = properties.group;}
  7050. if (properties.x != undefined) {this.x = properties.x;}
  7051. if (properties.y != undefined) {this.y = properties.y;}
  7052. if (properties.value != undefined) {this.value = properties.value;}
  7053. if (this.id === undefined) {
  7054. throw "Node must have an id";
  7055. }
  7056. // copy group properties
  7057. if (this.group) {
  7058. var groupObj = this.grouplist.get(this.group);
  7059. for (var prop in groupObj) {
  7060. if (groupObj.hasOwnProperty(prop)) {
  7061. this[prop] = groupObj[prop];
  7062. }
  7063. }
  7064. }
  7065. // individual shape properties
  7066. if (properties.shape != undefined) {this.shape = properties.shape;}
  7067. if (properties.image != undefined) {this.image = properties.image;}
  7068. if (properties.radius != undefined) {this.radius = properties.radius;}
  7069. if (properties.color != undefined) {this.color = Node.parseColor(properties.color);}
  7070. if (properties.fontColor != undefined) {this.fontColor = properties.fontColor;}
  7071. if (properties.fontSize != undefined) {this.fontSize = properties.fontSize;}
  7072. if (properties.fontFace != undefined) {this.fontFace = properties.fontFace;}
  7073. if (this.image != undefined) {
  7074. if (this.imagelist) {
  7075. this.imageObj = this.imagelist.load(this.image);
  7076. }
  7077. else {
  7078. throw "No imagelist provided";
  7079. }
  7080. }
  7081. this.xFixed = this.xFixed || (properties.x != undefined);
  7082. this.yFixed = this.yFixed || (properties.y != undefined);
  7083. this.radiusFixed = this.radiusFixed || (properties.radius != undefined);
  7084. if (this.shape == 'image') {
  7085. this.radiusMin = constants.nodes.widthMin;
  7086. this.radiusMax = constants.nodes.widthMax;
  7087. }
  7088. // choose draw method depending on the shape
  7089. switch (this.shape) {
  7090. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  7091. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  7092. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  7093. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  7094. // TODO: add diamond shape
  7095. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  7096. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  7097. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  7098. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  7099. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  7100. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  7101. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  7102. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  7103. }
  7104. // reset the size of the node, this can be changed
  7105. this._reset();
  7106. };
  7107. /**
  7108. * Parse a color property into an object with border, background, and
  7109. * hightlight colors
  7110. * @param {Object | String} color
  7111. * @return {Object} colorObject
  7112. */
  7113. Node.parseColor = function(color) {
  7114. var c;
  7115. if (util.isString(color)) {
  7116. c = {
  7117. border: color,
  7118. background: color,
  7119. highlight: {
  7120. border: color,
  7121. background: color
  7122. }
  7123. };
  7124. // TODO: automatically generate a nice highlight color
  7125. }
  7126. else {
  7127. c = {};
  7128. c.background = color.background || 'white';
  7129. c.border = color.border || c.background;
  7130. if (util.isString(color.highlight)) {
  7131. c.highlight = {
  7132. border: color.highlight,
  7133. background: color.highlight
  7134. }
  7135. }
  7136. else {
  7137. c.highlight = {};
  7138. c.highlight.background = color.highlight && color.highlight.background || c.background;
  7139. c.highlight.border = color.highlight && color.highlight.border || c.border;
  7140. }
  7141. }
  7142. return c;
  7143. };
  7144. /**
  7145. * select this node
  7146. */
  7147. Node.prototype.select = function() {
  7148. this.selected = true;
  7149. this._reset();
  7150. };
  7151. /**
  7152. * unselect this node
  7153. */
  7154. Node.prototype.unselect = function() {
  7155. this.selected = false;
  7156. this._reset();
  7157. };
  7158. /**
  7159. * Reset the calculated size of the node, forces it to recalculate its size
  7160. * @private
  7161. */
  7162. Node.prototype._reset = function() {
  7163. this.width = undefined;
  7164. this.height = undefined;
  7165. };
  7166. /**
  7167. * get the title of this node.
  7168. * @return {string} title The title of the node, or undefined when no title
  7169. * has been set.
  7170. */
  7171. Node.prototype.getTitle = function() {
  7172. return this.title;
  7173. };
  7174. /**
  7175. * Calculate the distance to the border of the Node
  7176. * @param {CanvasRenderingContext2D} ctx
  7177. * @param {Number} angle Angle in radians
  7178. * @returns {number} distance Distance to the border in pixels
  7179. */
  7180. Node.prototype.distanceToBorder = function (ctx, angle) {
  7181. var borderWidth = 1;
  7182. if (!this.width) {
  7183. this.resize(ctx);
  7184. }
  7185. //noinspection FallthroughInSwitchStatementJS
  7186. switch (this.shape) {
  7187. case 'circle':
  7188. case 'dot':
  7189. return this.radius + borderWidth;
  7190. case 'ellipse':
  7191. var a = this.width / 2;
  7192. var b = this.height / 2;
  7193. var w = (Math.sin(angle) * a);
  7194. var h = (Math.cos(angle) * b);
  7195. return a * b / Math.sqrt(w * w + h * h);
  7196. // TODO: implement distanceToBorder for database
  7197. // TODO: implement distanceToBorder for triangle
  7198. // TODO: implement distanceToBorder for triangleDown
  7199. case 'box':
  7200. case 'image':
  7201. case 'text':
  7202. default:
  7203. if (this.width) {
  7204. return Math.min(
  7205. Math.abs(this.width / 2 / Math.cos(angle)),
  7206. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  7207. // TODO: reckon with border radius too in case of box
  7208. }
  7209. else {
  7210. return 0;
  7211. }
  7212. }
  7213. // TODO: implement calculation of distance to border for all shapes
  7214. };
  7215. /**
  7216. * Set forces acting on the node
  7217. * @param {number} fx Force in horizontal direction
  7218. * @param {number} fy Force in vertical direction
  7219. */
  7220. Node.prototype._setForce = function(fx, fy) {
  7221. this.fx = fx;
  7222. this.fy = fy;
  7223. };
  7224. /**
  7225. * Add forces acting on the node
  7226. * @param {number} fx Force in horizontal direction
  7227. * @param {number} fy Force in vertical direction
  7228. * @private
  7229. */
  7230. Node.prototype._addForce = function(fx, fy) {
  7231. this.fx += fx;
  7232. this.fy += fy;
  7233. };
  7234. /**
  7235. * Perform one discrete step for the node
  7236. * @param {number} interval Time interval in seconds
  7237. */
  7238. Node.prototype.discreteStep = function(interval) {
  7239. if (!this.xFixed) {
  7240. var dx = -this.damping * this.vx; // damping force
  7241. var ax = (this.fx + dx) / this.mass; // acceleration
  7242. this.vx += ax / interval; // velocity
  7243. this.x += this.vx / interval; // position
  7244. }
  7245. if (!this.yFixed) {
  7246. var dy = -this.damping * this.vy; // damping force
  7247. var ay = (this.fy + dy) / this.mass; // acceleration
  7248. this.vy += ay / interval; // velocity
  7249. this.y += this.vy / interval; // position
  7250. }
  7251. };
  7252. /**
  7253. * Check if this node has a fixed x and y position
  7254. * @return {boolean} true if fixed, false if not
  7255. */
  7256. Node.prototype.isFixed = function() {
  7257. return (this.xFixed && this.yFixed);
  7258. };
  7259. /**
  7260. * Check if this node is moving
  7261. * @param {number} vmin the minimum velocity considered as "moving"
  7262. * @return {boolean} true if moving, false if it has no velocity
  7263. */
  7264. // TODO: replace this method with calculating the kinetic energy
  7265. Node.prototype.isMoving = function(vmin) {
  7266. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin ||
  7267. (!this.xFixed && Math.abs(this.fx) > this.minForce) ||
  7268. (!this.yFixed && Math.abs(this.fy) > this.minForce));
  7269. };
  7270. /**
  7271. * check if this node is selecte
  7272. * @return {boolean} selected True if node is selected, else false
  7273. */
  7274. Node.prototype.isSelected = function() {
  7275. return this.selected;
  7276. };
  7277. /**
  7278. * Retrieve the value of the node. Can be undefined
  7279. * @return {Number} value
  7280. */
  7281. Node.prototype.getValue = function() {
  7282. return this.value;
  7283. };
  7284. /**
  7285. * Calculate the distance from the nodes location to the given location (x,y)
  7286. * @param {Number} x
  7287. * @param {Number} y
  7288. * @return {Number} value
  7289. */
  7290. Node.prototype.getDistance = function(x, y) {
  7291. var dx = this.x - x,
  7292. dy = this.y - y;
  7293. return Math.sqrt(dx * dx + dy * dy);
  7294. };
  7295. /**
  7296. * Adjust the value range of the node. The node will adjust it's radius
  7297. * based on its value.
  7298. * @param {Number} min
  7299. * @param {Number} max
  7300. */
  7301. Node.prototype.setValueRange = function(min, max) {
  7302. if (!this.radiusFixed && this.value !== undefined) {
  7303. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  7304. this.radius = (this.value - min) * scale + this.radiusMin;
  7305. }
  7306. };
  7307. /**
  7308. * Draw this node in the given canvas
  7309. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  7310. * @param {CanvasRenderingContext2D} ctx
  7311. */
  7312. Node.prototype.draw = function(ctx) {
  7313. throw "Draw method not initialized for node";
  7314. };
  7315. /**
  7316. * Recalculate the size of this node in the given canvas
  7317. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  7318. * @param {CanvasRenderingContext2D} ctx
  7319. */
  7320. Node.prototype.resize = function(ctx) {
  7321. throw "Resize method not initialized for node";
  7322. };
  7323. /**
  7324. * Check if this object is overlapping with the provided object
  7325. * @param {Object} obj an object with parameters left, top, right, bottom
  7326. * @return {boolean} True if location is located on node
  7327. */
  7328. Node.prototype.isOverlappingWith = function(obj) {
  7329. return (this.left < obj.right &&
  7330. this.left + this.width > obj.left &&
  7331. this.top < obj.bottom &&
  7332. this.top + this.height > obj.top);
  7333. };
  7334. Node.prototype._resizeImage = function (ctx) {
  7335. // TODO: pre calculate the image size
  7336. if (!this.width) { // undefined or 0
  7337. var width, height;
  7338. if (this.value) {
  7339. var scale = this.imageObj.height / this.imageObj.width;
  7340. width = this.radius || this.imageObj.width;
  7341. height = this.radius * scale || this.imageObj.height;
  7342. }
  7343. else {
  7344. width = this.imageObj.width;
  7345. height = this.imageObj.height;
  7346. }
  7347. this.width = width;
  7348. this.height = height;
  7349. }
  7350. };
  7351. Node.prototype._drawImage = function (ctx) {
  7352. this._resizeImage(ctx);
  7353. this.left = this.x - this.width / 2;
  7354. this.top = this.y - this.height / 2;
  7355. var yLabel;
  7356. if (this.imageObj) {
  7357. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  7358. yLabel = this.y + this.height / 2;
  7359. }
  7360. else {
  7361. // image still loading... just draw the label for now
  7362. yLabel = this.y;
  7363. }
  7364. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  7365. };
  7366. Node.prototype._resizeBox = function (ctx) {
  7367. if (!this.width) {
  7368. var margin = 5;
  7369. var textSize = this.getTextSize(ctx);
  7370. this.width = textSize.width + 2 * margin;
  7371. this.height = textSize.height + 2 * margin;
  7372. }
  7373. };
  7374. Node.prototype._drawBox = function (ctx) {
  7375. this._resizeBox(ctx);
  7376. this.left = this.x - this.width / 2;
  7377. this.top = this.y - this.height / 2;
  7378. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  7379. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  7380. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  7381. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  7382. ctx.fill();
  7383. ctx.stroke();
  7384. this._label(ctx, this.label, this.x, this.y);
  7385. };
  7386. Node.prototype._resizeDatabase = function (ctx) {
  7387. if (!this.width) {
  7388. var margin = 5;
  7389. var textSize = this.getTextSize(ctx);
  7390. var size = textSize.width + 2 * margin;
  7391. this.width = size;
  7392. this.height = size;
  7393. }
  7394. };
  7395. Node.prototype._drawDatabase = function (ctx) {
  7396. this._resizeDatabase(ctx);
  7397. this.left = this.x - this.width / 2;
  7398. this.top = this.y - this.height / 2;
  7399. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  7400. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  7401. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  7402. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  7403. ctx.fill();
  7404. ctx.stroke();
  7405. this._label(ctx, this.label, this.x, this.y);
  7406. };
  7407. Node.prototype._resizeCircle = function (ctx) {
  7408. if (!this.width) {
  7409. var margin = 5;
  7410. var textSize = this.getTextSize(ctx);
  7411. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  7412. this.radius = diameter / 2;
  7413. this.width = diameter;
  7414. this.height = diameter;
  7415. }
  7416. };
  7417. Node.prototype._drawCircle = function (ctx) {
  7418. this._resizeCircle(ctx);
  7419. this.left = this.x - this.width / 2;
  7420. this.top = this.y - this.height / 2;
  7421. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  7422. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  7423. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  7424. ctx.circle(this.x, this.y, this.radius);
  7425. ctx.fill();
  7426. ctx.stroke();
  7427. this._label(ctx, this.label, this.x, this.y);
  7428. };
  7429. Node.prototype._resizeEllipse = function (ctx) {
  7430. if (!this.width) {
  7431. var textSize = this.getTextSize(ctx);
  7432. this.width = textSize.width * 1.5;
  7433. this.height = textSize.height * 2;
  7434. if (this.width < this.height) {
  7435. this.width = this.height;
  7436. }
  7437. }
  7438. };
  7439. Node.prototype._drawEllipse = function (ctx) {
  7440. this._resizeEllipse(ctx);
  7441. this.left = this.x - this.width / 2;
  7442. this.top = this.y - this.height / 2;
  7443. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  7444. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  7445. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  7446. ctx.ellipse(this.left, this.top, this.width, this.height);
  7447. ctx.fill();
  7448. ctx.stroke();
  7449. this._label(ctx, this.label, this.x, this.y);
  7450. };
  7451. Node.prototype._drawDot = function (ctx) {
  7452. this._drawShape(ctx, 'circle');
  7453. };
  7454. Node.prototype._drawTriangle = function (ctx) {
  7455. this._drawShape(ctx, 'triangle');
  7456. };
  7457. Node.prototype._drawTriangleDown = function (ctx) {
  7458. this._drawShape(ctx, 'triangleDown');
  7459. };
  7460. Node.prototype._drawSquare = function (ctx) {
  7461. this._drawShape(ctx, 'square');
  7462. };
  7463. Node.prototype._drawStar = function (ctx) {
  7464. this._drawShape(ctx, 'star');
  7465. };
  7466. Node.prototype._resizeShape = function (ctx) {
  7467. if (!this.width) {
  7468. var size = 2 * this.radius;
  7469. this.width = size;
  7470. this.height = size;
  7471. }
  7472. };
  7473. Node.prototype._drawShape = function (ctx, shape) {
  7474. this._resizeShape(ctx);
  7475. this.left = this.x - this.width / 2;
  7476. this.top = this.y - this.height / 2;
  7477. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  7478. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  7479. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  7480. ctx[shape](this.x, this.y, this.radius);
  7481. ctx.fill();
  7482. ctx.stroke();
  7483. if (this.label) {
  7484. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  7485. }
  7486. };
  7487. Node.prototype._resizeText = function (ctx) {
  7488. if (!this.width) {
  7489. var margin = 5;
  7490. var textSize = this.getTextSize(ctx);
  7491. this.width = textSize.width + 2 * margin;
  7492. this.height = textSize.height + 2 * margin;
  7493. }
  7494. };
  7495. Node.prototype._drawText = function (ctx) {
  7496. this._resizeText(ctx);
  7497. this.left = this.x - this.width / 2;
  7498. this.top = this.y - this.height / 2;
  7499. this._label(ctx, this.label, this.x, this.y);
  7500. };
  7501. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  7502. if (text) {
  7503. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  7504. ctx.fillStyle = this.fontColor || "black";
  7505. ctx.textAlign = align || "center";
  7506. ctx.textBaseline = baseline || "middle";
  7507. var lines = text.split('\n'),
  7508. lineCount = lines.length,
  7509. fontSize = (this.fontSize + 4),
  7510. yLine = y + (1 - lineCount) / 2 * fontSize;
  7511. for (var i = 0; i < lineCount; i++) {
  7512. ctx.fillText(lines[i], x, yLine);
  7513. yLine += fontSize;
  7514. }
  7515. }
  7516. };
  7517. Node.prototype.getTextSize = function(ctx) {
  7518. if (this.label != undefined) {
  7519. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  7520. var lines = this.label.split('\n'),
  7521. height = (this.fontSize + 4) * lines.length,
  7522. width = 0;
  7523. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  7524. width = Math.max(width, ctx.measureText(lines[i]).width);
  7525. }
  7526. return {"width": width, "height": height};
  7527. }
  7528. else {
  7529. return {"width": 0, "height": 0};
  7530. }
  7531. };
  7532. /**
  7533. * @class Edge
  7534. *
  7535. * A edge connects two nodes
  7536. * @param {Object} properties Object with properties. Must contain
  7537. * At least properties from and to.
  7538. * Available properties: from (number),
  7539. * to (number), label (string, color (string),
  7540. * width (number), style (string),
  7541. * length (number), title (string)
  7542. * @param {Graph} graph A graph object, used to find and edge to
  7543. * nodes.
  7544. * @param {Object} constants An object with default values for
  7545. * example for the color
  7546. */
  7547. function Edge (properties, graph, constants) {
  7548. if (!graph) {
  7549. throw "No graph provided";
  7550. }
  7551. this.graph = graph;
  7552. // initialize constants
  7553. this.widthMin = constants.edges.widthMin;
  7554. this.widthMax = constants.edges.widthMax;
  7555. // initialize variables
  7556. this.id = undefined;
  7557. this.style = constants.edges.style;
  7558. this.title = undefined;
  7559. this.width = constants.edges.width;
  7560. this.value = undefined;
  7561. this.length = constants.edges.length;
  7562. // Added to support dashed lines
  7563. // David Jordan
  7564. // 2012-08-08
  7565. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gaph, altLength
  7566. this.stiffness = undefined; // depends on the length of the edge
  7567. this.color = constants.edges.color;
  7568. this.widthFixed = false;
  7569. this.lengthFixed = false;
  7570. this.setProperties(properties, constants);
  7571. };
  7572. /**
  7573. * Set or overwrite properties for the edge
  7574. * @param {Object} properties an object with properties
  7575. * @param {Object} constants and object with default, global properties
  7576. */
  7577. Edge.prototype.setProperties = function(properties, constants) {
  7578. if (!properties) {
  7579. return;
  7580. }
  7581. if (properties.from != undefined) {this.from = this.graph._getNode(properties.from);}
  7582. if (properties.to != undefined) {this.to = this.graph._getNode(properties.to);}
  7583. if (properties.id != undefined) {this.id = properties.id;}
  7584. if (properties.style != undefined) {this.style = properties.style;}
  7585. if (properties.label != undefined) {this.label = properties.label;}
  7586. if (this.label) {
  7587. this.fontSize = constants.edges.fontSize;
  7588. this.fontFace = constants.edges.fontFace;
  7589. this.fontColor = constants.edges.fontColor;
  7590. if (properties.fontColor != undefined) {this.fontColor = properties.fontColor;}
  7591. if (properties.fontSize != undefined) {this.fontSize = properties.fontSize;}
  7592. if (properties.fontFace != undefined) {this.fontFace = properties.fontFace;}
  7593. }
  7594. if (properties.title != undefined) {this.title = properties.title;}
  7595. if (properties.width != undefined) {this.width = properties.width;}
  7596. if (properties.value != undefined) {this.value = properties.value;}
  7597. if (properties.length != undefined) {this.length = properties.length;}
  7598. // Added to support dashed lines
  7599. // David Jordan
  7600. // 2012-08-08
  7601. if (properties.dash) {
  7602. if (properties.dash.length != undefined) {this.dash.length = properties.dash.length;}
  7603. if (properties.dash.gap != undefined) {this.dash.gap = properties.dash.gap;}
  7604. if (properties.dash.altLength != undefined) {this.dash.altLength = properties.dash.altLength;}
  7605. }
  7606. if (properties.color != undefined) {this.color = properties.color;}
  7607. if (!this.from) {
  7608. throw "Node with id " + properties.from + " not found";
  7609. }
  7610. if (!this.to) {
  7611. throw "Node with id " + properties.to + " not found";
  7612. }
  7613. this.widthFixed = this.widthFixed || (properties.width != undefined);
  7614. this.lengthFixed = this.lengthFixed || (properties.length != undefined);
  7615. this.stiffness = 1 / this.length;
  7616. // set draw method based on style
  7617. switch (this.style) {
  7618. case 'line': this.draw = this._drawLine; break;
  7619. case 'arrow': this.draw = this._drawArrow; break;
  7620. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  7621. case 'dash-line': this.draw = this._drawDashLine; break;
  7622. default: this.draw = this._drawLine; break;
  7623. }
  7624. };
  7625. /**
  7626. * get the title of this edge.
  7627. * @return {string} title The title of the edge, or undefined when no title
  7628. * has been set.
  7629. */
  7630. Edge.prototype.getTitle = function() {
  7631. return this.title;
  7632. };
  7633. /**
  7634. * Retrieve the value of the edge. Can be undefined
  7635. * @return {Number} value
  7636. */
  7637. Edge.prototype.getValue = function() {
  7638. return this.value;
  7639. };
  7640. /**
  7641. * Adjust the value range of the edge. The edge will adjust it's width
  7642. * based on its value.
  7643. * @param {Number} min
  7644. * @param {Number} max
  7645. */
  7646. Edge.prototype.setValueRange = function(min, max) {
  7647. if (!this.widthFixed && this.value !== undefined) {
  7648. var factor = (this.widthMax - this.widthMin) / (max - min);
  7649. this.width = (this.value - min) * factor + this.widthMin;
  7650. }
  7651. };
  7652. /**
  7653. * Redraw a edge
  7654. * Draw this edge in the given canvas
  7655. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  7656. * @param {CanvasRenderingContext2D} ctx
  7657. */
  7658. Edge.prototype.draw = function(ctx) {
  7659. throw "Method draw not initialized in edge";
  7660. };
  7661. /**
  7662. * Check if this object is overlapping with the provided object
  7663. * @param {Object} obj an object with parameters left, top
  7664. * @return {boolean} True if location is located on the edge
  7665. */
  7666. Edge.prototype.isOverlappingWith = function(obj) {
  7667. var distMax = 10;
  7668. var xFrom = this.from.x;
  7669. var yFrom = this.from.y;
  7670. var xTo = this.to.x;
  7671. var yTo = this.to.y;
  7672. var xObj = obj.left;
  7673. var yObj = obj.top;
  7674. var dist = Edge._dist(xFrom, yFrom, xTo, yTo, xObj, yObj);
  7675. return (dist < distMax);
  7676. };
  7677. /**
  7678. * Redraw a edge as a line
  7679. * Draw this edge in the given canvas
  7680. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  7681. * @param {CanvasRenderingContext2D} ctx
  7682. * @private
  7683. */
  7684. Edge.prototype._drawLine = function(ctx) {
  7685. // set style
  7686. ctx.strokeStyle = this.color;
  7687. ctx.lineWidth = this._getLineWidth();
  7688. var point;
  7689. if (this.from != this.to) {
  7690. // draw line
  7691. this._line(ctx);
  7692. // draw label
  7693. if (this.label) {
  7694. point = this._pointOnLine(0.5);
  7695. this._label(ctx, this.label, point.x, point.y);
  7696. }
  7697. }
  7698. else {
  7699. var x, y;
  7700. var radius = this.length / 4;
  7701. var node = this.from;
  7702. if (!node.width) {
  7703. node.resize(ctx);
  7704. }
  7705. if (node.width > node.height) {
  7706. x = node.x + node.width / 2;
  7707. y = node.y - radius;
  7708. }
  7709. else {
  7710. x = node.x + radius;
  7711. y = node.y - node.height / 2;
  7712. }
  7713. this._circle(ctx, x, y, radius);
  7714. point = this._pointOnCircle(x, y, radius, 0.5);
  7715. this._label(ctx, this.label, point.x, point.y);
  7716. }
  7717. };
  7718. /**
  7719. * Get the line width of the edge. Depends on width and whether one of the
  7720. * connected nodes is selected.
  7721. * @return {Number} width
  7722. * @private
  7723. */
  7724. Edge.prototype._getLineWidth = function() {
  7725. if (this.from.selected || this.to.selected) {
  7726. return Math.min(this.width * 2, this.widthMax);
  7727. }
  7728. else {
  7729. return this.width;
  7730. }
  7731. };
  7732. /**
  7733. * Draw a line between two nodes
  7734. * @param {CanvasRenderingContext2D} ctx
  7735. * @private
  7736. */
  7737. Edge.prototype._line = function (ctx) {
  7738. // draw a straight line
  7739. ctx.beginPath();
  7740. ctx.moveTo(this.from.x, this.from.y);
  7741. ctx.lineTo(this.to.x, this.to.y);
  7742. ctx.stroke();
  7743. };
  7744. /**
  7745. * Draw a line from a node to itself, a circle
  7746. * @param {CanvasRenderingContext2D} ctx
  7747. * @param {Number} x
  7748. * @param {Number} y
  7749. * @param {Number} radius
  7750. * @private
  7751. */
  7752. Edge.prototype._circle = function (ctx, x, y, radius) {
  7753. // draw a circle
  7754. ctx.beginPath();
  7755. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  7756. ctx.stroke();
  7757. };
  7758. /**
  7759. * Draw label with white background and with the middle at (x, y)
  7760. * @param {CanvasRenderingContext2D} ctx
  7761. * @param {String} text
  7762. * @param {Number} x
  7763. * @param {Number} y
  7764. * @private
  7765. */
  7766. Edge.prototype._label = function (ctx, text, x, y) {
  7767. if (text) {
  7768. // TODO: cache the calculated size
  7769. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  7770. this.fontSize + "px " + this.fontFace;
  7771. ctx.fillStyle = 'white';
  7772. var width = ctx.measureText(text).width;
  7773. var height = this.fontSize;
  7774. var left = x - width / 2;
  7775. var top = y - height / 2;
  7776. ctx.fillRect(left, top, width, height);
  7777. // draw text
  7778. ctx.fillStyle = this.fontColor || "black";
  7779. ctx.textAlign = "left";
  7780. ctx.textBaseline = "top";
  7781. ctx.fillText(text, left, top);
  7782. }
  7783. };
  7784. /**
  7785. * Redraw a edge as a dashed line
  7786. * Draw this edge in the given canvas
  7787. * @author David Jordan
  7788. * @date 2012-08-08
  7789. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  7790. * @param {CanvasRenderingContext2D} ctx
  7791. * @private
  7792. */
  7793. Edge.prototype._drawDashLine = function(ctx) {
  7794. // set style
  7795. ctx.strokeStyle = this.color;
  7796. ctx.lineWidth = this._getLineWidth();
  7797. // draw dashed line
  7798. ctx.beginPath();
  7799. ctx.lineCap = 'round';
  7800. if (this.dash.altLength != undefined) //If an alt dash value has been set add to the array this value
  7801. {
  7802. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  7803. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  7804. }
  7805. 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
  7806. {
  7807. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  7808. [this.dash.length,this.dash.gap]);
  7809. }
  7810. else //If all else fails draw a line
  7811. {
  7812. ctx.moveTo(this.from.x, this.from.y);
  7813. ctx.lineTo(this.to.x, this.to.y);
  7814. }
  7815. ctx.stroke();
  7816. // draw label
  7817. if (this.label) {
  7818. var point = this._pointOnLine(0.5);
  7819. this._label(ctx, this.label, point.x, point.y);
  7820. }
  7821. };
  7822. /**
  7823. * Get a point on a line
  7824. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  7825. * @return {Object} point
  7826. * @private
  7827. */
  7828. Edge.prototype._pointOnLine = function (percentage) {
  7829. return {
  7830. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  7831. y: (1 - percentage) * this.from.y + percentage * this.to.y
  7832. }
  7833. };
  7834. /**
  7835. * Get a point on a circle
  7836. * @param {Number} x
  7837. * @param {Number} y
  7838. * @param {Number} radius
  7839. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  7840. * @return {Object} point
  7841. * @private
  7842. */
  7843. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  7844. var angle = (percentage - 3/8) * 2 * Math.PI;
  7845. return {
  7846. x: x + radius * Math.cos(angle),
  7847. y: y - radius * Math.sin(angle)
  7848. }
  7849. };
  7850. /**
  7851. * Redraw a edge as a line with an arrow halfway the line
  7852. * Draw this edge in the given canvas
  7853. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  7854. * @param {CanvasRenderingContext2D} ctx
  7855. * @private
  7856. */
  7857. Edge.prototype._drawArrowCenter = function(ctx) {
  7858. var point;
  7859. // set style
  7860. ctx.strokeStyle = this.color;
  7861. ctx.fillStyle = this.color;
  7862. ctx.lineWidth = this._getLineWidth();
  7863. if (this.from != this.to) {
  7864. // draw line
  7865. this._line(ctx);
  7866. // draw an arrow halfway the line
  7867. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  7868. var length = 10 + 5 * this.width; // TODO: make customizable?
  7869. point = this._pointOnLine(0.5);
  7870. ctx.arrow(point.x, point.y, angle, length);
  7871. ctx.fill();
  7872. ctx.stroke();
  7873. // draw label
  7874. if (this.label) {
  7875. point = this._pointOnLine(0.5);
  7876. this._label(ctx, this.label, point.x, point.y);
  7877. }
  7878. }
  7879. else {
  7880. // draw circle
  7881. var x, y;
  7882. var radius = this.length / 4;
  7883. var node = this.from;
  7884. if (!node.width) {
  7885. node.resize(ctx);
  7886. }
  7887. if (node.width > node.height) {
  7888. x = node.x + node.width / 2;
  7889. y = node.y - radius;
  7890. }
  7891. else {
  7892. x = node.x + radius;
  7893. y = node.y - node.height / 2;
  7894. }
  7895. this._circle(ctx, x, y, radius);
  7896. // draw all arrows
  7897. var angle = 0.2 * Math.PI;
  7898. var length = 10 + 5 * this.width; // TODO: make customizable?
  7899. point = this._pointOnCircle(x, y, radius, 0.5);
  7900. ctx.arrow(point.x, point.y, angle, length);
  7901. ctx.fill();
  7902. ctx.stroke();
  7903. // draw label
  7904. if (this.label) {
  7905. point = this._pointOnCircle(x, y, radius, 0.5);
  7906. this._label(ctx, this.label, point.x, point.y);
  7907. }
  7908. }
  7909. };
  7910. /**
  7911. * Redraw a edge as a line with an arrow
  7912. * Draw this edge in the given canvas
  7913. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  7914. * @param {CanvasRenderingContext2D} ctx
  7915. * @private
  7916. */
  7917. Edge.prototype._drawArrow = function(ctx) {
  7918. // set style
  7919. ctx.strokeStyle = this.color;
  7920. ctx.fillStyle = this.color;
  7921. ctx.lineWidth = this._getLineWidth();
  7922. // draw line
  7923. var angle, length;
  7924. if (this.from != this.to) {
  7925. // calculate length and angle of the line
  7926. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  7927. var dx = (this.to.x - this.from.x);
  7928. var dy = (this.to.y - this.from.y);
  7929. var lEdge = Math.sqrt(dx * dx + dy * dy);
  7930. var lFrom = this.from.distanceToBorder(ctx, angle + Math.PI);
  7931. var pFrom = (lEdge - lFrom) / lEdge;
  7932. var xFrom = (pFrom) * this.from.x + (1 - pFrom) * this.to.x;
  7933. var yFrom = (pFrom) * this.from.y + (1 - pFrom) * this.to.y;
  7934. var lTo = this.to.distanceToBorder(ctx, angle);
  7935. var pTo = (lEdge - lTo) / lEdge;
  7936. var xTo = (1 - pTo) * this.from.x + pTo * this.to.x;
  7937. var yTo = (1 - pTo) * this.from.y + pTo * this.to.y;
  7938. ctx.beginPath();
  7939. ctx.moveTo(xFrom, yFrom);
  7940. ctx.lineTo(xTo, yTo);
  7941. ctx.stroke();
  7942. // draw arrow at the end of the line
  7943. length = 10 + 5 * this.width; // TODO: make customizable?
  7944. ctx.arrow(xTo, yTo, angle, length);
  7945. ctx.fill();
  7946. ctx.stroke();
  7947. // draw label
  7948. if (this.label) {
  7949. var point = this._pointOnLine(0.5);
  7950. this._label(ctx, this.label, point.x, point.y);
  7951. }
  7952. }
  7953. else {
  7954. // draw circle
  7955. var node = this.from;
  7956. var x, y, arrow;
  7957. var radius = this.length / 4;
  7958. if (!node.width) {
  7959. node.resize(ctx);
  7960. }
  7961. if (node.width > node.height) {
  7962. x = node.x + node.width / 2;
  7963. y = node.y - radius;
  7964. arrow = {
  7965. x: x,
  7966. y: node.y,
  7967. angle: 0.9 * Math.PI
  7968. };
  7969. }
  7970. else {
  7971. x = node.x + radius;
  7972. y = node.y - node.height / 2;
  7973. arrow = {
  7974. x: node.x,
  7975. y: y,
  7976. angle: 0.6 * Math.PI
  7977. };
  7978. }
  7979. ctx.beginPath();
  7980. // TODO: do not draw a circle, but an arc
  7981. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  7982. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  7983. ctx.stroke();
  7984. // draw all arrows
  7985. length = 10 + 5 * this.width; // TODO: make customizable?
  7986. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  7987. ctx.fill();
  7988. ctx.stroke();
  7989. // draw label
  7990. if (this.label) {
  7991. point = this._pointOnCircle(x, y, radius, 0.5);
  7992. this._label(ctx, this.label, point.x, point.y);
  7993. }
  7994. }
  7995. };
  7996. /**
  7997. * Calculate the distance between a point (x3,y3) and a line segment from
  7998. * (x1,y1) to (x2,y2).
  7999. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  8000. * @param {number} x1
  8001. * @param {number} y1
  8002. * @param {number} x2
  8003. * @param {number} y2
  8004. * @param {number} x3
  8005. * @param {number} y3
  8006. * @private
  8007. */
  8008. Edge._dist = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  8009. var px = x2-x1,
  8010. py = y2-y1,
  8011. something = px*px + py*py,
  8012. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  8013. if (u > 1) {
  8014. u = 1;
  8015. }
  8016. else if (u < 0) {
  8017. u = 0;
  8018. }
  8019. var x = x1 + u * px,
  8020. y = y1 + u * py,
  8021. dx = x - x3,
  8022. dy = y - y3;
  8023. //# Note: If the actual distance does not matter,
  8024. //# if you only want to compare what this function
  8025. //# returns to other results of this function, you
  8026. //# can just return the squared distance instead
  8027. //# (i.e. remove the sqrt) to gain a little performance
  8028. return Math.sqrt(dx*dx + dy*dy);
  8029. };
  8030. /**
  8031. * Popup is a class to create a popup window with some text
  8032. * @param {Element} container The container object.
  8033. * @param {Number} [x]
  8034. * @param {Number} [y]
  8035. * @param {String} [text]
  8036. */
  8037. function Popup(container, x, y, text) {
  8038. if (container) {
  8039. this.container = container;
  8040. }
  8041. else {
  8042. this.container = document.body;
  8043. }
  8044. this.x = 0;
  8045. this.y = 0;
  8046. this.padding = 5;
  8047. if (x !== undefined && y !== undefined ) {
  8048. this.setPosition(x, y);
  8049. }
  8050. if (text !== undefined) {
  8051. this.setText(text);
  8052. }
  8053. // create the frame
  8054. this.frame = document.createElement("div");
  8055. var style = this.frame.style;
  8056. style.position = "absolute";
  8057. style.visibility = "hidden";
  8058. style.border = "1px solid #666";
  8059. style.color = "black";
  8060. style.padding = this.padding + "px";
  8061. style.backgroundColor = "#FFFFC6";
  8062. style.borderRadius = "3px";
  8063. style.MozBorderRadius = "3px";
  8064. style.WebkitBorderRadius = "3px";
  8065. style.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  8066. style.whiteSpace = "nowrap";
  8067. this.container.appendChild(this.frame);
  8068. };
  8069. /**
  8070. * @param {number} x Horizontal position of the popup window
  8071. * @param {number} y Vertical position of the popup window
  8072. */
  8073. Popup.prototype.setPosition = function(x, y) {
  8074. this.x = parseInt(x);
  8075. this.y = parseInt(y);
  8076. };
  8077. /**
  8078. * Set the text for the popup window. This can be HTML code
  8079. * @param {string} text
  8080. */
  8081. Popup.prototype.setText = function(text) {
  8082. this.frame.innerHTML = text;
  8083. };
  8084. /**
  8085. * Show the popup window
  8086. * @param {boolean} show Optional. Show or hide the window
  8087. */
  8088. Popup.prototype.show = function (show) {
  8089. if (show === undefined) {
  8090. show = true;
  8091. }
  8092. if (show) {
  8093. var height = this.frame.clientHeight;
  8094. var width = this.frame.clientWidth;
  8095. var maxHeight = this.frame.parentNode.clientHeight;
  8096. var maxWidth = this.frame.parentNode.clientWidth;
  8097. var top = (this.y - height);
  8098. if (top + height + this.padding > maxHeight) {
  8099. top = maxHeight - height - this.padding;
  8100. }
  8101. if (top < this.padding) {
  8102. top = this.padding;
  8103. }
  8104. var left = this.x;
  8105. if (left + width + this.padding > maxWidth) {
  8106. left = maxWidth - width - this.padding;
  8107. }
  8108. if (left < this.padding) {
  8109. left = this.padding;
  8110. }
  8111. this.frame.style.left = left + "px";
  8112. this.frame.style.top = top + "px";
  8113. this.frame.style.visibility = "visible";
  8114. }
  8115. else {
  8116. this.hide();
  8117. }
  8118. };
  8119. /**
  8120. * Hide the popup window
  8121. */
  8122. Popup.prototype.hide = function () {
  8123. this.frame.style.visibility = "hidden";
  8124. };
  8125. /**
  8126. * @class Groups
  8127. * This class can store groups and properties specific for groups.
  8128. */
  8129. Groups = function () {
  8130. this.clear();
  8131. this.defaultIndex = 0;
  8132. };
  8133. /**
  8134. * default constants for group colors
  8135. */
  8136. Groups.DEFAULT = [
  8137. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  8138. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  8139. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  8140. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  8141. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  8142. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  8143. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  8144. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  8145. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  8146. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  8147. ];
  8148. /**
  8149. * Clear all groups
  8150. */
  8151. Groups.prototype.clear = function () {
  8152. this.groups = {};
  8153. this.groups.length = function()
  8154. {
  8155. var i = 0;
  8156. for ( var p in this ) {
  8157. if (this.hasOwnProperty(p)) {
  8158. i++;
  8159. }
  8160. }
  8161. return i;
  8162. }
  8163. };
  8164. /**
  8165. * get group properties of a groupname. If groupname is not found, a new group
  8166. * is added.
  8167. * @param {*} groupname Can be a number, string, Date, etc.
  8168. * @return {Object} group The created group, containing all group properties
  8169. */
  8170. Groups.prototype.get = function (groupname) {
  8171. var group = this.groups[groupname];
  8172. if (group == undefined) {
  8173. // create new group
  8174. var index = this.defaultIndex % Groups.DEFAULT.length;
  8175. this.defaultIndex++;
  8176. group = {};
  8177. group.color = Groups.DEFAULT[index];
  8178. this.groups[groupname] = group;
  8179. }
  8180. return group;
  8181. };
  8182. /**
  8183. * Add a custom group style
  8184. * @param {String} groupname
  8185. * @param {Object} style An object containing borderColor,
  8186. * backgroundColor, etc.
  8187. * @return {Object} group The created group object
  8188. */
  8189. Groups.prototype.add = function (groupname, style) {
  8190. this.groups[groupname] = style;
  8191. if (style.color) {
  8192. style.color = Node.parseColor(style.color);
  8193. }
  8194. return style;
  8195. };
  8196. /**
  8197. * @class Images
  8198. * This class loads images and keeps them stored.
  8199. */
  8200. Images = function () {
  8201. this.images = {};
  8202. this.callback = undefined;
  8203. };
  8204. /**
  8205. * Set an onload callback function. This will be called each time an image
  8206. * is loaded
  8207. * @param {function} callback
  8208. */
  8209. Images.prototype.setOnloadCallback = function(callback) {
  8210. this.callback = callback;
  8211. };
  8212. /**
  8213. *
  8214. * @param {string} url Url of the image
  8215. * @return {Image} img The image object
  8216. */
  8217. Images.prototype.load = function(url) {
  8218. var img = this.images[url];
  8219. if (img == undefined) {
  8220. // create the image
  8221. var images = this;
  8222. img = new Image();
  8223. this.images[url] = img;
  8224. img.onload = function() {
  8225. if (images.callback) {
  8226. images.callback(this);
  8227. }
  8228. };
  8229. img.src = url;
  8230. }
  8231. return img;
  8232. };
  8233. /**
  8234. * @constructor Graph
  8235. * Create a graph visualization, displaying nodes and edges.
  8236. *
  8237. * @param {Element} container The DOM element in which the Graph will
  8238. * be created. Normally a div element.
  8239. * @param {Object} data An object containing parameters
  8240. * {Array} nodes
  8241. * {Array} edges
  8242. * @param {Object} options Options
  8243. */
  8244. function Graph (container, data, options) {
  8245. // create variables and set default values
  8246. this.containerElement = container;
  8247. this.width = '100%';
  8248. this.height = '100%';
  8249. this.refreshRate = 50; // milliseconds
  8250. this.stabilize = true; // stabilize before displaying the graph
  8251. this.selectable = true;
  8252. // set constant values
  8253. this.constants = {
  8254. nodes: {
  8255. radiusMin: 5,
  8256. radiusMax: 20,
  8257. radius: 5,
  8258. distance: 100, // px
  8259. shape: 'ellipse',
  8260. image: undefined,
  8261. widthMin: 16, // px
  8262. widthMax: 64, // px
  8263. fontColor: 'black',
  8264. fontSize: 14, // px
  8265. //fontFace: verdana,
  8266. fontFace: 'arial',
  8267. color: {
  8268. border: '#2B7CE9',
  8269. background: '#97C2FC',
  8270. highlight: {
  8271. border: '#2B7CE9',
  8272. background: '#D2E5FF'
  8273. }
  8274. },
  8275. borderColor: '#2B7CE9',
  8276. backgroundColor: '#97C2FC',
  8277. highlightColor: '#D2E5FF',
  8278. group: undefined
  8279. },
  8280. edges: {
  8281. widthMin: 1,
  8282. widthMax: 15,
  8283. width: 1,
  8284. style: 'line',
  8285. color: '#343434',
  8286. fontColor: '#343434',
  8287. fontSize: 14, // px
  8288. fontFace: 'arial',
  8289. //distance: 100, //px
  8290. length: 100, // px
  8291. dash: {
  8292. length: 10,
  8293. gap: 5,
  8294. altLength: undefined
  8295. }
  8296. },
  8297. minForce: 0.05,
  8298. minVelocity: 0.02, // px/s
  8299. maxIterations: 1000 // maximum number of iteration to stabilize
  8300. };
  8301. var graph = this;
  8302. this.nodes = []; // array with Node objects
  8303. this.edges = []; // array with Edge objects
  8304. this.groups = new Groups(); // object with groups
  8305. this.images = new Images(); // object with images
  8306. this.images.setOnloadCallback(function () {
  8307. graph._redraw();
  8308. });
  8309. // properties of the data
  8310. this.moving = false; // True if any of the nodes have an undefined position
  8311. this.selection = [];
  8312. this.timer = undefined;
  8313. // create a frame and canvas
  8314. this._create();
  8315. // apply options
  8316. this.setOptions(options);
  8317. // draw data
  8318. this.setData(data);
  8319. }
  8320. /**
  8321. * Set nodes and edges, and optionally options as well.
  8322. *
  8323. * @param {Object} data Object containing parameters:
  8324. * {Array} [nodes] Array with nodes.
  8325. * Required when format is 'vis'
  8326. * {Array} [edges] Array with edges
  8327. * Required when format is 'vis'
  8328. * {String} [dot] String containing data in DOT
  8329. * format.
  8330. * {Options} [options] Object with options
  8331. */
  8332. Graph.prototype.setData = function(data) {
  8333. if (data && data.dot && (data.nodes || data.edges)) {
  8334. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  8335. ' parameter pair "nodes" and "edges", but not both.');
  8336. }
  8337. // set options
  8338. this.setOptions(data && data.options);
  8339. // set all data
  8340. if (data && data.dot) {
  8341. // parse DOT file
  8342. if(data && data.dot) {
  8343. var dotData = vis.util.DOTToGraph(data.dot);
  8344. this.setData(dotData);
  8345. return;
  8346. }
  8347. }
  8348. else {
  8349. this._setNodes(data && data.nodes);
  8350. this._setEdges(data && data.edges);
  8351. }
  8352. // find a stable position or start animating to a stable position
  8353. if (this.stabilize) {
  8354. this._doStabilize();
  8355. }
  8356. this.start();
  8357. };
  8358. /**
  8359. * Set options
  8360. * @param {Object} options
  8361. */
  8362. Graph.prototype.setOptions = function (options) {
  8363. if (options) {
  8364. // retrieve parameter values
  8365. if (options.width != undefined) {this.width = options.width;}
  8366. if (options.height != undefined) {this.height = options.height;}
  8367. if (options.stabilize != undefined) {this.stabilize = options.stabilize;}
  8368. if (options.selectable != undefined) {this.selectable = options.selectable;}
  8369. // TODO: work out these options and document them
  8370. if (options.edges) {
  8371. for (var prop in options.edges) {
  8372. if (options.edges.hasOwnProperty(prop)) {
  8373. this.constants.edges[prop] = options.edges[prop];
  8374. }
  8375. }
  8376. if (options.edges.length != undefined &&
  8377. options.nodes && options.nodes.distance == undefined) {
  8378. this.constants.edges.length = options.edges.length;
  8379. this.constants.nodes.distance = options.edges.length * 1.25;
  8380. }
  8381. if (!options.edges.fontColor) {
  8382. this.constants.edges.fontColor = options.edges.color;
  8383. }
  8384. // Added to support dashed lines
  8385. // David Jordan
  8386. // 2012-08-08
  8387. if (options.edges.dash) {
  8388. if (options.edges.dash.length != undefined) {
  8389. this.constants.edges.dash.length = options.edges.dash.length;
  8390. }
  8391. if (options.edges.dash.gap != undefined) {
  8392. this.constants.edges.dash.gap = options.edges.dash.gap;
  8393. }
  8394. if (options.edges.dash.altLength != undefined) {
  8395. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  8396. }
  8397. }
  8398. }
  8399. if (options.nodes) {
  8400. for (prop in options.nodes) {
  8401. if (options.nodes.hasOwnProperty(prop)) {
  8402. this.constants.nodes[prop] = options.nodes[prop];
  8403. }
  8404. }
  8405. if (options.nodes.color) {
  8406. this.constants.nodes.color = Node.parseColor(options.nodes.color);
  8407. }
  8408. /*
  8409. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  8410. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  8411. */
  8412. }
  8413. if (options.groups) {
  8414. for (var groupname in options.groups) {
  8415. if (options.groups.hasOwnProperty(groupname)) {
  8416. var group = options.groups[groupname];
  8417. this.groups.add(groupname, group);
  8418. }
  8419. }
  8420. }
  8421. }
  8422. this.setSize(this.width, this.height);
  8423. this._setTranslation(0, 0);
  8424. this._setScale(1);
  8425. };
  8426. /**
  8427. * fire an event
  8428. * @param {String} event The name of an event, for example "select"
  8429. * @param {Object} params Optional object with event parameters
  8430. * @private
  8431. */
  8432. Graph.prototype._trigger = function (event, params) {
  8433. events.trigger(this, event, params);
  8434. };
  8435. /**
  8436. * Create the main frame for the Graph.
  8437. * This function is executed once when a Graph object is created. The frame
  8438. * contains a canvas, and this canvas contains all objects like the axis and
  8439. * nodes.
  8440. * @private
  8441. */
  8442. Graph.prototype._create = function () {
  8443. // remove all elements from the container element.
  8444. while (this.containerElement.hasChildNodes()) {
  8445. this.containerElement.removeChild(this.containerElement.firstChild);
  8446. }
  8447. this.frame = document.createElement("div");
  8448. this.frame.className = "graph-frame";
  8449. this.frame.style.position = "relative";
  8450. this.frame.style.overflow = "hidden";
  8451. // create the graph canvas (HTML canvas element)
  8452. this.frame.canvas = document.createElement( "canvas" );
  8453. this.frame.canvas.style.position = "relative";
  8454. this.frame.appendChild(this.frame.canvas);
  8455. if (!this.frame.canvas.getContext) {
  8456. var noCanvas = document.createElement( "DIV" );
  8457. noCanvas.style.color = "red";
  8458. noCanvas.style.fontWeight = "bold" ;
  8459. noCanvas.style.padding = "10px";
  8460. noCanvas.innerHTML = "Error: your browser does not support HTML canvas";
  8461. this.frame.canvas.appendChild(noCanvas);
  8462. }
  8463. // create event listeners
  8464. var me = this;
  8465. var onmousedown = function (event) {me._onMouseDown(event);};
  8466. var onmousemove = function (event) {me._onMouseMoveTitle(event);};
  8467. var onmousewheel = function (event) {me._onMouseWheel(event);};
  8468. var ontouchstart = function (event) {me._onTouchStart(event);};
  8469. vis.util.addEventListener(this.frame.canvas, "mousedown", onmousedown);
  8470. vis.util.addEventListener(this.frame.canvas, "mousemove", onmousemove);
  8471. vis.util.addEventListener(this.frame.canvas, "mousewheel", onmousewheel);
  8472. vis.util.addEventListener(this.frame.canvas, "touchstart", ontouchstart);
  8473. // add the frame to the container element
  8474. this.containerElement.appendChild(this.frame);
  8475. };
  8476. /**
  8477. * handle on mouse down event
  8478. * @private
  8479. */
  8480. Graph.prototype._onMouseDown = function (event) {
  8481. event = event || window.event;
  8482. if (!this.selectable) {
  8483. return;
  8484. }
  8485. // check if mouse is still down (may be up when focus is lost for example
  8486. // in an iframe)
  8487. if (this.leftButtonDown) {
  8488. this._onMouseUp(event);
  8489. }
  8490. // only react on left mouse button down
  8491. this.leftButtonDown = event.which ? (event.which == 1) : (event.button == 1);
  8492. if (!this.leftButtonDown && !this.touchDown) {
  8493. return;
  8494. }
  8495. // add event listeners to handle moving the contents
  8496. // we store the function onmousemove and onmouseup in the timeline, so we can
  8497. // remove the eventlisteners lateron in the function mouseUp()
  8498. var me = this;
  8499. if (!this.onmousemove) {
  8500. this.onmousemove = function (event) {me._onMouseMove(event);};
  8501. vis.util.addEventListener(document, "mousemove", me.onmousemove);
  8502. }
  8503. if (!this.onmouseup) {
  8504. this.onmouseup = function (event) {me._onMouseUp(event);};
  8505. vis.util.addEventListener(document, "mouseup", me.onmouseup);
  8506. }
  8507. vis.util.preventDefault(event);
  8508. // store the start x and y position of the mouse
  8509. this.startMouseX = event.clientX || event.targetTouches[0].clientX;
  8510. this.startMouseY = event.clientY || event.targetTouches[0].clientY;
  8511. this.startFrameLeft = vis.util.getAbsoluteLeft(this.frame.canvas);
  8512. this.startFrameTop = vis.util.getAbsoluteTop(this.frame.canvas);
  8513. this.startTranslation = this._getTranslation();
  8514. this.ctrlKeyDown = event.ctrlKey;
  8515. this.shiftKeyDown = event.shiftKey;
  8516. var obj = {
  8517. "left" : this._xToCanvas(this.startMouseX - this.startFrameLeft),
  8518. "top" : this._yToCanvas(this.startMouseY - this.startFrameTop),
  8519. "right" : this._xToCanvas(this.startMouseX - this.startFrameLeft),
  8520. "bottom" : this._yToCanvas(this.startMouseY - this.startFrameTop)
  8521. };
  8522. var overlappingNodes = this._getNodesOverlappingWith(obj);
  8523. // if there are overlapping nodes, select the last one, this is the
  8524. // one which is drawn on top of the others
  8525. this.startClickedObj = (overlappingNodes.length > 0) ?
  8526. overlappingNodes[overlappingNodes.length - 1] : undefined;
  8527. if (this.startClickedObj) {
  8528. // move clicked node with the mouse
  8529. // make the clicked node temporarily fixed, and store their original state
  8530. var node = this.nodes[this.startClickedObj.row];
  8531. this.startClickedObj.xFixed = node.xFixed;
  8532. this.startClickedObj.yFixed = node.yFixed;
  8533. node.xFixed = true;
  8534. node.yFixed = true;
  8535. if (!this.ctrlKeyDown || !node.isSelected()) {
  8536. // select this node
  8537. this._selectNodes([this.startClickedObj], this.ctrlKeyDown);
  8538. }
  8539. else {
  8540. // unselect this node
  8541. this._unselectNodes([this.startClickedObj]);
  8542. }
  8543. if (!this.moving) {
  8544. this._redraw();
  8545. }
  8546. }
  8547. else if (this.shiftKeyDown) {
  8548. // start selection of multiple nodes
  8549. }
  8550. else {
  8551. // start moving the graph
  8552. this.moved = false;
  8553. }
  8554. };
  8555. /**
  8556. * handle on mouse move event
  8557. * @param {Event} event
  8558. * @private
  8559. */
  8560. Graph.prototype._onMouseMove = function (event) {
  8561. event = event || window.event;
  8562. if (!this.selectable) {
  8563. return;
  8564. }
  8565. var mouseX = event.clientX || (event.targetTouches && event.targetTouches[0].clientX) || 0;
  8566. var mouseY = event.clientY || (event.targetTouches && event.targetTouches[0].clientY) || 0;
  8567. this.mouseX = mouseX;
  8568. this.mouseY = mouseY;
  8569. if (this.startClickedObj) {
  8570. var node = this.nodes[this.startClickedObj.row];
  8571. if (!this.startClickedObj.xFixed)
  8572. node.x = this._xToCanvas(mouseX - this.startFrameLeft);
  8573. if (!this.startClickedObj.yFixed)
  8574. node.y = this._yToCanvas(mouseY - this.startFrameTop);
  8575. // start animation if not yet running
  8576. if (!this.moving) {
  8577. this.moving = true;
  8578. this.start();
  8579. }
  8580. }
  8581. else if (this.shiftKeyDown) {
  8582. // draw a rect from start mouse location to current mouse location
  8583. if (this.frame.selRect == undefined) {
  8584. this.frame.selRect = document.createElement("DIV");
  8585. this.frame.appendChild(this.frame.selRect);
  8586. this.frame.selRect.style.position = "absolute";
  8587. this.frame.selRect.style.border = "1px dashed red";
  8588. }
  8589. var left = Math.min(this.startMouseX, mouseX) - this.startFrameLeft;
  8590. var top = Math.min(this.startMouseY, mouseY) - this.startFrameTop;
  8591. var right = Math.max(this.startMouseX, mouseX) - this.startFrameLeft;
  8592. var bottom = Math.max(this.startMouseY, mouseY) - this.startFrameTop;
  8593. this.frame.selRect.style.left = left + "px";
  8594. this.frame.selRect.style.top = top + "px";
  8595. this.frame.selRect.style.width = (right - left) + "px";
  8596. this.frame.selRect.style.height = (bottom - top) + "px";
  8597. }
  8598. else {
  8599. // move the graph
  8600. var diffX = mouseX - this.startMouseX;
  8601. var diffY = mouseY - this.startMouseY;
  8602. this._setTranslation(
  8603. this.startTranslation.x + diffX,
  8604. this.startTranslation.y + diffY);
  8605. this._redraw();
  8606. this.moved = true;
  8607. }
  8608. vis.util.preventDefault(event);
  8609. };
  8610. /**
  8611. * handle on mouse up event
  8612. * @param {Event} event
  8613. * @private
  8614. */
  8615. Graph.prototype._onMouseUp = function (event) {
  8616. event = event || window.event;
  8617. if (!this.selectable) {
  8618. return;
  8619. }
  8620. // remove event listeners here, important for Safari
  8621. if (this.onmousemove) {
  8622. vis.util.removeEventListener(document, "mousemove", this.onmousemove);
  8623. this.onmousemove = undefined;
  8624. }
  8625. if (this.onmouseup) {
  8626. vis.util.removeEventListener(document, "mouseup", this.onmouseup);
  8627. this.onmouseup = undefined;
  8628. }
  8629. vis.util.preventDefault(event);
  8630. // check selected nodes
  8631. var endMouseX = event.clientX || this.mouseX || 0;
  8632. var endMouseY = event.clientY || this.mouseY || 0;
  8633. var ctrlKey = event ? event.ctrlKey : window.event.ctrlKey;
  8634. if (this.startClickedObj) {
  8635. // restore the original fixed state
  8636. var node = this.nodes[this.startClickedObj.row];
  8637. node.xFixed = this.startClickedObj.xFixed;
  8638. node.yFixed = this.startClickedObj.yFixed;
  8639. }
  8640. else if (this.shiftKeyDown) {
  8641. // select nodes inside selection area
  8642. var obj = {
  8643. "left": this._xToCanvas(Math.min(this.startMouseX, endMouseX) - this.startFrameLeft),
  8644. "top": this._yToCanvas(Math.min(this.startMouseY, endMouseY) - this.startFrameTop),
  8645. "right": this._xToCanvas(Math.max(this.startMouseX, endMouseX) - this.startFrameLeft),
  8646. "bottom": this._yToCanvas(Math.max(this.startMouseY, endMouseY) - this.startFrameTop)
  8647. };
  8648. var overlappingNodes = this._getNodesOverlappingWith(obj);
  8649. this._selectNodes(overlappingNodes, ctrlKey);
  8650. this.redraw();
  8651. // remove the selection rectangle
  8652. if (this.frame.selRect) {
  8653. this.frame.removeChild(this.frame.selRect);
  8654. this.frame.selRect = undefined;
  8655. }
  8656. }
  8657. else {
  8658. if (!this.ctrlKeyDown && !this.moved) {
  8659. // remove selection
  8660. this._unselectNodes();
  8661. this._redraw();
  8662. }
  8663. }
  8664. this.leftButtonDown = false;
  8665. this.ctrlKeyDown = false;
  8666. };
  8667. /**
  8668. * Event handler for mouse wheel event, used to zoom the timeline
  8669. * Code from http://adomas.org/javascript-mouse-wheel/
  8670. * @param {Event} event
  8671. * @private
  8672. */
  8673. Graph.prototype._onMouseWheel = function(event) {
  8674. event = event || window.event;
  8675. var mouseX = event.clientX;
  8676. var mouseY = event.clientY;
  8677. // retrieve delta
  8678. var delta = 0;
  8679. if (event.wheelDelta) { /* IE/Opera. */
  8680. delta = event.wheelDelta/120;
  8681. } else if (event.detail) { /* Mozilla case. */
  8682. // In Mozilla, sign of delta is different than in IE.
  8683. // Also, delta is multiple of 3.
  8684. delta = -event.detail/3;
  8685. }
  8686. // If delta is nonzero, handle it.
  8687. // Basically, delta is now positive if wheel was scrolled up,
  8688. // and negative, if wheel was scrolled down.
  8689. if (delta) {
  8690. // determine zoom factor, and adjust the zoom factor such that zooming in
  8691. // and zooming out correspond wich each other
  8692. var zoom = delta / 10;
  8693. if (delta < 0) {
  8694. zoom = zoom / (1 - zoom);
  8695. }
  8696. var scaleOld = this._getScale();
  8697. var scaleNew = scaleOld * (1 + zoom);
  8698. if (scaleNew < 0.01) {
  8699. scaleNew = 0.01;
  8700. }
  8701. if (scaleNew > 10) {
  8702. scaleNew = 10;
  8703. }
  8704. var frameLeft = vis.util.getAbsoluteLeft(this.frame.canvas);
  8705. var frameTop = vis.util.getAbsoluteTop(this.frame.canvas);
  8706. var x = mouseX - frameLeft;
  8707. var y = mouseY - frameTop;
  8708. var translation = this._getTranslation();
  8709. var scaleFrac = scaleNew / scaleOld;
  8710. var tx = (1 - scaleFrac) * x + translation.x * scaleFrac;
  8711. var ty = (1 - scaleFrac) * y + translation.y * scaleFrac;
  8712. this._setScale(scaleNew);
  8713. this._setTranslation(tx, ty);
  8714. this._redraw();
  8715. }
  8716. // Prevent default actions caused by mouse wheel.
  8717. // That might be ugly, but we handle scrolls somehow
  8718. // anyway, so don't bother here...
  8719. vis.util.preventDefault(event);
  8720. };
  8721. /**
  8722. * Mouse move handler for checking whether the title moves over a node with a title.
  8723. * @param {Event} event
  8724. * @private
  8725. */
  8726. Graph.prototype._onMouseMoveTitle = function (event) {
  8727. event = event || window.event;
  8728. var startMouseX = event.clientX;
  8729. var startMouseY = event.clientY;
  8730. this.startFrameLeft = this.startFrameLeft || vis.util.getAbsoluteLeft(this.frame.canvas);
  8731. this.startFrameTop = this.startFrameTop || vis.util.getAbsoluteTop(this.frame.canvas);
  8732. var x = startMouseX - this.startFrameLeft;
  8733. var y = startMouseY - this.startFrameTop;
  8734. // check if the previously selected node is still selected
  8735. if (this.popupNode) {
  8736. this._checkHidePopup(x, y);
  8737. }
  8738. // start a timeout that will check if the mouse is positioned above
  8739. // an element
  8740. var me = this;
  8741. var checkShow = function() {
  8742. me._checkShowPopup(x, y);
  8743. };
  8744. if (this.popupTimer) {
  8745. clearInterval(this.popupTimer); // stop any running timer
  8746. }
  8747. if (!this.leftButtonDown) {
  8748. this.popupTimer = setTimeout(checkShow, 300);
  8749. }
  8750. };
  8751. /**
  8752. * Check if there is an element on the given position in the graph
  8753. * (a node or edge). If so, and if this element has a title,
  8754. * show a popup window with its title.
  8755. *
  8756. * @param {number} x
  8757. * @param {number} y
  8758. * @private
  8759. */
  8760. Graph.prototype._checkShowPopup = function (x, y) {
  8761. var obj = {
  8762. "left" : this._xToCanvas(x),
  8763. "top" : this._yToCanvas(y),
  8764. "right" : this._xToCanvas(x),
  8765. "bottom" : this._yToCanvas(y)
  8766. };
  8767. var i, len;
  8768. var lastPopupNode = this.popupNode;
  8769. if (this.popupNode == undefined) {
  8770. // search the nodes for overlap, select the top one in case of multiple nodes
  8771. var nodes = this.nodes;
  8772. for (i = nodes.length - 1; i >= 0; i--) {
  8773. var node = nodes[i];
  8774. if (node.getTitle() != undefined && node.isOverlappingWith(obj)) {
  8775. this.popupNode = node;
  8776. break;
  8777. }
  8778. }
  8779. }
  8780. if (this.popupNode == undefined) {
  8781. // search the edges for overlap
  8782. var allEdges = this.edges;
  8783. for (i = 0, len = allEdges.length; i < len; i++) {
  8784. var edge = allEdges[i];
  8785. if (edge.getTitle() != undefined && edge.isOverlappingWith(obj)) {
  8786. this.popupNode = edge;
  8787. break;
  8788. }
  8789. }
  8790. }
  8791. if (this.popupNode) {
  8792. // show popup message window
  8793. if (this.popupNode != lastPopupNode) {
  8794. var me = this;
  8795. if (!me.popup) {
  8796. me.popup = new Popup(me.frame);
  8797. }
  8798. // adjust a small offset such that the mouse cursor is located in the
  8799. // bottom left location of the popup, and you can easily move over the
  8800. // popup area
  8801. me.popup.setPosition(x - 3, y - 3);
  8802. me.popup.setText(me.popupNode.getTitle());
  8803. me.popup.show();
  8804. }
  8805. }
  8806. else {
  8807. if (this.popup) {
  8808. this.popup.hide();
  8809. }
  8810. }
  8811. };
  8812. /**
  8813. * Check if the popup must be hided, which is the case when the mouse is no
  8814. * longer hovering on the object
  8815. * @param {number} x
  8816. * @param {number} y
  8817. * @private
  8818. */
  8819. Graph.prototype._checkHidePopup = function (x, y) {
  8820. var obj = {
  8821. "left" : x,
  8822. "top" : y,
  8823. "right" : x,
  8824. "bottom" : y
  8825. };
  8826. if (!this.popupNode || !this.popupNode.isOverlappingWith(obj) ) {
  8827. this.popupNode = undefined;
  8828. if (this.popup) {
  8829. this.popup.hide();
  8830. }
  8831. }
  8832. };
  8833. /**
  8834. * Event handler for touchstart event on mobile devices
  8835. * @param {Event} event
  8836. * @private
  8837. */
  8838. Graph.prototype._onTouchStart = function(event) {
  8839. vis.util.preventDefault(event);
  8840. if (this.touchDown) {
  8841. // if already moving, return
  8842. return;
  8843. }
  8844. this.touchDown = true;
  8845. var me = this;
  8846. if (!this.ontouchmove) {
  8847. this.ontouchmove = function (event) {me._onTouchMove(event);};
  8848. vis.util.addEventListener(document, "touchmove", this.ontouchmove);
  8849. }
  8850. if (!this.ontouchend) {
  8851. this.ontouchend = function (event) {me._onTouchEnd(event);};
  8852. vis.util.addEventListener(document, "touchend", this.ontouchend);
  8853. }
  8854. this._onMouseDown(event);
  8855. };
  8856. /**
  8857. * Event handler for touchmove event on mobile devices
  8858. * @param {Event} event
  8859. * @private
  8860. */
  8861. Graph.prototype._onTouchMove = function(event) {
  8862. vis.util.preventDefault(event);
  8863. this._onMouseMove(event);
  8864. };
  8865. /**
  8866. * Event handler for touchend event on mobile devices
  8867. * @param {Event} event
  8868. * @private
  8869. */
  8870. Graph.prototype._onTouchEnd = function(event) {
  8871. vis.util.preventDefault(event);
  8872. this.touchDown = false;
  8873. if (this.ontouchmove) {
  8874. vis.util.removeEventListener(document, "touchmove", this.ontouchmove);
  8875. this.ontouchmove = undefined;
  8876. }
  8877. if (this.ontouchend) {
  8878. vis.util.removeEventListener(document, "touchend", this.ontouchend);
  8879. this.ontouchend = undefined;
  8880. }
  8881. this._onMouseUp(event);
  8882. };
  8883. /**
  8884. * Unselect selected nodes. If no selection array is provided, all nodes
  8885. * are unselected
  8886. * @param {Object[]} selection Array with selection objects, each selection
  8887. * object has a parameter row. Optional
  8888. * @param {Boolean} triggerSelect If true (default), the select event
  8889. * is triggered when nodes are unselected
  8890. * @return {Boolean} changed True if the selection is changed
  8891. * @private
  8892. */
  8893. Graph.prototype._unselectNodes = function(selection, triggerSelect) {
  8894. var changed = false;
  8895. var i, iMax, row;
  8896. if (selection) {
  8897. // remove provided selections
  8898. for (i = 0, iMax = selection.length; i < iMax; i++) {
  8899. row = selection[i].row;
  8900. this.nodes[row].unselect();
  8901. var j = 0;
  8902. while (j < this.selection.length) {
  8903. if (this.selection[j].row == row) {
  8904. this.selection.splice(j, 1);
  8905. changed = true;
  8906. }
  8907. else {
  8908. j++;
  8909. }
  8910. }
  8911. }
  8912. }
  8913. else if (this.selection && this.selection.length) {
  8914. // remove all selections
  8915. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  8916. row = this.selection[i].row;
  8917. this.nodes[row].unselect();
  8918. changed = true;
  8919. }
  8920. this.selection = [];
  8921. }
  8922. if (changed && (triggerSelect == true || triggerSelect == undefined)) {
  8923. // fire the select event
  8924. this._trigger('select');
  8925. }
  8926. return changed;
  8927. };
  8928. /**
  8929. * select all nodes on given location x, y
  8930. * @param {Array} selection an array with selection objects. Each selection
  8931. * object has a parameter row
  8932. * @param {boolean} append If true, the new selection will be appended to the
  8933. * current selection (except for duplicate entries)
  8934. * @return {Boolean} changed True if the selection is changed
  8935. * @private
  8936. */
  8937. Graph.prototype._selectNodes = function(selection, append) {
  8938. var changed = false;
  8939. var i, iMax;
  8940. // TODO: the selectNodes method is a little messy, rework this
  8941. // check if the current selection equals the desired selection
  8942. var selectionAlreadyDone = true;
  8943. if (selection.length != this.selection.length) {
  8944. selectionAlreadyDone = false;
  8945. }
  8946. else {
  8947. for (i = 0, iMax = Math.min(selection.length, this.selection.length); i < iMax; i++) {
  8948. if (selection[i].row != this.selection[i].row) {
  8949. selectionAlreadyDone = false;
  8950. break;
  8951. }
  8952. }
  8953. }
  8954. if (selectionAlreadyDone) {
  8955. return changed;
  8956. }
  8957. if (append == undefined || append == false) {
  8958. // first deselect any selected node
  8959. var triggerSelect = false;
  8960. changed = this._unselectNodes(undefined, triggerSelect);
  8961. }
  8962. for (i = 0, iMax = selection.length; i < iMax; i++) {
  8963. // add each of the new selections, but only when they are not duplicate
  8964. var row = selection[i].row;
  8965. var isDuplicate = false;
  8966. for (var j = 0, jMax = this.selection.length; j < jMax; j++) {
  8967. if (this.selection[j].row == row) {
  8968. isDuplicate = true;
  8969. break;
  8970. }
  8971. }
  8972. if (!isDuplicate) {
  8973. this.nodes[row].select();
  8974. this.selection.push(selection[i]);
  8975. changed = true;
  8976. }
  8977. }
  8978. if (changed) {
  8979. // fire the select event
  8980. this._trigger('select');
  8981. }
  8982. return changed;
  8983. };
  8984. /**
  8985. * retrieve all nodes overlapping with given object
  8986. * @param {Object} obj An object with parameters left, top, right, bottom
  8987. * @return {Object[]} An array with selection objects containing
  8988. * the parameter row.
  8989. * @private
  8990. */
  8991. Graph.prototype._getNodesOverlappingWith = function (obj) {
  8992. var overlappingNodes = [];
  8993. for (var i = 0; i < this.nodes.length; i++) {
  8994. if (this.nodes[i].isOverlappingWith(obj)) {
  8995. var sel = {"row": i};
  8996. overlappingNodes.push(sel);
  8997. }
  8998. }
  8999. return overlappingNodes;
  9000. };
  9001. /**
  9002. * retrieve the currently selected nodes
  9003. * @return {Object[]} an array with zero or more objects. Each object
  9004. * contains the parameter row
  9005. */
  9006. Graph.prototype.getSelection = function() {
  9007. var selection = [];
  9008. for (var i = 0; i < this.selection.length; i++) {
  9009. var row = this.selection[i].row;
  9010. selection.push({"row": row});
  9011. }
  9012. return selection;
  9013. };
  9014. /**
  9015. * select zero or more nodes
  9016. * @param {object[]} selection an array with zero or more objects. Each object
  9017. * contains the parameter row
  9018. */
  9019. Graph.prototype.setSelection = function(selection) {
  9020. var i, iMax, row;
  9021. if (selection.length == undefined)
  9022. throw "Selection must be an array with objects";
  9023. // first unselect any selected node
  9024. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  9025. row = this.selection[i].row;
  9026. this.nodes[row].unselect();
  9027. }
  9028. this.selection = [];
  9029. for (i = 0, iMax = selection.length; i < iMax; i++) {
  9030. row = selection[i].row;
  9031. if (row == undefined)
  9032. throw "Parameter row missing in selection object";
  9033. if (row > this.nodes.length-1)
  9034. throw "Parameter row out of range";
  9035. var sel = {"row": row};
  9036. this.selection.push(sel);
  9037. this.nodes[row].select();
  9038. }
  9039. this.redraw();
  9040. };
  9041. /**
  9042. * Temporary method to test calculating a hub value for the nodes
  9043. * @param {number} level Maximum number edges between two nodes in order
  9044. * to call them connected. Optional, 1 by default
  9045. * @return {Number[]} connectioncount array with the connection count
  9046. * for each node
  9047. * @private
  9048. */
  9049. Graph.prototype._getConnectionCount = function(level) {
  9050. var conn = this.edges;
  9051. if (level == undefined) {
  9052. level = 1;
  9053. }
  9054. // get the nodes connected to given nodes
  9055. function getConnectedNodes(nodes) {
  9056. var connectedNodes = [];
  9057. for (var j = 0, jMax = nodes.length; j < jMax; j++) {
  9058. var node = nodes[j];
  9059. // find all nodes connected to this node
  9060. for (var i = 0, iMax = conn.length; i < iMax; i++) {
  9061. var other = null;
  9062. // check if connected
  9063. if (conn[i].from == node)
  9064. other = conn[i].to;
  9065. else if (conn[i].to == node)
  9066. other = conn[i].from;
  9067. // check if the other node is not already in the list with nodes
  9068. var k, kMax;
  9069. if (other) {
  9070. for (k = 0, kMax = nodes.length; k < kMax; k++) {
  9071. if (nodes[k] == other) {
  9072. other = null;
  9073. break;
  9074. }
  9075. }
  9076. }
  9077. if (other) {
  9078. for (k = 0, kMax = connectedNodes.length; k < kMax; k++) {
  9079. if (connectedNodes[k] == other) {
  9080. other = null;
  9081. break;
  9082. }
  9083. }
  9084. }
  9085. if (other)
  9086. connectedNodes.push(other);
  9087. }
  9088. }
  9089. return connectedNodes;
  9090. }
  9091. var connections = [];
  9092. var level0 = [];
  9093. var nodes = this.nodes;
  9094. var i, iMax;
  9095. for (i = 0, iMax = nodes.length; i < iMax; i++) {
  9096. var c = [nodes[i]];
  9097. for (var l = 0; l < level; l++) {
  9098. c = c.concat(getConnectedNodes(c));
  9099. }
  9100. connections.push(c);
  9101. }
  9102. var hubs = [];
  9103. for (i = 0, len = connections.length; i < len; i++) {
  9104. hubs.push(connections[i].length);
  9105. }
  9106. return hubs;
  9107. };
  9108. /**
  9109. * Set a new size for the graph
  9110. * @param {string} width Width in pixels or percentage (for example "800px"
  9111. * or "50%")
  9112. * @param {string} height Height in pixels or percentage (for example "400px"
  9113. * or "30%")
  9114. */
  9115. Graph.prototype.setSize = function(width, height) {
  9116. this.frame.style.width = width;
  9117. this.frame.style.height = height;
  9118. this.frame.canvas.style.width = "100%";
  9119. this.frame.canvas.style.height = "100%";
  9120. this.frame.canvas.width = this.frame.canvas.clientWidth;
  9121. this.frame.canvas.height = this.frame.canvas.clientHeight;
  9122. };
  9123. /**
  9124. * Set a data set with nodes for the graph
  9125. * @param {Array} nodes The data containing the nodes.
  9126. * @private
  9127. */
  9128. Graph.prototype._setNodes = function(nodes) {
  9129. this.selection = [];
  9130. this.nodes = [];
  9131. this.moving = false;
  9132. if (!nodes) {
  9133. return;
  9134. }
  9135. var hasValues = false;
  9136. var rowCount = nodes.length;
  9137. for (var i = 0; i < rowCount; i++) {
  9138. var properties = nodes[i];
  9139. if (properties.value != undefined) {
  9140. hasValues = true;
  9141. }
  9142. if (properties.id == undefined) {
  9143. throw "Column 'id' missing in table with nodes (row " + i + ")";
  9144. }
  9145. this._createNode(properties);
  9146. }
  9147. // calculate scaling function when value is provided
  9148. if (hasValues) {
  9149. this._updateValueRange(this.nodes);
  9150. }
  9151. // give the nodes some first (random) position
  9152. this._reposition(); // TODO: bad solution
  9153. };
  9154. /**
  9155. * Create a node with the given properties
  9156. * If the new node has an id identical to an existing node, the existing
  9157. * node will be overwritten.
  9158. * The properties can contain a property "action", which can have values
  9159. * "create", "update", or "delete"
  9160. * @param {Object} properties An object with properties
  9161. * @private
  9162. */
  9163. Graph.prototype._createNode = function(properties) {
  9164. var action = properties.action ? properties.action : "update";
  9165. var id, index, newNode, oldNode;
  9166. if (action === "create") {
  9167. // create the node
  9168. newNode = new Node(properties, this.images, this.groups, this.constants);
  9169. id = properties.id;
  9170. index = (id !== undefined) ? this._findNode(id) : undefined;
  9171. if (index !== undefined) {
  9172. // replace node
  9173. oldNode = this.nodes[index];
  9174. this.nodes[index] = newNode;
  9175. // remove selection of old node
  9176. if (oldNode.selected) {
  9177. this._unselectNodes([{'row': index}], false);
  9178. }
  9179. /* TODO: implement this? -> will give performance issues, searching all edges and nodes...
  9180. // update edges linking to this node
  9181. var edgesTable = this.edges;
  9182. for (var i = 0, iMax = edgesTable.length; i < iMax; i++) {
  9183. var edge = edgesTable[i];
  9184. if (edge.from == oldNode) {
  9185. edge.from = newNode;
  9186. }
  9187. if (edge.to == oldNode) {
  9188. edge.to = newNode;
  9189. }
  9190. }
  9191. */
  9192. }
  9193. else {
  9194. // add new node
  9195. this.nodes.push(newNode);
  9196. }
  9197. if (!newNode.isFixed()) {
  9198. // note: no not use node.isMoving() here, as that gives the current
  9199. // velocity of the node, which is zero after creation of the node.
  9200. this.moving = true;
  9201. }
  9202. }
  9203. else if (action === "update") {
  9204. // update existing node, or create it when not yet existing
  9205. id = properties.id;
  9206. if (id === undefined) {
  9207. throw "Cannot update a node without id";
  9208. }
  9209. index = this._findNode(id);
  9210. if (index !== undefined) {
  9211. // update node
  9212. this.nodes[index].setProperties(properties, this.constants);
  9213. }
  9214. else {
  9215. // create node
  9216. newNode = new Node(properties, this.images, this.groups, this.constants);
  9217. this.nodes.push(newNode);
  9218. if (!newNode.isFixed()) {
  9219. // note: no not use node.isMoving() here, as that gives the current
  9220. // velocity of the node, which is zero after creation of the node.
  9221. this.moving = true;
  9222. }
  9223. }
  9224. }
  9225. else if (action === "delete") {
  9226. // delete existing node
  9227. id = properties.id;
  9228. if (id === undefined) {
  9229. throw "Cannot delete node without its id";
  9230. }
  9231. index = this._findNode(id);
  9232. if (index !== undefined) {
  9233. oldNode = this.nodes[index];
  9234. // remove selection of old node
  9235. if (oldNode.selected) {
  9236. this._unselectNodes([{'row': index}], false);
  9237. }
  9238. this.nodes.splice(index, 1);
  9239. }
  9240. else {
  9241. throw "Node with id " + id + " not found";
  9242. }
  9243. }
  9244. else {
  9245. throw "Unknown action " + action + ". Choose 'create', 'update', or 'delete'.";
  9246. }
  9247. };
  9248. /**
  9249. * Find a node by its id
  9250. * @param {Number} id Id of the node
  9251. * @return {Number | undefined} index Index of the node in the array
  9252. * this.nodes, or undefined when not found
  9253. * @private
  9254. */
  9255. Graph.prototype._findNode = function (id) {
  9256. var nodes = this.nodes;
  9257. for (var n = 0, len = nodes.length; n < len; n++) {
  9258. if (nodes[n].id === id) {
  9259. return n;
  9260. }
  9261. }
  9262. return undefined;
  9263. };
  9264. /**
  9265. * Find a node by its rowNumber
  9266. * @param {Number} row Row number of the node
  9267. * @return {Node} node     The node with the given row number, or
  9268. *                            undefined when not found.
  9269. * @private
  9270. */
  9271. Graph.prototype._findNodeByRow = function (row) {
  9272. return this.nodes[row];
  9273. };
  9274. /**
  9275. * Load edges by reading the data table
  9276. * @param {Array} edges The data containing the edges.
  9277. * @private
  9278. * @private
  9279. */
  9280. Graph.prototype._setEdges = function(edges) {
  9281. this.edges = [];
  9282. if (!edges) {
  9283. return;
  9284. }
  9285. var hasValues = false;
  9286. var rowCount = edges.length;
  9287. for (var i = 0; i < rowCount; i++) {
  9288. var properties = edges[i];
  9289. if (properties.from === undefined) {
  9290. throw "Column 'from' missing in table with edges (row " + i + ")";
  9291. }
  9292. if (properties.to === undefined) {
  9293. throw "Column 'to' missing in table with edges (row " + i + ")";
  9294. }
  9295. if (properties.value != undefined) {
  9296. hasValues = true;
  9297. }
  9298. this._createEdge(properties);
  9299. }
  9300. // calculate scaling function when value is provided
  9301. if (hasValues) {
  9302. this._updateValueRange(this.edges);
  9303. }
  9304. };
  9305. /**
  9306. * Create a edge with the given properties
  9307. * If the new edge has an id identical to an existing edge, the existing
  9308. * edge will be overwritten or updated.
  9309. * The properties can contain a property "action", which can have values
  9310. * "create", "update", or "delete"
  9311. * @param {Object} properties An object with properties
  9312. * @private
  9313. */
  9314. Graph.prototype._createEdge = function(properties) {
  9315. var action = properties.action ? properties.action : "create";
  9316. var id, index, edge, oldEdge, newEdge;
  9317. if (action === "create") {
  9318. // create the edge, or replace it if already existing
  9319. id = properties.id;
  9320. index = (id !== undefined) ? this._findEdge(id) : undefined;
  9321. edge = new Edge(properties, this, this.constants);
  9322. if (index !== undefined) {
  9323. // replace existing edge
  9324. oldEdge = this.edges[index];
  9325. oldEdge.from.detachEdge(oldEdge);
  9326. oldEdge.to.detachEdge(oldEdge);
  9327. this.edges[index] = edge;
  9328. }
  9329. else {
  9330. // add new edge
  9331. this.edges.push(edge);
  9332. }
  9333. edge.from.attachEdge(edge);
  9334. edge.to.attachEdge(edge);
  9335. }
  9336. else if (action === "update") {
  9337. // update existing edge, or create the edge if not existing
  9338. id = properties.id;
  9339. if (id === undefined) {
  9340. throw "Cannot update a edge without id";
  9341. }
  9342. index = this._findEdge(id);
  9343. if (index !== undefined) {
  9344. // update edge
  9345. edge = this.edges[index];
  9346. edge.from.detachEdge(edge);
  9347. edge.to.detachEdge(edge);
  9348. edge.setProperties(properties, this.constants);
  9349. edge.from.attachEdge(edge);
  9350. edge.to.attachEdge(edge);
  9351. }
  9352. else {
  9353. // add new edge
  9354. edge = new Edge(properties, this, this.constants);
  9355. edge.from.attachEdge(edge);
  9356. edge.to.attachEdge(edge);
  9357. this.edges.push(edge);
  9358. }
  9359. }
  9360. else if (action === "delete") {
  9361. // delete existing edge
  9362. id = properties.id;
  9363. if (id === undefined) {
  9364. throw "Cannot delete edge without its id";
  9365. }
  9366. index = this._findEdge(id);
  9367. if (index !== undefined) {
  9368. oldEdge = this.edges[id];
  9369. edge.from.detachEdge(oldEdge);
  9370. edge.to.detachEdge(oldEdge);
  9371. this.edges.splice(index, 1);
  9372. }
  9373. else {
  9374. throw "Edge with id " + id + " not found";
  9375. }
  9376. }
  9377. else {
  9378. throw "Unknown action " + action + ". Choose 'create', 'update', or 'delete'.";
  9379. }
  9380. };
  9381. /**
  9382. * Update the references to oldNode in all edges.
  9383. * @param {Node} oldNode
  9384. * @param {Node} newNode
  9385. * @private
  9386. */
  9387. // TODO: start utilizing this method _updateNodeReferences
  9388. Graph.prototype._updateNodeReferences = function(oldNode, newNode) {
  9389. var edges = this.edges;
  9390. for (var i = 0, iMax = edges.length; i < iMax; i++) {
  9391. var edge = edges[i];
  9392. if (edge.from === oldNode) {
  9393. edge.from = newNode;
  9394. }
  9395. if (edge.to === oldNode) {
  9396. edge.to = newNode;
  9397. }
  9398. }
  9399. };
  9400. /**
  9401. * Find a edge by its id
  9402. * @param {Number} id Id of the edge
  9403. * @return {Number | undefined} index Index of the edge in the array
  9404. * this.edges, or undefined when not found
  9405. * @private
  9406. */
  9407. Graph.prototype._findEdge = function (id) {
  9408. var edges = this.edges;
  9409. for (var n = 0, len = edges.length; n < len; n++) {
  9410. if (edges[n].id === id) {
  9411. return n;
  9412. }
  9413. }
  9414. return undefined;
  9415. };
  9416. /**
  9417. * Find a edge by its row
  9418. * @param {Number} row Row of the edge
  9419. * @return {Edge | undefined} the found edge, or undefined when not found
  9420. * @private
  9421. */
  9422. Graph.prototype._findEdgeByRow = function (row) {
  9423. return this.edges[row];
  9424. };
  9425. /**
  9426. * Update the values of all object in the given array according to the current
  9427. * value range of the objects in the array.
  9428. * @param {Array} array. An array with objects like Edges or Nodes
  9429. * The objects must have a method getValue() and
  9430. * setValueRange(min, max).
  9431. * @private
  9432. */
  9433. Graph.prototype._updateValueRange = function(array) {
  9434. var count = array.length;
  9435. var i;
  9436. // determine the range of the node values
  9437. var valueMin = undefined;
  9438. var valueMax = undefined;
  9439. for (i = 0; i < count; i++) {
  9440. var value = array[i].getValue();
  9441. if (value !== undefined) {
  9442. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  9443. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  9444. }
  9445. }
  9446. // adjust the range of all nodes
  9447. if (valueMin !== undefined && valueMax !== undefined) {
  9448. for (i = 0; i < count; i++) {
  9449. array[i].setValueRange(valueMin, valueMax);
  9450. }
  9451. }
  9452. };
  9453. /**
  9454. * Redraw the graph with the current data
  9455. * chart will be resized too.
  9456. */
  9457. Graph.prototype.redraw = function() {
  9458. this.setSize(this.width, this.height);
  9459. this._redraw();
  9460. };
  9461. /**
  9462. * Redraw the graph with the current data
  9463. * @private
  9464. */
  9465. Graph.prototype._redraw = function() {
  9466. var ctx = this.frame.canvas.getContext("2d");
  9467. // clear the canvas
  9468. var w = this.frame.canvas.width;
  9469. var h = this.frame.canvas.height;
  9470. ctx.clearRect(0, 0, w, h);
  9471. // set scaling and translation
  9472. ctx.save();
  9473. ctx.translate(this.translation.x, this.translation.y);
  9474. ctx.scale(this.scale, this.scale);
  9475. this._drawEdges(ctx);
  9476. this._drawNodes(ctx);
  9477. // restore original scaling and translation
  9478. ctx.restore();
  9479. };
  9480. /**
  9481. * Set the translation of the graph
  9482. * @param {Number} offsetX Horizontal offset
  9483. * @param {Number} offsetY Vertical offset
  9484. * @private
  9485. */
  9486. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  9487. if (this.translation === undefined) {
  9488. this.translation = {
  9489. "x": 0,
  9490. "y": 0
  9491. };
  9492. }
  9493. if (offsetX !== undefined) {
  9494. this.translation.x = offsetX;
  9495. }
  9496. if (offsetY !== undefined) {
  9497. this.translation.y = offsetY;
  9498. }
  9499. };
  9500. /**
  9501. * Get the translation of the graph
  9502. * @return {Object} translation An object with parameters x and y, both a number
  9503. * @private
  9504. */
  9505. Graph.prototype._getTranslation = function() {
  9506. return {
  9507. "x": this.translation.x,
  9508. "y": this.translation.y
  9509. };
  9510. };
  9511. /**
  9512. * Scale the graph
  9513. * @param {Number} scale Scaling factor 1.0 is unscaled
  9514. * @private
  9515. */
  9516. Graph.prototype._setScale = function(scale) {
  9517. this.scale = scale;
  9518. };
  9519. /**
  9520. * Get the current scale of the graph
  9521. * @return {Number} scale Scaling factor 1.0 is unscaled
  9522. * @private
  9523. */
  9524. Graph.prototype._getScale = function() {
  9525. return this.scale;
  9526. };
  9527. Graph.prototype._xToCanvas = function(x) {
  9528. return (x - this.translation.x) / this.scale;
  9529. };
  9530. Graph.prototype._canvasToX = function(x) {
  9531. return x * this.scale + this.translation.x;
  9532. };
  9533. Graph.prototype._yToCanvas = function(y) {
  9534. return (y - this.translation.y) / this.scale;
  9535. };
  9536. Graph.prototype._canvasToY = function(y) {
  9537. return y * this.scale + this.translation.y ;
  9538. };
  9539. /**
  9540. * Get a node by its id
  9541. * @param {number} id
  9542. * @return {Node} node, or null if not found
  9543. * @private
  9544. */
  9545. Graph.prototype._getNode = function(id) {
  9546. for (var i = 0; i < this.nodes.length; i++) {
  9547. if (this.nodes[i].id == id)
  9548. return this.nodes[i];
  9549. }
  9550. return null;
  9551. };
  9552. /**
  9553. * Redraw all nodes
  9554. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9555. * @param {CanvasRenderingContext2D} ctx
  9556. * @private
  9557. */
  9558. Graph.prototype._drawNodes = function(ctx) {
  9559. // first draw the unselected nodes
  9560. var nodes = this.nodes;
  9561. var selected = [];
  9562. for (var i = 0, iMax = nodes.length; i < iMax; i++) {
  9563. if (nodes[i].isSelected()) {
  9564. selected.push(i);
  9565. }
  9566. else {
  9567. nodes[i].draw(ctx);
  9568. }
  9569. }
  9570. // draw the selected nodes on top
  9571. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  9572. nodes[selected[s]].draw(ctx);
  9573. }
  9574. };
  9575. /**
  9576. * Redraw all edges
  9577. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9578. * @param {CanvasRenderingContext2D} ctx
  9579. * @private
  9580. */
  9581. Graph.prototype._drawEdges = function(ctx) {
  9582. var edges = this.edges;
  9583. for (var i = 0, iMax = edges.length; i < iMax; i++) {
  9584. edges[i].draw(ctx);
  9585. }
  9586. };
  9587. /**
  9588. * Recalculate the best positions for all nodes
  9589. * @private
  9590. */
  9591. Graph.prototype._reposition = function() {
  9592. // TODO: implement function reposition
  9593. /*
  9594. var w = this.frame.canvas.clientWidth;
  9595. var h = this.frame.canvas.clientHeight;
  9596. for (var i = 0; i < this.nodes.length; i++) {
  9597. if (!this.nodes[i].xFixed) this.nodes[i].x = w * Math.random();
  9598. if (!this.nodes[i].yFixed) this.nodes[i].y = h * Math.random();
  9599. }
  9600. //*/
  9601. //*
  9602. // TODO
  9603. var radius = this.constants.edges.length * 2;
  9604. var cx = this.frame.canvas.clientWidth / 2;
  9605. var cy = this.frame.canvas.clientHeight / 2;
  9606. for (var i = 0; i < this.nodes.length; i++) {
  9607. var angle = 2*Math.PI * (i / this.nodes.length);
  9608. if (!this.nodes[i].xFixed) this.nodes[i].x = cx + radius * Math.cos(angle);
  9609. if (!this.nodes[i].yFixed) this.nodes[i].y = cy + radius * Math.sin(angle);
  9610. }
  9611. //*/
  9612. /*
  9613. // TODO
  9614. var radius = this.constants.edges.length * 2;
  9615. var w = this.frame.canvas.clientWidth,
  9616. h = this.frame.canvas.clientHeight;
  9617. var cx = this.frame.canvas.clientWidth / 2;
  9618. var cy = this.frame.canvas.clientHeight / 2;
  9619. var s = Math.sqrt(this.nodes.length);
  9620. for (var i = 0; i < this.nodes.length; i++) {
  9621. //var angle = 2*Math.PI * (i / this.nodes.length);
  9622. if (!this.nodes[i].xFixed) this.nodes[i].x = w/s * (i % s);
  9623. if (!this.nodes[i].yFixed) this.nodes[i].y = h/s * (i / s);
  9624. }
  9625. //*/
  9626. /*
  9627. var cx = this.frame.canvas.clientWidth / 2;
  9628. var cy = this.frame.canvas.clientHeight / 2;
  9629. for (var i = 0; i < this.nodes.length; i++) {
  9630. this.nodes[i].x = cx;
  9631. this.nodes[i].y = cy;
  9632. }
  9633. //*/
  9634. };
  9635. /**
  9636. * Find a stable position for all nodes
  9637. * @private
  9638. */
  9639. Graph.prototype._doStabilize = function() {
  9640. var start = new Date();
  9641. // find stable position
  9642. var count = 0;
  9643. var vmin = this.constants.minVelocity;
  9644. var stable = false;
  9645. while (!stable && count < this.constants.maxIterations) {
  9646. this._calculateForces();
  9647. this._discreteStepNodes();
  9648. stable = !this._isMoving(vmin);
  9649. count++;
  9650. }
  9651. var end = new Date();
  9652. // console.log("Stabilized in " + (end-start) + " ms, " + count + " iterations" ); // TODO: cleanup
  9653. };
  9654. /**
  9655. * Calculate the external forces acting on the nodes
  9656. * Forces are caused by: edges, repulsing forces between nodes, gravity
  9657. * @private
  9658. */
  9659. Graph.prototype._calculateForces = function() {
  9660. // create a local edge to the nodes and edges, that is faster
  9661. var nodes = this.nodes,
  9662. edges = this.edges;
  9663. // gravity, add a small constant force to pull the nodes towards the center of
  9664. // the graph
  9665. // Also, the forces are reset to zero in this loop by using _setForce instead
  9666. // of _addForce
  9667. var gravity = 0.01,
  9668. gx = this.frame.canvas.clientWidth / 2,
  9669. gy = this.frame.canvas.clientHeight / 2;
  9670. for (var n = 0; n < nodes.length; n++) {
  9671. var dx = gx - nodes[n].x,
  9672. dy = gy - nodes[n].y,
  9673. angle = Math.atan2(dy, dx),
  9674. fx = Math.cos(angle) * gravity,
  9675. fy = Math.sin(angle) * gravity;
  9676. this.nodes[n]._setForce(fx, fy);
  9677. }
  9678. // repulsing forces between nodes
  9679. var minimumDistance = this.constants.nodes.distance,
  9680. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  9681. for (var n = 0; n < nodes.length; n++) {
  9682. for (var n2 = n + 1; n2 < this.nodes.length; n2++) {
  9683. //var dmin = (nodes[n].width + nodes[n].height + nodes[n2].width + nodes[n2].height) / 1 || minimumDistance, // TODO: dmin
  9684. //var dmin = (nodes[n].width + nodes[n2].width)/2 || minimumDistance, // TODO: dmin
  9685. //dmin = 40 + ((nodes[n].width/2 + nodes[n2].width/2) || 0),
  9686. // calculate normally distributed force
  9687. var dx = nodes[n2].x - nodes[n].x,
  9688. dy = nodes[n2].y - nodes[n].y,
  9689. distance = Math.sqrt(dx * dx + dy * dy),
  9690. angle = Math.atan2(dy, dx),
  9691. // TODO: correct factor for repulsing force
  9692. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  9693. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  9694. repulsingforce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)), // TODO: customize the repulsing force
  9695. fx = Math.cos(angle) * repulsingforce,
  9696. fy = Math.sin(angle) * repulsingforce;
  9697. this.nodes[n]._addForce(-fx, -fy);
  9698. this.nodes[n2]._addForce(fx, fy);
  9699. }
  9700. /* TODO: re-implement repulsion of edges
  9701. for (var l = 0; l < edges.length; l++) {
  9702. var lx = edges[l].from.x+(edges[l].to.x - edges[l].from.x)/2,
  9703. ly = edges[l].from.y+(edges[l].to.y - edges[l].from.y)/2,
  9704. // calculate normally distributed force
  9705. dx = nodes[n].x - lx,
  9706. dy = nodes[n].y - ly,
  9707. distance = Math.sqrt(dx * dx + dy * dy),
  9708. angle = Math.atan2(dy, dx),
  9709. // TODO: correct factor for repulsing force
  9710. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  9711. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  9712. repulsingforce = 1 / (1 + Math.exp((distance / (minimumDistance / 2) - 1) * steepness)), // TODO: customize the repulsing force
  9713. fx = Math.cos(angle) * repulsingforce,
  9714. fy = Math.sin(angle) * repulsingforce;
  9715. nodes[n]._addForce(fx, fy);
  9716. edges[l].from._addForce(-fx/2,-fy/2);
  9717. edges[l].to._addForce(-fx/2,-fy/2);
  9718. }
  9719. */
  9720. }
  9721. // forces caused by the edges, modelled as springs
  9722. for (var l = 0, lMax = edges.length; l < lMax; l++) {
  9723. var edge = edges[l],
  9724. dx = (edge.to.x - edge.from.x),
  9725. dy = (edge.to.y - edge.from.y),
  9726. //edgeLength = (edge.from.width + edge.from.height + edge.to.width + edge.to.height)/2 || edge.length, // TODO: dmin
  9727. //edgeLength = (edge.from.width + edge.to.width)/2 || edge.length, // TODO: dmin
  9728. //edgeLength = 20 + ((edge.from.width + edge.to.width) || 0) / 2,
  9729. edgeLength = edge.length,
  9730. length = Math.sqrt(dx * dx + dy * dy),
  9731. angle = Math.atan2(dy, dx),
  9732. springforce = edge.stiffness * (edgeLength - length),
  9733. fx = Math.cos(angle) * springforce,
  9734. fy = Math.sin(angle) * springforce;
  9735. edge.from._addForce(-fx, -fy);
  9736. edge.to._addForce(fx, fy);
  9737. }
  9738. /* TODO: re-implement repulsion of edges
  9739. // repulsing forces between edges
  9740. var minimumDistance = this.constants.edges.distance,
  9741. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  9742. for (var l = 0; l < edges.length; l++) {
  9743. //Keep distance from other edge centers
  9744. for (var l2 = l + 1; l2 < this.edges.length; l2++) {
  9745. //var dmin = (nodes[n].width + nodes[n].height + nodes[n2].width + nodes[n2].height) / 1 || minimumDistance, // TODO: dmin
  9746. //var dmin = (nodes[n].width + nodes[n2].width)/2 || minimumDistance, // TODO: dmin
  9747. //dmin = 40 + ((nodes[n].width/2 + nodes[n2].width/2) || 0),
  9748. var lx = edges[l].from.x+(edges[l].to.x - edges[l].from.x)/2,
  9749. ly = edges[l].from.y+(edges[l].to.y - edges[l].from.y)/2,
  9750. l2x = edges[l2].from.x+(edges[l2].to.x - edges[l2].from.x)/2,
  9751. l2y = edges[l2].from.y+(edges[l2].to.y - edges[l2].from.y)/2,
  9752. // calculate normally distributed force
  9753. dx = l2x - lx,
  9754. dy = l2y - ly,
  9755. distance = Math.sqrt(dx * dx + dy * dy),
  9756. angle = Math.atan2(dy, dx),
  9757. // TODO: correct factor for repulsing force
  9758. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  9759. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  9760. repulsingforce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)), // TODO: customize the repulsing force
  9761. fx = Math.cos(angle) * repulsingforce,
  9762. fy = Math.sin(angle) * repulsingforce;
  9763. edges[l].from._addForce(-fx, -fy);
  9764. edges[l].to._addForce(-fx, -fy);
  9765. edges[l2].from._addForce(fx, fy);
  9766. edges[l2].to._addForce(fx, fy);
  9767. }
  9768. }
  9769. */
  9770. };
  9771. /**
  9772. * Check if any of the nodes is still moving
  9773. * @param {number} vmin the minimum velocity considered as "moving"
  9774. * @return {boolean} true if moving, false if non of the nodes is moving
  9775. * @private
  9776. */
  9777. Graph.prototype._isMoving = function(vmin) {
  9778. // TODO: ismoving does not work well: should check the kinetic energy, not its velocity
  9779. var nodes = this.nodes;
  9780. for (var n = 0, nMax = nodes.length; n < nMax; n++) {
  9781. if (nodes[n].isMoving(vmin)) {
  9782. return true;
  9783. }
  9784. }
  9785. return false;
  9786. };
  9787. /**
  9788. * Perform one discrete step for all nodes
  9789. * @private
  9790. */
  9791. Graph.prototype._discreteStepNodes = function() {
  9792. var interval = this.refreshRate / 1000.0; // in seconds
  9793. var nodes = this.nodes;
  9794. for (var n = 0, nMax = nodes.length; n < nMax; n++) {
  9795. nodes[n].discreteStep(interval);
  9796. }
  9797. };
  9798. /**
  9799. * Start animating nodes and edges
  9800. */
  9801. Graph.prototype.start = function() {
  9802. if (this.moving) {
  9803. this._calculateForces();
  9804. this._discreteStepNodes();
  9805. var vmin = this.constants.minVelocity;
  9806. this.moving = this._isMoving(vmin);
  9807. }
  9808. if (this.moving) {
  9809. // start animation. only start timer if it is not already running
  9810. if (!this.timer) {
  9811. var graph = this;
  9812. this.timer = window.setTimeout(function () {
  9813. graph.timer = undefined;
  9814. graph.start();
  9815. graph._redraw();
  9816. }, this.refreshRate);
  9817. }
  9818. }
  9819. else {
  9820. this._redraw();
  9821. }
  9822. };
  9823. /**
  9824. * Stop animating nodes and edges.
  9825. */
  9826. Graph.prototype.stop = function () {
  9827. if (this.timer) {
  9828. window.clearInterval(this.timer);
  9829. this.timer = undefined;
  9830. }
  9831. };
  9832. /**
  9833. * vis.js module exports
  9834. */
  9835. var vis = {
  9836. util: util,
  9837. events: events,
  9838. Controller: Controller,
  9839. DataSet: DataSet,
  9840. DataView: DataView,
  9841. Range: Range,
  9842. Stack: Stack,
  9843. TimeStep: TimeStep,
  9844. EventBus: EventBus,
  9845. components: {
  9846. items: {
  9847. Item: Item,
  9848. ItemBox: ItemBox,
  9849. ItemPoint: ItemPoint,
  9850. ItemRange: ItemRange
  9851. },
  9852. Component: Component,
  9853. Panel: Panel,
  9854. RootPanel: RootPanel,
  9855. ItemSet: ItemSet,
  9856. TimeAxis: TimeAxis
  9857. },
  9858. graph: {
  9859. Node: Node,
  9860. Edge: Edge,
  9861. Popup: Popup,
  9862. Groups: Groups,
  9863. Images: Images
  9864. },
  9865. Timeline: Timeline,
  9866. Graph: Graph
  9867. };
  9868. /**
  9869. * CommonJS module exports
  9870. */
  9871. if (typeof exports !== 'undefined') {
  9872. exports = vis;
  9873. }
  9874. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  9875. module.exports = vis;
  9876. }
  9877. /**
  9878. * AMD module exports
  9879. */
  9880. if (typeof(define) === 'function') {
  9881. define(function () {
  9882. return vis;
  9883. });
  9884. }
  9885. /**
  9886. * Window exports
  9887. */
  9888. if (typeof window !== 'undefined') {
  9889. // attach the module to the window, load as a regular javascript file
  9890. window['vis'] = vis;
  9891. }
  9892. // inject css
  9893. util.loadCss("/* vis.js stylesheet */\n\n.graph {\n position: relative;\n border: 1px solid #bfbfbf;\n}\n\n.graph .panel {\n position: absolute;\n}\n\n.graph .groupset {\n position: absolute;\n padding: 0;\n margin: 0;\n}\n\n\n.graph .itemset {\n position: absolute;\n padding: 0;\n margin: 0;\n overflow: hidden;\n}\n\n.graph .background {\n}\n\n.graph .foreground {\n}\n\n.graph .itemset-axis {\n position: absolute;\n}\n\n.graph .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.graph .groupset .itemset-axis:last-child {\n border-top: none;\n}\n*/\n\n\n.graph .item {\n position: absolute;\n color: #1A1A1A;\n border-color: #97B0F8;\n background-color: #D5DDF6;\n display: inline-block;\n}\n\n.graph .item.selected {\n border-color: #FFC200;\n background-color: #FFF785;\n z-index: 999;\n}\n\n.graph .item.cluster {\n /* TODO: use another color or pattern? */\n background: #97B0F8 url('img/cluster_bg.png');\n color: white;\n}\n.graph .item.cluster.point {\n border-color: #D5DDF6;\n}\n\n.graph .item.box {\n text-align: center;\n border-style: solid;\n border-width: 1px;\n border-radius: 5px;\n -moz-border-radius: 5px; /* For Firefox 3.6 and older */\n}\n\n.graph .item.point {\n background: none;\n}\n\n.graph .dot {\n border: 5px solid #97B0F8;\n position: absolute;\n border-radius: 5px;\n -moz-border-radius: 5px; /* For Firefox 3.6 and older */\n}\n\n.graph .item.range {\n overflow: hidden;\n border-style: solid;\n border-width: 1px;\n border-radius: 2px;\n -moz-border-radius: 2px; /* For Firefox 3.6 and older */\n}\n\n.graph .item.range .drag-left {\n cursor: w-resize;\n z-index: 1000;\n}\n\n.graph .item.range .drag-right {\n cursor: e-resize;\n z-index: 1000;\n}\n\n.graph .item.range .content {\n position: relative;\n display: inline-block;\n}\n\n.graph .item.line {\n position: absolute;\n width: 0;\n border-left-width: 1px;\n border-left-style: solid;\n}\n\n.graph .item .content {\n margin: 5px;\n white-space: nowrap;\n overflow: hidden;\n}\n\n/* TODO: better css name, 'graph' is way to generic */\n\n.graph {\n overflow: hidden;\n}\n\n.graph .axis {\n position: relative;\n}\n\n.graph .axis .text {\n position: absolute;\n color: #4d4d4d;\n padding: 3px;\n white-space: nowrap;\n}\n\n.graph .axis .text.measure {\n position: absolute;\n padding-left: 0;\n padding-right: 0;\n margin-left: 0;\n margin-right: 0;\n visibility: hidden;\n}\n\n.graph .axis .grid.vertical {\n position: absolute;\n width: 0;\n border-right: 1px solid;\n}\n\n.graph .axis .grid.horizontal {\n position: absolute;\n left: 0;\n width: 100%;\n height: 0;\n border-bottom: 1px solid;\n}\n\n.graph .axis .grid.minor {\n border-color: #e5e5e5;\n}\n\n.graph .axis .grid.major {\n border-color: #bfbfbf;\n}\n\n");
  9894. })()
  9895. },{"moment":2}],2:[function(require,module,exports){
  9896. (function(){// moment.js
  9897. // version : 2.0.0
  9898. // author : Tim Wood
  9899. // license : MIT
  9900. // momentjs.com
  9901. (function (undefined) {
  9902. /************************************
  9903. Constants
  9904. ************************************/
  9905. var moment,
  9906. VERSION = "2.0.0",
  9907. round = Math.round, i,
  9908. // internal storage for language config files
  9909. languages = {},
  9910. // check for nodeJS
  9911. hasModule = (typeof module !== 'undefined' && module.exports),
  9912. // ASP.NET json date format regex
  9913. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  9914. // format tokens
  9915. 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,
  9916. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  9917. // parsing tokens
  9918. parseMultipleFormatChunker = /([0-9a-zA-Z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)/gi,
  9919. // parsing token regexes
  9920. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  9921. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  9922. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  9923. parseTokenFourDigits = /\d{1,4}/, // 0 - 9999
  9924. parseTokenSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  9925. 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.
  9926. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/i, // +00:00 -00:00 +0000 -0000 or Z
  9927. parseTokenT = /T/i, // T (ISO seperator)
  9928. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  9929. // preliminary iso regex
  9930. // 0000-00-00 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000
  9931. isoRegex = /^\s*\d{4}-\d\d-\d\d((T| )(\d\d(:\d\d(:\d\d(\.\d\d?\d?)?)?)?)?([\+\-]\d\d:?\d\d)?)?/,
  9932. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  9933. // iso time formats and regexes
  9934. isoTimes = [
  9935. ['HH:mm:ss.S', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/],
  9936. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  9937. ['HH:mm', /(T| )\d\d:\d\d/],
  9938. ['HH', /(T| )\d\d/]
  9939. ],
  9940. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  9941. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  9942. // getter and setter names
  9943. proxyGettersAndSetters = 'Month|Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  9944. unitMillisecondFactors = {
  9945. 'Milliseconds' : 1,
  9946. 'Seconds' : 1e3,
  9947. 'Minutes' : 6e4,
  9948. 'Hours' : 36e5,
  9949. 'Days' : 864e5,
  9950. 'Months' : 2592e6,
  9951. 'Years' : 31536e6
  9952. },
  9953. // format function strings
  9954. formatFunctions = {},
  9955. // tokens to ordinalize and pad
  9956. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  9957. paddedTokens = 'M D H h m s w W'.split(' '),
  9958. formatTokenFunctions = {
  9959. M : function () {
  9960. return this.month() + 1;
  9961. },
  9962. MMM : function (format) {
  9963. return this.lang().monthsShort(this, format);
  9964. },
  9965. MMMM : function (format) {
  9966. return this.lang().months(this, format);
  9967. },
  9968. D : function () {
  9969. return this.date();
  9970. },
  9971. DDD : function () {
  9972. return this.dayOfYear();
  9973. },
  9974. d : function () {
  9975. return this.day();
  9976. },
  9977. dd : function (format) {
  9978. return this.lang().weekdaysMin(this, format);
  9979. },
  9980. ddd : function (format) {
  9981. return this.lang().weekdaysShort(this, format);
  9982. },
  9983. dddd : function (format) {
  9984. return this.lang().weekdays(this, format);
  9985. },
  9986. w : function () {
  9987. return this.week();
  9988. },
  9989. W : function () {
  9990. return this.isoWeek();
  9991. },
  9992. YY : function () {
  9993. return leftZeroFill(this.year() % 100, 2);
  9994. },
  9995. YYYY : function () {
  9996. return leftZeroFill(this.year(), 4);
  9997. },
  9998. YYYYY : function () {
  9999. return leftZeroFill(this.year(), 5);
  10000. },
  10001. a : function () {
  10002. return this.lang().meridiem(this.hours(), this.minutes(), true);
  10003. },
  10004. A : function () {
  10005. return this.lang().meridiem(this.hours(), this.minutes(), false);
  10006. },
  10007. H : function () {
  10008. return this.hours();
  10009. },
  10010. h : function () {
  10011. return this.hours() % 12 || 12;
  10012. },
  10013. m : function () {
  10014. return this.minutes();
  10015. },
  10016. s : function () {
  10017. return this.seconds();
  10018. },
  10019. S : function () {
  10020. return ~~(this.milliseconds() / 100);
  10021. },
  10022. SS : function () {
  10023. return leftZeroFill(~~(this.milliseconds() / 10), 2);
  10024. },
  10025. SSS : function () {
  10026. return leftZeroFill(this.milliseconds(), 3);
  10027. },
  10028. Z : function () {
  10029. var a = -this.zone(),
  10030. b = "+";
  10031. if (a < 0) {
  10032. a = -a;
  10033. b = "-";
  10034. }
  10035. return b + leftZeroFill(~~(a / 60), 2) + ":" + leftZeroFill(~~a % 60, 2);
  10036. },
  10037. ZZ : function () {
  10038. var a = -this.zone(),
  10039. b = "+";
  10040. if (a < 0) {
  10041. a = -a;
  10042. b = "-";
  10043. }
  10044. return b + leftZeroFill(~~(10 * a / 6), 4);
  10045. },
  10046. X : function () {
  10047. return this.unix();
  10048. }
  10049. };
  10050. function padToken(func, count) {
  10051. return function (a) {
  10052. return leftZeroFill(func.call(this, a), count);
  10053. };
  10054. }
  10055. function ordinalizeToken(func) {
  10056. return function (a) {
  10057. return this.lang().ordinal(func.call(this, a));
  10058. };
  10059. }
  10060. while (ordinalizeTokens.length) {
  10061. i = ordinalizeTokens.pop();
  10062. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i]);
  10063. }
  10064. while (paddedTokens.length) {
  10065. i = paddedTokens.pop();
  10066. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  10067. }
  10068. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  10069. /************************************
  10070. Constructors
  10071. ************************************/
  10072. function Language() {
  10073. }
  10074. // Moment prototype object
  10075. function Moment(config) {
  10076. extend(this, config);
  10077. }
  10078. // Duration Constructor
  10079. function Duration(duration) {
  10080. var data = this._data = {},
  10081. years = duration.years || duration.year || duration.y || 0,
  10082. months = duration.months || duration.month || duration.M || 0,
  10083. weeks = duration.weeks || duration.week || duration.w || 0,
  10084. days = duration.days || duration.day || duration.d || 0,
  10085. hours = duration.hours || duration.hour || duration.h || 0,
  10086. minutes = duration.minutes || duration.minute || duration.m || 0,
  10087. seconds = duration.seconds || duration.second || duration.s || 0,
  10088. milliseconds = duration.milliseconds || duration.millisecond || duration.ms || 0;
  10089. // representation for dateAddRemove
  10090. this._milliseconds = milliseconds +
  10091. seconds * 1e3 + // 1000
  10092. minutes * 6e4 + // 1000 * 60
  10093. hours * 36e5; // 1000 * 60 * 60
  10094. // Because of dateAddRemove treats 24 hours as different from a
  10095. // day when working around DST, we need to store them separately
  10096. this._days = days +
  10097. weeks * 7;
  10098. // It is impossible translate months into days without knowing
  10099. // which months you are are talking about, so we have to store
  10100. // it separately.
  10101. this._months = months +
  10102. years * 12;
  10103. // The following code bubbles up values, see the tests for
  10104. // examples of what that means.
  10105. data.milliseconds = milliseconds % 1000;
  10106. seconds += absRound(milliseconds / 1000);
  10107. data.seconds = seconds % 60;
  10108. minutes += absRound(seconds / 60);
  10109. data.minutes = minutes % 60;
  10110. hours += absRound(minutes / 60);
  10111. data.hours = hours % 24;
  10112. days += absRound(hours / 24);
  10113. days += weeks * 7;
  10114. data.days = days % 30;
  10115. months += absRound(days / 30);
  10116. data.months = months % 12;
  10117. years += absRound(months / 12);
  10118. data.years = years;
  10119. }
  10120. /************************************
  10121. Helpers
  10122. ************************************/
  10123. function extend(a, b) {
  10124. for (var i in b) {
  10125. if (b.hasOwnProperty(i)) {
  10126. a[i] = b[i];
  10127. }
  10128. }
  10129. return a;
  10130. }
  10131. function absRound(number) {
  10132. if (number < 0) {
  10133. return Math.ceil(number);
  10134. } else {
  10135. return Math.floor(number);
  10136. }
  10137. }
  10138. // left zero fill a number
  10139. // see http://jsperf.com/left-zero-filling for performance comparison
  10140. function leftZeroFill(number, targetLength) {
  10141. var output = number + '';
  10142. while (output.length < targetLength) {
  10143. output = '0' + output;
  10144. }
  10145. return output;
  10146. }
  10147. // helper function for _.addTime and _.subtractTime
  10148. function addOrSubtractDurationFromMoment(mom, duration, isAdding) {
  10149. var ms = duration._milliseconds,
  10150. d = duration._days,
  10151. M = duration._months,
  10152. currentDate;
  10153. if (ms) {
  10154. mom._d.setTime(+mom + ms * isAdding);
  10155. }
  10156. if (d) {
  10157. mom.date(mom.date() + d * isAdding);
  10158. }
  10159. if (M) {
  10160. currentDate = mom.date();
  10161. mom.date(1)
  10162. .month(mom.month() + M * isAdding)
  10163. .date(Math.min(currentDate, mom.daysInMonth()));
  10164. }
  10165. }
  10166. // check if is an array
  10167. function isArray(input) {
  10168. return Object.prototype.toString.call(input) === '[object Array]';
  10169. }
  10170. // compare two arrays, return the number of differences
  10171. function compareArrays(array1, array2) {
  10172. var len = Math.min(array1.length, array2.length),
  10173. lengthDiff = Math.abs(array1.length - array2.length),
  10174. diffs = 0,
  10175. i;
  10176. for (i = 0; i < len; i++) {
  10177. if (~~array1[i] !== ~~array2[i]) {
  10178. diffs++;
  10179. }
  10180. }
  10181. return diffs + lengthDiff;
  10182. }
  10183. /************************************
  10184. Languages
  10185. ************************************/
  10186. Language.prototype = {
  10187. set : function (config) {
  10188. var prop, i;
  10189. for (i in config) {
  10190. prop = config[i];
  10191. if (typeof prop === 'function') {
  10192. this[i] = prop;
  10193. } else {
  10194. this['_' + i] = prop;
  10195. }
  10196. }
  10197. },
  10198. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  10199. months : function (m) {
  10200. return this._months[m.month()];
  10201. },
  10202. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  10203. monthsShort : function (m) {
  10204. return this._monthsShort[m.month()];
  10205. },
  10206. monthsParse : function (monthName) {
  10207. var i, mom, regex, output;
  10208. if (!this._monthsParse) {
  10209. this._monthsParse = [];
  10210. }
  10211. for (i = 0; i < 12; i++) {
  10212. // make the regex if we don't have it already
  10213. if (!this._monthsParse[i]) {
  10214. mom = moment([2000, i]);
  10215. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  10216. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  10217. }
  10218. // test the regex
  10219. if (this._monthsParse[i].test(monthName)) {
  10220. return i;
  10221. }
  10222. }
  10223. },
  10224. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  10225. weekdays : function (m) {
  10226. return this._weekdays[m.day()];
  10227. },
  10228. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  10229. weekdaysShort : function (m) {
  10230. return this._weekdaysShort[m.day()];
  10231. },
  10232. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  10233. weekdaysMin : function (m) {
  10234. return this._weekdaysMin[m.day()];
  10235. },
  10236. _longDateFormat : {
  10237. LT : "h:mm A",
  10238. L : "MM/DD/YYYY",
  10239. LL : "MMMM D YYYY",
  10240. LLL : "MMMM D YYYY LT",
  10241. LLLL : "dddd, MMMM D YYYY LT"
  10242. },
  10243. longDateFormat : function (key) {
  10244. var output = this._longDateFormat[key];
  10245. if (!output && this._longDateFormat[key.toUpperCase()]) {
  10246. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  10247. return val.slice(1);
  10248. });
  10249. this._longDateFormat[key] = output;
  10250. }
  10251. return output;
  10252. },
  10253. meridiem : function (hours, minutes, isLower) {
  10254. if (hours > 11) {
  10255. return isLower ? 'pm' : 'PM';
  10256. } else {
  10257. return isLower ? 'am' : 'AM';
  10258. }
  10259. },
  10260. _calendar : {
  10261. sameDay : '[Today at] LT',
  10262. nextDay : '[Tomorrow at] LT',
  10263. nextWeek : 'dddd [at] LT',
  10264. lastDay : '[Yesterday at] LT',
  10265. lastWeek : '[last] dddd [at] LT',
  10266. sameElse : 'L'
  10267. },
  10268. calendar : function (key, mom) {
  10269. var output = this._calendar[key];
  10270. return typeof output === 'function' ? output.apply(mom) : output;
  10271. },
  10272. _relativeTime : {
  10273. future : "in %s",
  10274. past : "%s ago",
  10275. s : "a few seconds",
  10276. m : "a minute",
  10277. mm : "%d minutes",
  10278. h : "an hour",
  10279. hh : "%d hours",
  10280. d : "a day",
  10281. dd : "%d days",
  10282. M : "a month",
  10283. MM : "%d months",
  10284. y : "a year",
  10285. yy : "%d years"
  10286. },
  10287. relativeTime : function (number, withoutSuffix, string, isFuture) {
  10288. var output = this._relativeTime[string];
  10289. return (typeof output === 'function') ?
  10290. output(number, withoutSuffix, string, isFuture) :
  10291. output.replace(/%d/i, number);
  10292. },
  10293. pastFuture : function (diff, output) {
  10294. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  10295. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  10296. },
  10297. ordinal : function (number) {
  10298. return this._ordinal.replace("%d", number);
  10299. },
  10300. _ordinal : "%d",
  10301. preparse : function (string) {
  10302. return string;
  10303. },
  10304. postformat : function (string) {
  10305. return string;
  10306. },
  10307. week : function (mom) {
  10308. return weekOfYear(mom, this._week.dow, this._week.doy);
  10309. },
  10310. _week : {
  10311. dow : 0, // Sunday is the first day of the week.
  10312. doy : 6 // The week that contains Jan 1st is the first week of the year.
  10313. }
  10314. };
  10315. // Loads a language definition into the `languages` cache. The function
  10316. // takes a key and optionally values. If not in the browser and no values
  10317. // are provided, it will load the language file module. As a convenience,
  10318. // this function also returns the language values.
  10319. function loadLang(key, values) {
  10320. values.abbr = key;
  10321. if (!languages[key]) {
  10322. languages[key] = new Language();
  10323. }
  10324. languages[key].set(values);
  10325. return languages[key];
  10326. }
  10327. // Determines which language definition to use and returns it.
  10328. //
  10329. // With no parameters, it will return the global language. If you
  10330. // pass in a language key, such as 'en', it will return the
  10331. // definition for 'en', so long as 'en' has already been loaded using
  10332. // moment.lang.
  10333. function getLangDefinition(key) {
  10334. if (!key) {
  10335. return moment.fn._lang;
  10336. }
  10337. if (!languages[key] && hasModule) {
  10338. require('./lang/' + key);
  10339. }
  10340. return languages[key];
  10341. }
  10342. /************************************
  10343. Formatting
  10344. ************************************/
  10345. function removeFormattingTokens(input) {
  10346. if (input.match(/\[.*\]/)) {
  10347. return input.replace(/^\[|\]$/g, "");
  10348. }
  10349. return input.replace(/\\/g, "");
  10350. }
  10351. function makeFormatFunction(format) {
  10352. var array = format.match(formattingTokens), i, length;
  10353. for (i = 0, length = array.length; i < length; i++) {
  10354. if (formatTokenFunctions[array[i]]) {
  10355. array[i] = formatTokenFunctions[array[i]];
  10356. } else {
  10357. array[i] = removeFormattingTokens(array[i]);
  10358. }
  10359. }
  10360. return function (mom) {
  10361. var output = "";
  10362. for (i = 0; i < length; i++) {
  10363. output += typeof array[i].call === 'function' ? array[i].call(mom, format) : array[i];
  10364. }
  10365. return output;
  10366. };
  10367. }
  10368. // format date using native date object
  10369. function formatMoment(m, format) {
  10370. var i = 5;
  10371. function replaceLongDateFormatTokens(input) {
  10372. return m.lang().longDateFormat(input) || input;
  10373. }
  10374. while (i-- && localFormattingTokens.test(format)) {
  10375. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  10376. }
  10377. if (!formatFunctions[format]) {
  10378. formatFunctions[format] = makeFormatFunction(format);
  10379. }
  10380. return formatFunctions[format](m);
  10381. }
  10382. /************************************
  10383. Parsing
  10384. ************************************/
  10385. // get the regex to find the next token
  10386. function getParseRegexForToken(token) {
  10387. switch (token) {
  10388. case 'DDDD':
  10389. return parseTokenThreeDigits;
  10390. case 'YYYY':
  10391. return parseTokenFourDigits;
  10392. case 'YYYYY':
  10393. return parseTokenSixDigits;
  10394. case 'S':
  10395. case 'SS':
  10396. case 'SSS':
  10397. case 'DDD':
  10398. return parseTokenOneToThreeDigits;
  10399. case 'MMM':
  10400. case 'MMMM':
  10401. case 'dd':
  10402. case 'ddd':
  10403. case 'dddd':
  10404. case 'a':
  10405. case 'A':
  10406. return parseTokenWord;
  10407. case 'X':
  10408. return parseTokenTimestampMs;
  10409. case 'Z':
  10410. case 'ZZ':
  10411. return parseTokenTimezone;
  10412. case 'T':
  10413. return parseTokenT;
  10414. case 'MM':
  10415. case 'DD':
  10416. case 'YY':
  10417. case 'HH':
  10418. case 'hh':
  10419. case 'mm':
  10420. case 'ss':
  10421. case 'M':
  10422. case 'D':
  10423. case 'd':
  10424. case 'H':
  10425. case 'h':
  10426. case 'm':
  10427. case 's':
  10428. return parseTokenOneOrTwoDigits;
  10429. default :
  10430. return new RegExp(token.replace('\\', ''));
  10431. }
  10432. }
  10433. // function to convert string input to date
  10434. function addTimeToArrayFromToken(token, input, config) {
  10435. var a, b,
  10436. datePartArray = config._a;
  10437. switch (token) {
  10438. // MONTH
  10439. case 'M' : // fall through to MM
  10440. case 'MM' :
  10441. datePartArray[1] = (input == null) ? 0 : ~~input - 1;
  10442. break;
  10443. case 'MMM' : // fall through to MMMM
  10444. case 'MMMM' :
  10445. a = getLangDefinition(config._l).monthsParse(input);
  10446. // if we didn't find a month name, mark the date as invalid.
  10447. if (a != null) {
  10448. datePartArray[1] = a;
  10449. } else {
  10450. config._isValid = false;
  10451. }
  10452. break;
  10453. // DAY OF MONTH
  10454. case 'D' : // fall through to DDDD
  10455. case 'DD' : // fall through to DDDD
  10456. case 'DDD' : // fall through to DDDD
  10457. case 'DDDD' :
  10458. if (input != null) {
  10459. datePartArray[2] = ~~input;
  10460. }
  10461. break;
  10462. // YEAR
  10463. case 'YY' :
  10464. datePartArray[0] = ~~input + (~~input > 68 ? 1900 : 2000);
  10465. break;
  10466. case 'YYYY' :
  10467. case 'YYYYY' :
  10468. datePartArray[0] = ~~input;
  10469. break;
  10470. // AM / PM
  10471. case 'a' : // fall through to A
  10472. case 'A' :
  10473. config._isPm = ((input + '').toLowerCase() === 'pm');
  10474. break;
  10475. // 24 HOUR
  10476. case 'H' : // fall through to hh
  10477. case 'HH' : // fall through to hh
  10478. case 'h' : // fall through to hh
  10479. case 'hh' :
  10480. datePartArray[3] = ~~input;
  10481. break;
  10482. // MINUTE
  10483. case 'm' : // fall through to mm
  10484. case 'mm' :
  10485. datePartArray[4] = ~~input;
  10486. break;
  10487. // SECOND
  10488. case 's' : // fall through to ss
  10489. case 'ss' :
  10490. datePartArray[5] = ~~input;
  10491. break;
  10492. // MILLISECOND
  10493. case 'S' :
  10494. case 'SS' :
  10495. case 'SSS' :
  10496. datePartArray[6] = ~~ (('0.' + input) * 1000);
  10497. break;
  10498. // UNIX TIMESTAMP WITH MS
  10499. case 'X':
  10500. config._d = new Date(parseFloat(input) * 1000);
  10501. break;
  10502. // TIMEZONE
  10503. case 'Z' : // fall through to ZZ
  10504. case 'ZZ' :
  10505. config._useUTC = true;
  10506. a = (input + '').match(parseTimezoneChunker);
  10507. if (a && a[1]) {
  10508. config._tzh = ~~a[1];
  10509. }
  10510. if (a && a[2]) {
  10511. config._tzm = ~~a[2];
  10512. }
  10513. // reverse offsets
  10514. if (a && a[0] === '+') {
  10515. config._tzh = -config._tzh;
  10516. config._tzm = -config._tzm;
  10517. }
  10518. break;
  10519. }
  10520. // if the input is null, the date is not valid
  10521. if (input == null) {
  10522. config._isValid = false;
  10523. }
  10524. }
  10525. // convert an array to a date.
  10526. // the array should mirror the parameters below
  10527. // note: all values past the year are optional and will default to the lowest possible value.
  10528. // [year, month, day , hour, minute, second, millisecond]
  10529. function dateFromArray(config) {
  10530. var i, date, input = [];
  10531. if (config._d) {
  10532. return;
  10533. }
  10534. for (i = 0; i < 7; i++) {
  10535. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  10536. }
  10537. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  10538. input[3] += config._tzh || 0;
  10539. input[4] += config._tzm || 0;
  10540. date = new Date(0);
  10541. if (config._useUTC) {
  10542. date.setUTCFullYear(input[0], input[1], input[2]);
  10543. date.setUTCHours(input[3], input[4], input[5], input[6]);
  10544. } else {
  10545. date.setFullYear(input[0], input[1], input[2]);
  10546. date.setHours(input[3], input[4], input[5], input[6]);
  10547. }
  10548. config._d = date;
  10549. }
  10550. // date from string and format string
  10551. function makeDateFromStringAndFormat(config) {
  10552. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  10553. var tokens = config._f.match(formattingTokens),
  10554. string = config._i,
  10555. i, parsedInput;
  10556. config._a = [];
  10557. for (i = 0; i < tokens.length; i++) {
  10558. parsedInput = (getParseRegexForToken(tokens[i]).exec(string) || [])[0];
  10559. if (parsedInput) {
  10560. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  10561. }
  10562. // don't parse if its not a known token
  10563. if (formatTokenFunctions[tokens[i]]) {
  10564. addTimeToArrayFromToken(tokens[i], parsedInput, config);
  10565. }
  10566. }
  10567. // handle am pm
  10568. if (config._isPm && config._a[3] < 12) {
  10569. config._a[3] += 12;
  10570. }
  10571. // if is 12 am, change hours to 0
  10572. if (config._isPm === false && config._a[3] === 12) {
  10573. config._a[3] = 0;
  10574. }
  10575. // return
  10576. dateFromArray(config);
  10577. }
  10578. // date from string and array of format strings
  10579. function makeDateFromStringAndArray(config) {
  10580. var tempConfig,
  10581. tempMoment,
  10582. bestMoment,
  10583. scoreToBeat = 99,
  10584. i,
  10585. currentDate,
  10586. currentScore;
  10587. while (config._f.length) {
  10588. tempConfig = extend({}, config);
  10589. tempConfig._f = config._f.pop();
  10590. makeDateFromStringAndFormat(tempConfig);
  10591. tempMoment = new Moment(tempConfig);
  10592. if (tempMoment.isValid()) {
  10593. bestMoment = tempMoment;
  10594. break;
  10595. }
  10596. currentScore = compareArrays(tempConfig._a, tempMoment.toArray());
  10597. if (currentScore < scoreToBeat) {
  10598. scoreToBeat = currentScore;
  10599. bestMoment = tempMoment;
  10600. }
  10601. }
  10602. extend(config, bestMoment);
  10603. }
  10604. // date from iso format
  10605. function makeDateFromString(config) {
  10606. var i,
  10607. string = config._i;
  10608. if (isoRegex.exec(string)) {
  10609. config._f = 'YYYY-MM-DDT';
  10610. for (i = 0; i < 4; i++) {
  10611. if (isoTimes[i][1].exec(string)) {
  10612. config._f += isoTimes[i][0];
  10613. break;
  10614. }
  10615. }
  10616. if (parseTokenTimezone.exec(string)) {
  10617. config._f += " Z";
  10618. }
  10619. makeDateFromStringAndFormat(config);
  10620. } else {
  10621. config._d = new Date(string);
  10622. }
  10623. }
  10624. function makeDateFromInput(config) {
  10625. var input = config._i,
  10626. matched = aspNetJsonRegex.exec(input);
  10627. if (input === undefined) {
  10628. config._d = new Date();
  10629. } else if (matched) {
  10630. config._d = new Date(+matched[1]);
  10631. } else if (typeof input === 'string') {
  10632. makeDateFromString(config);
  10633. } else if (isArray(input)) {
  10634. config._a = input.slice(0);
  10635. dateFromArray(config);
  10636. } else {
  10637. config._d = input instanceof Date ? new Date(+input) : new Date(input);
  10638. }
  10639. }
  10640. /************************************
  10641. Relative Time
  10642. ************************************/
  10643. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  10644. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  10645. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  10646. }
  10647. function relativeTime(milliseconds, withoutSuffix, lang) {
  10648. var seconds = round(Math.abs(milliseconds) / 1000),
  10649. minutes = round(seconds / 60),
  10650. hours = round(minutes / 60),
  10651. days = round(hours / 24),
  10652. years = round(days / 365),
  10653. args = seconds < 45 && ['s', seconds] ||
  10654. minutes === 1 && ['m'] ||
  10655. minutes < 45 && ['mm', minutes] ||
  10656. hours === 1 && ['h'] ||
  10657. hours < 22 && ['hh', hours] ||
  10658. days === 1 && ['d'] ||
  10659. days <= 25 && ['dd', days] ||
  10660. days <= 45 && ['M'] ||
  10661. days < 345 && ['MM', round(days / 30)] ||
  10662. years === 1 && ['y'] || ['yy', years];
  10663. args[2] = withoutSuffix;
  10664. args[3] = milliseconds > 0;
  10665. args[4] = lang;
  10666. return substituteTimeAgo.apply({}, args);
  10667. }
  10668. /************************************
  10669. Week of Year
  10670. ************************************/
  10671. // firstDayOfWeek 0 = sun, 6 = sat
  10672. // the day of the week that starts the week
  10673. // (usually sunday or monday)
  10674. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  10675. // the first week is the week that contains the first
  10676. // of this day of the week
  10677. // (eg. ISO weeks use thursday (4))
  10678. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  10679. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  10680. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day();
  10681. if (daysToDayOfWeek > end) {
  10682. daysToDayOfWeek -= 7;
  10683. }
  10684. if (daysToDayOfWeek < end - 7) {
  10685. daysToDayOfWeek += 7;
  10686. }
  10687. return Math.ceil(moment(mom).add('d', daysToDayOfWeek).dayOfYear() / 7);
  10688. }
  10689. /************************************
  10690. Top Level Functions
  10691. ************************************/
  10692. function makeMoment(config) {
  10693. var input = config._i,
  10694. format = config._f;
  10695. if (input === null || input === '') {
  10696. return null;
  10697. }
  10698. if (typeof input === 'string') {
  10699. config._i = input = getLangDefinition().preparse(input);
  10700. }
  10701. if (moment.isMoment(input)) {
  10702. config = extend({}, input);
  10703. config._d = new Date(+input._d);
  10704. } else if (format) {
  10705. if (isArray(format)) {
  10706. makeDateFromStringAndArray(config);
  10707. } else {
  10708. makeDateFromStringAndFormat(config);
  10709. }
  10710. } else {
  10711. makeDateFromInput(config);
  10712. }
  10713. return new Moment(config);
  10714. }
  10715. moment = function (input, format, lang) {
  10716. return makeMoment({
  10717. _i : input,
  10718. _f : format,
  10719. _l : lang,
  10720. _isUTC : false
  10721. });
  10722. };
  10723. // creating with utc
  10724. moment.utc = function (input, format, lang) {
  10725. return makeMoment({
  10726. _useUTC : true,
  10727. _isUTC : true,
  10728. _l : lang,
  10729. _i : input,
  10730. _f : format
  10731. });
  10732. };
  10733. // creating with unix timestamp (in seconds)
  10734. moment.unix = function (input) {
  10735. return moment(input * 1000);
  10736. };
  10737. // duration
  10738. moment.duration = function (input, key) {
  10739. var isDuration = moment.isDuration(input),
  10740. isNumber = (typeof input === 'number'),
  10741. duration = (isDuration ? input._data : (isNumber ? {} : input)),
  10742. ret;
  10743. if (isNumber) {
  10744. if (key) {
  10745. duration[key] = input;
  10746. } else {
  10747. duration.milliseconds = input;
  10748. }
  10749. }
  10750. ret = new Duration(duration);
  10751. if (isDuration && input.hasOwnProperty('_lang')) {
  10752. ret._lang = input._lang;
  10753. }
  10754. return ret;
  10755. };
  10756. // version number
  10757. moment.version = VERSION;
  10758. // default format
  10759. moment.defaultFormat = isoFormat;
  10760. // This function will load languages and then set the global language. If
  10761. // no arguments are passed in, it will simply return the current global
  10762. // language key.
  10763. moment.lang = function (key, values) {
  10764. var i;
  10765. if (!key) {
  10766. return moment.fn._lang._abbr;
  10767. }
  10768. if (values) {
  10769. loadLang(key, values);
  10770. } else if (!languages[key]) {
  10771. getLangDefinition(key);
  10772. }
  10773. moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  10774. };
  10775. // returns language data
  10776. moment.langData = function (key) {
  10777. if (key && key._lang && key._lang._abbr) {
  10778. key = key._lang._abbr;
  10779. }
  10780. return getLangDefinition(key);
  10781. };
  10782. // compare moment object
  10783. moment.isMoment = function (obj) {
  10784. return obj instanceof Moment;
  10785. };
  10786. // for typechecking Duration objects
  10787. moment.isDuration = function (obj) {
  10788. return obj instanceof Duration;
  10789. };
  10790. /************************************
  10791. Moment Prototype
  10792. ************************************/
  10793. moment.fn = Moment.prototype = {
  10794. clone : function () {
  10795. return moment(this);
  10796. },
  10797. valueOf : function () {
  10798. return +this._d;
  10799. },
  10800. unix : function () {
  10801. return Math.floor(+this._d / 1000);
  10802. },
  10803. toString : function () {
  10804. return this.format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  10805. },
  10806. toDate : function () {
  10807. return this._d;
  10808. },
  10809. toJSON : function () {
  10810. return moment.utc(this).format('YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  10811. },
  10812. toArray : function () {
  10813. var m = this;
  10814. return [
  10815. m.year(),
  10816. m.month(),
  10817. m.date(),
  10818. m.hours(),
  10819. m.minutes(),
  10820. m.seconds(),
  10821. m.milliseconds()
  10822. ];
  10823. },
  10824. isValid : function () {
  10825. if (this._isValid == null) {
  10826. if (this._a) {
  10827. this._isValid = !compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray());
  10828. } else {
  10829. this._isValid = !isNaN(this._d.getTime());
  10830. }
  10831. }
  10832. return !!this._isValid;
  10833. },
  10834. utc : function () {
  10835. this._isUTC = true;
  10836. return this;
  10837. },
  10838. local : function () {
  10839. this._isUTC = false;
  10840. return this;
  10841. },
  10842. format : function (inputString) {
  10843. var output = formatMoment(this, inputString || moment.defaultFormat);
  10844. return this.lang().postformat(output);
  10845. },
  10846. add : function (input, val) {
  10847. var dur;
  10848. // switch args to support add('s', 1) and add(1, 's')
  10849. if (typeof input === 'string') {
  10850. dur = moment.duration(+val, input);
  10851. } else {
  10852. dur = moment.duration(input, val);
  10853. }
  10854. addOrSubtractDurationFromMoment(this, dur, 1);
  10855. return this;
  10856. },
  10857. subtract : function (input, val) {
  10858. var dur;
  10859. // switch args to support subtract('s', 1) and subtract(1, 's')
  10860. if (typeof input === 'string') {
  10861. dur = moment.duration(+val, input);
  10862. } else {
  10863. dur = moment.duration(input, val);
  10864. }
  10865. addOrSubtractDurationFromMoment(this, dur, -1);
  10866. return this;
  10867. },
  10868. diff : function (input, units, asFloat) {
  10869. var that = this._isUTC ? moment(input).utc() : moment(input).local(),
  10870. zoneDiff = (this.zone() - that.zone()) * 6e4,
  10871. diff, output;
  10872. if (units) {
  10873. // standardize on singular form
  10874. units = units.replace(/s$/, '');
  10875. }
  10876. if (units === 'year' || units === 'month') {
  10877. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  10878. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  10879. output += ((this - moment(this).startOf('month')) - (that - moment(that).startOf('month'))) / diff;
  10880. if (units === 'year') {
  10881. output = output / 12;
  10882. }
  10883. } else {
  10884. diff = (this - that) - zoneDiff;
  10885. output = units === 'second' ? diff / 1e3 : // 1000
  10886. units === 'minute' ? diff / 6e4 : // 1000 * 60
  10887. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  10888. units === 'day' ? diff / 864e5 : // 1000 * 60 * 60 * 24
  10889. units === 'week' ? diff / 6048e5 : // 1000 * 60 * 60 * 24 * 7
  10890. diff;
  10891. }
  10892. return asFloat ? output : absRound(output);
  10893. },
  10894. from : function (time, withoutSuffix) {
  10895. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  10896. },
  10897. fromNow : function (withoutSuffix) {
  10898. return this.from(moment(), withoutSuffix);
  10899. },
  10900. calendar : function () {
  10901. var diff = this.diff(moment().startOf('day'), 'days', true),
  10902. format = diff < -6 ? 'sameElse' :
  10903. diff < -1 ? 'lastWeek' :
  10904. diff < 0 ? 'lastDay' :
  10905. diff < 1 ? 'sameDay' :
  10906. diff < 2 ? 'nextDay' :
  10907. diff < 7 ? 'nextWeek' : 'sameElse';
  10908. return this.format(this.lang().calendar(format, this));
  10909. },
  10910. isLeapYear : function () {
  10911. var year = this.year();
  10912. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  10913. },
  10914. isDST : function () {
  10915. return (this.zone() < moment([this.year()]).zone() ||
  10916. this.zone() < moment([this.year(), 5]).zone());
  10917. },
  10918. day : function (input) {
  10919. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  10920. return input == null ? day :
  10921. this.add({ d : input - day });
  10922. },
  10923. startOf: function (units) {
  10924. units = units.replace(/s$/, '');
  10925. // the following switch intentionally omits break keywords
  10926. // to utilize falling through the cases.
  10927. switch (units) {
  10928. case 'year':
  10929. this.month(0);
  10930. /* falls through */
  10931. case 'month':
  10932. this.date(1);
  10933. /* falls through */
  10934. case 'week':
  10935. case 'day':
  10936. this.hours(0);
  10937. /* falls through */
  10938. case 'hour':
  10939. this.minutes(0);
  10940. /* falls through */
  10941. case 'minute':
  10942. this.seconds(0);
  10943. /* falls through */
  10944. case 'second':
  10945. this.milliseconds(0);
  10946. /* falls through */
  10947. }
  10948. // weeks are a special case
  10949. if (units === 'week') {
  10950. this.day(0);
  10951. }
  10952. return this;
  10953. },
  10954. endOf: function (units) {
  10955. return this.startOf(units).add(units.replace(/s?$/, 's'), 1).subtract('ms', 1);
  10956. },
  10957. isAfter: function (input, units) {
  10958. units = typeof units !== 'undefined' ? units : 'millisecond';
  10959. return +this.clone().startOf(units) > +moment(input).startOf(units);
  10960. },
  10961. isBefore: function (input, units) {
  10962. units = typeof units !== 'undefined' ? units : 'millisecond';
  10963. return +this.clone().startOf(units) < +moment(input).startOf(units);
  10964. },
  10965. isSame: function (input, units) {
  10966. units = typeof units !== 'undefined' ? units : 'millisecond';
  10967. return +this.clone().startOf(units) === +moment(input).startOf(units);
  10968. },
  10969. zone : function () {
  10970. return this._isUTC ? 0 : this._d.getTimezoneOffset();
  10971. },
  10972. daysInMonth : function () {
  10973. return moment.utc([this.year(), this.month() + 1, 0]).date();
  10974. },
  10975. dayOfYear : function (input) {
  10976. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  10977. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  10978. },
  10979. isoWeek : function (input) {
  10980. var week = weekOfYear(this, 1, 4);
  10981. return input == null ? week : this.add("d", (input - week) * 7);
  10982. },
  10983. week : function (input) {
  10984. var week = this.lang().week(this);
  10985. return input == null ? week : this.add("d", (input - week) * 7);
  10986. },
  10987. // If passed a language key, it will set the language for this
  10988. // instance. Otherwise, it will return the language configuration
  10989. // variables for this instance.
  10990. lang : function (key) {
  10991. if (key === undefined) {
  10992. return this._lang;
  10993. } else {
  10994. this._lang = getLangDefinition(key);
  10995. return this;
  10996. }
  10997. }
  10998. };
  10999. // helper for adding shortcuts
  11000. function makeGetterAndSetter(name, key) {
  11001. moment.fn[name] = moment.fn[name + 's'] = function (input) {
  11002. var utc = this._isUTC ? 'UTC' : '';
  11003. if (input != null) {
  11004. this._d['set' + utc + key](input);
  11005. return this;
  11006. } else {
  11007. return this._d['get' + utc + key]();
  11008. }
  11009. };
  11010. }
  11011. // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds)
  11012. for (i = 0; i < proxyGettersAndSetters.length; i ++) {
  11013. makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]);
  11014. }
  11015. // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear')
  11016. makeGetterAndSetter('year', 'FullYear');
  11017. // add plural methods
  11018. moment.fn.days = moment.fn.day;
  11019. moment.fn.weeks = moment.fn.week;
  11020. moment.fn.isoWeeks = moment.fn.isoWeek;
  11021. /************************************
  11022. Duration Prototype
  11023. ************************************/
  11024. moment.duration.fn = Duration.prototype = {
  11025. weeks : function () {
  11026. return absRound(this.days() / 7);
  11027. },
  11028. valueOf : function () {
  11029. return this._milliseconds +
  11030. this._days * 864e5 +
  11031. this._months * 2592e6;
  11032. },
  11033. humanize : function (withSuffix) {
  11034. var difference = +this,
  11035. output = relativeTime(difference, !withSuffix, this.lang());
  11036. if (withSuffix) {
  11037. output = this.lang().pastFuture(difference, output);
  11038. }
  11039. return this.lang().postformat(output);
  11040. },
  11041. lang : moment.fn.lang
  11042. };
  11043. function makeDurationGetter(name) {
  11044. moment.duration.fn[name] = function () {
  11045. return this._data[name];
  11046. };
  11047. }
  11048. function makeDurationAsGetter(name, factor) {
  11049. moment.duration.fn['as' + name] = function () {
  11050. return +this / factor;
  11051. };
  11052. }
  11053. for (i in unitMillisecondFactors) {
  11054. if (unitMillisecondFactors.hasOwnProperty(i)) {
  11055. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  11056. makeDurationGetter(i.toLowerCase());
  11057. }
  11058. }
  11059. makeDurationAsGetter('Weeks', 6048e5);
  11060. /************************************
  11061. Default Lang
  11062. ************************************/
  11063. // Set default language, other languages will inherit from English.
  11064. moment.lang('en', {
  11065. ordinal : function (number) {
  11066. var b = number % 10,
  11067. output = (~~ (number % 100 / 10) === 1) ? 'th' :
  11068. (b === 1) ? 'st' :
  11069. (b === 2) ? 'nd' :
  11070. (b === 3) ? 'rd' : 'th';
  11071. return number + output;
  11072. }
  11073. });
  11074. /************************************
  11075. Exposing Moment
  11076. ************************************/
  11077. // CommonJS module is defined
  11078. if (hasModule) {
  11079. module.exports = moment;
  11080. }
  11081. /*global ender:false */
  11082. if (typeof ender === 'undefined') {
  11083. // here, `this` means `window` in the browser, or `global` on the server
  11084. // add `moment` as a global object via a string identifier,
  11085. // for Closure Compiler "advanced" mode
  11086. this['moment'] = moment;
  11087. }
  11088. /*global define:false */
  11089. if (typeof define === "function" && define.amd) {
  11090. define("moment", [], function () {
  11091. return moment;
  11092. });
  11093. }
  11094. }).call(this);
  11095. })()
  11096. },{}]},{},[1])(1)
  11097. });
  11098. ;