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.

12854 lines
385 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version 0.2.0-SNAPSHOT
  8. * @date 2013-06-25
  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. * Convert 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.convert = function convert(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.valueOf());
  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. match = ASPDateRegex.exec(object);
  166. if (match) {
  167. // object is an ASP date
  168. return new Date(Number(match[1])); // parse number
  169. }
  170. else {
  171. return moment(object).toDate(); // parse string
  172. }
  173. }
  174. else {
  175. throw new Error(
  176. 'Cannot convert object of type ' + util.getType(object) +
  177. ' to type Date');
  178. }
  179. case 'Moment':
  180. if (util.isNumber(object)) {
  181. return moment(object);
  182. }
  183. if (object instanceof Date) {
  184. return moment(object.valueOf());
  185. }
  186. else if (moment.isMoment(object)) {
  187. return moment.clone();
  188. }
  189. if (util.isString(object)) {
  190. match = ASPDateRegex.exec(object);
  191. if (match) {
  192. // object is an ASP date
  193. return moment(Number(match[1])); // parse number
  194. }
  195. else {
  196. return moment(object); // parse string
  197. }
  198. }
  199. else {
  200. throw new Error(
  201. 'Cannot convert object of type ' + util.getType(object) +
  202. ' to type Date');
  203. }
  204. case 'ISODate':
  205. if (util.isNumber(object)) {
  206. return new Date(object);
  207. }
  208. else if (object instanceof Date) {
  209. return object.toISOString();
  210. }
  211. else if (moment.isMoment(object)) {
  212. return object.toDate().toISOString();
  213. }
  214. else if (util.isString(object)) {
  215. match = ASPDateRegex.exec(object);
  216. if (match) {
  217. // object is an ASP date
  218. return new Date(Number(match[1])).toISOString(); // parse number
  219. }
  220. else {
  221. return new Date(object).toISOString(); // parse string
  222. }
  223. }
  224. else {
  225. throw new Error(
  226. 'Cannot convert object of type ' + util.getType(object) +
  227. ' to type ISODate');
  228. }
  229. case 'ASPDate':
  230. if (util.isNumber(object)) {
  231. return '/Date(' + object + ')/';
  232. }
  233. else if (object instanceof Date) {
  234. return '/Date(' + object.valueOf() + ')/';
  235. }
  236. else if (util.isString(object)) {
  237. match = ASPDateRegex.exec(object);
  238. var value;
  239. if (match) {
  240. // object is an ASP date
  241. value = new Date(Number(match[1])).valueOf(); // parse number
  242. }
  243. else {
  244. value = new Date(object).valueOf(); // parse string
  245. }
  246. return '/Date(' + value + ')/';
  247. }
  248. else {
  249. throw new Error(
  250. 'Cannot convert object of type ' + util.getType(object) +
  251. ' to type ASPDate');
  252. }
  253. default:
  254. throw new Error('Cannot convert object of type ' + util.getType(object) +
  255. ' to type "' + type + '"');
  256. }
  257. };
  258. // parse ASP.Net Date pattern,
  259. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  260. // code from http://momentjs.com/
  261. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  262. /**
  263. * Get the type of an object, for example util.getType([]) returns 'Array'
  264. * @param {*} object
  265. * @return {String} type
  266. */
  267. util.getType = function getType(object) {
  268. var type = typeof object;
  269. if (type == 'object') {
  270. if (object == null) {
  271. return 'null';
  272. }
  273. if (object instanceof Boolean) {
  274. return 'Boolean';
  275. }
  276. if (object instanceof Number) {
  277. return 'Number';
  278. }
  279. if (object instanceof String) {
  280. return 'String';
  281. }
  282. if (object instanceof Array) {
  283. return 'Array';
  284. }
  285. if (object instanceof Date) {
  286. return 'Date';
  287. }
  288. return 'Object';
  289. }
  290. else if (type == 'number') {
  291. return 'Number';
  292. }
  293. else if (type == 'boolean') {
  294. return 'Boolean';
  295. }
  296. else if (type == 'string') {
  297. return 'String';
  298. }
  299. return type;
  300. };
  301. /**
  302. * Retrieve the absolute left value of a DOM element
  303. * @param {Element} elem A dom element, for example a div
  304. * @return {number} left The absolute left position of this element
  305. * in the browser page.
  306. */
  307. util.getAbsoluteLeft = function getAbsoluteLeft (elem) {
  308. var doc = document.documentElement;
  309. var body = document.body;
  310. var left = elem.offsetLeft;
  311. var e = elem.offsetParent;
  312. while (e != null && e != body && e != doc) {
  313. left += e.offsetLeft;
  314. left -= e.scrollLeft;
  315. e = e.offsetParent;
  316. }
  317. return left;
  318. };
  319. /**
  320. * Retrieve the absolute top value of a DOM element
  321. * @param {Element} elem A dom element, for example a div
  322. * @return {number} top The absolute top position of this element
  323. * in the browser page.
  324. */
  325. util.getAbsoluteTop = function getAbsoluteTop (elem) {
  326. var doc = document.documentElement;
  327. var body = document.body;
  328. var top = elem.offsetTop;
  329. var e = elem.offsetParent;
  330. while (e != null && e != body && e != doc) {
  331. top += e.offsetTop;
  332. top -= e.scrollTop;
  333. e = e.offsetParent;
  334. }
  335. return top;
  336. };
  337. /**
  338. * Get the absolute, vertical mouse position from an event.
  339. * @param {Event} event
  340. * @return {Number} pageY
  341. */
  342. util.getPageY = function getPageY (event) {
  343. if ('pageY' in event) {
  344. return event.pageY;
  345. }
  346. else {
  347. var clientY;
  348. if (('targetTouches' in event) && event.targetTouches.length) {
  349. clientY = event.targetTouches[0].clientY;
  350. }
  351. else {
  352. clientY = event.clientY;
  353. }
  354. var doc = document.documentElement;
  355. var body = document.body;
  356. return clientY +
  357. ( doc && doc.scrollTop || body && body.scrollTop || 0 ) -
  358. ( doc && doc.clientTop || body && body.clientTop || 0 );
  359. }
  360. };
  361. /**
  362. * Get the absolute, horizontal mouse position from an event.
  363. * @param {Event} event
  364. * @return {Number} pageX
  365. */
  366. util.getPageX = function getPageX (event) {
  367. if ('pageY' in event) {
  368. return event.pageX;
  369. }
  370. else {
  371. var clientX;
  372. if (('targetTouches' in event) && event.targetTouches.length) {
  373. clientX = event.targetTouches[0].clientX;
  374. }
  375. else {
  376. clientX = event.clientX;
  377. }
  378. var doc = document.documentElement;
  379. var body = document.body;
  380. return clientX +
  381. ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
  382. ( doc && doc.clientLeft || body && body.clientLeft || 0 );
  383. }
  384. };
  385. /**
  386. * add a className to the given elements style
  387. * @param {Element} elem
  388. * @param {String} className
  389. */
  390. util.addClassName = function addClassName(elem, className) {
  391. var classes = elem.className.split(' ');
  392. if (classes.indexOf(className) == -1) {
  393. classes.push(className); // add the class to the array
  394. elem.className = classes.join(' ');
  395. }
  396. };
  397. /**
  398. * add a className to the given elements style
  399. * @param {Element} elem
  400. * @param {String} className
  401. */
  402. util.removeClassName = function removeClassname(elem, className) {
  403. var classes = elem.className.split(' ');
  404. var index = classes.indexOf(className);
  405. if (index != -1) {
  406. classes.splice(index, 1); // remove the class from the array
  407. elem.className = classes.join(' ');
  408. }
  409. };
  410. /**
  411. * For each method for both arrays and objects.
  412. * In case of an array, the built-in Array.forEach() is applied.
  413. * In case of an Object, the method loops over all properties of the object.
  414. * @param {Object | Array} object An Object or Array
  415. * @param {function} callback Callback method, called for each item in
  416. * the object or array with three parameters:
  417. * callback(value, index, object)
  418. */
  419. util.forEach = function forEach (object, callback) {
  420. var i,
  421. len;
  422. if (object instanceof Array) {
  423. // array
  424. for (i = 0, len = object.length; i < len; i++) {
  425. callback(object[i], i, object);
  426. }
  427. }
  428. else {
  429. // object
  430. for (i in object) {
  431. if (object.hasOwnProperty(i)) {
  432. callback(object[i], i, object);
  433. }
  434. }
  435. }
  436. };
  437. /**
  438. * Update a property in an object
  439. * @param {Object} object
  440. * @param {String} key
  441. * @param {*} value
  442. * @return {Boolean} changed
  443. */
  444. util.updateProperty = function updateProp (object, key, value) {
  445. if (object[key] !== value) {
  446. object[key] = value;
  447. return true;
  448. }
  449. else {
  450. return false;
  451. }
  452. };
  453. /**
  454. * Add and event listener. Works for all browsers
  455. * @param {Element} element An html element
  456. * @param {string} action The action, for example "click",
  457. * without the prefix "on"
  458. * @param {function} listener The callback function to be executed
  459. * @param {boolean} [useCapture]
  460. */
  461. util.addEventListener = function addEventListener(element, action, listener, useCapture) {
  462. if (element.addEventListener) {
  463. if (useCapture === undefined)
  464. useCapture = false;
  465. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  466. action = "DOMMouseScroll"; // For Firefox
  467. }
  468. element.addEventListener(action, listener, useCapture);
  469. } else {
  470. element.attachEvent("on" + action, listener); // IE browsers
  471. }
  472. };
  473. /**
  474. * Remove an event listener from an element
  475. * @param {Element} element An html dom element
  476. * @param {string} action The name of the event, for example "mousedown"
  477. * @param {function} listener The listener function
  478. * @param {boolean} [useCapture]
  479. */
  480. util.removeEventListener = function removeEventListener(element, action, listener, useCapture) {
  481. if (element.removeEventListener) {
  482. // non-IE browsers
  483. if (useCapture === undefined)
  484. useCapture = false;
  485. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  486. action = "DOMMouseScroll"; // For Firefox
  487. }
  488. element.removeEventListener(action, listener, useCapture);
  489. } else {
  490. // IE browsers
  491. element.detachEvent("on" + action, listener);
  492. }
  493. };
  494. /**
  495. * Get HTML element which is the target of the event
  496. * @param {Event} event
  497. * @return {Element} target element
  498. */
  499. util.getTarget = function getTarget(event) {
  500. // code from http://www.quirksmode.org/js/events_properties.html
  501. if (!event) {
  502. event = window.event;
  503. }
  504. var target;
  505. if (event.target) {
  506. target = event.target;
  507. }
  508. else if (event.srcElement) {
  509. target = event.srcElement;
  510. }
  511. if (target.nodeType != undefined && target.nodeType == 3) {
  512. // defeat Safari bug
  513. target = target.parentNode;
  514. }
  515. return target;
  516. };
  517. /**
  518. * Stop event propagation
  519. */
  520. util.stopPropagation = function stopPropagation(event) {
  521. if (!event)
  522. event = window.event;
  523. if (event.stopPropagation) {
  524. event.stopPropagation(); // non-IE browsers
  525. }
  526. else {
  527. event.cancelBubble = true; // IE browsers
  528. }
  529. };
  530. /**
  531. * Cancels the event if it is cancelable, without stopping further propagation of the event.
  532. */
  533. util.preventDefault = function preventDefault (event) {
  534. if (!event)
  535. event = window.event;
  536. if (event.preventDefault) {
  537. event.preventDefault(); // non-IE browsers
  538. }
  539. else {
  540. event.returnValue = false; // IE browsers
  541. }
  542. };
  543. util.option = {};
  544. /**
  545. * Convert a value into a boolean
  546. * @param {Boolean | function | undefined} value
  547. * @param {Boolean} [defaultValue]
  548. * @returns {Boolean} bool
  549. */
  550. util.option.asBoolean = function (value, defaultValue) {
  551. if (typeof value == 'function') {
  552. value = value();
  553. }
  554. if (value != null) {
  555. return (value != false);
  556. }
  557. return defaultValue || null;
  558. };
  559. /**
  560. * Convert a value into a number
  561. * @param {Boolean | function | undefined} value
  562. * @param {Number} [defaultValue]
  563. * @returns {Number} number
  564. */
  565. util.option.asNumber = function (value, defaultValue) {
  566. if (typeof value == 'function') {
  567. value = value();
  568. }
  569. if (value != null) {
  570. return Number(value) || defaultValue || null;
  571. }
  572. return defaultValue || null;
  573. };
  574. /**
  575. * Convert a value into a string
  576. * @param {String | function | undefined} value
  577. * @param {String} [defaultValue]
  578. * @returns {String} str
  579. */
  580. util.option.asString = function (value, defaultValue) {
  581. if (typeof value == 'function') {
  582. value = value();
  583. }
  584. if (value != null) {
  585. return String(value);
  586. }
  587. return defaultValue || null;
  588. };
  589. /**
  590. * Convert a size or location into a string with pixels or a percentage
  591. * @param {String | Number | function | undefined} value
  592. * @param {String} [defaultValue]
  593. * @returns {String} size
  594. */
  595. util.option.asSize = function (value, defaultValue) {
  596. if (typeof value == 'function') {
  597. value = value();
  598. }
  599. if (util.isString(value)) {
  600. return value;
  601. }
  602. else if (util.isNumber(value)) {
  603. return value + 'px';
  604. }
  605. else {
  606. return defaultValue || null;
  607. }
  608. };
  609. /**
  610. * Convert a value into a DOM element
  611. * @param {HTMLElement | function | undefined} value
  612. * @param {HTMLElement} [defaultValue]
  613. * @returns {HTMLElement | null} dom
  614. */
  615. util.option.asElement = function (value, defaultValue) {
  616. if (typeof value == 'function') {
  617. value = value();
  618. }
  619. return value || defaultValue || null;
  620. };
  621. /**
  622. * load css from text
  623. * @param {String} css Text containing css
  624. */
  625. util.loadCss = function (css) {
  626. if (typeof document === 'undefined') {
  627. return;
  628. }
  629. // get the script location, and built the css file name from the js file name
  630. // http://stackoverflow.com/a/2161748/1262753
  631. // var scripts = document.getElementsByTagName('script');
  632. // var jsFile = scripts[scripts.length-1].src.split('?')[0];
  633. // var cssFile = jsFile.substring(0, jsFile.length - 2) + 'css';
  634. // inject css
  635. // http://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript
  636. var style = document.createElement('style');
  637. style.type = 'text/css';
  638. if (style.styleSheet){
  639. style.styleSheet.cssText = css;
  640. } else {
  641. style.appendChild(document.createTextNode(css));
  642. }
  643. document.getElementsByTagName('head')[0].appendChild(style);
  644. };
  645. // Internet Explorer 8 and older does not support Array.indexOf, so we define
  646. // it here in that case.
  647. // http://soledadpenades.com/2007/05/17/arrayindexof-in-internet-explorer/
  648. if(!Array.prototype.indexOf) {
  649. Array.prototype.indexOf = function(obj){
  650. for(var i = 0; i < this.length; i++){
  651. if(this[i] == obj){
  652. return i;
  653. }
  654. }
  655. return -1;
  656. };
  657. try {
  658. console.log("Warning: Ancient browser detected. Please update your browser");
  659. }
  660. catch (err) {
  661. }
  662. }
  663. // Internet Explorer 8 and older does not support Array.forEach, so we define
  664. // it here in that case.
  665. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
  666. if (!Array.prototype.forEach) {
  667. Array.prototype.forEach = function(fn, scope) {
  668. for(var i = 0, len = this.length; i < len; ++i) {
  669. fn.call(scope || this, this[i], i, this);
  670. }
  671. }
  672. }
  673. // Internet Explorer 8 and older does not support Array.map, so we define it
  674. // here in that case.
  675. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
  676. // Production steps of ECMA-262, Edition 5, 15.4.4.19
  677. // Reference: http://es5.github.com/#x15.4.4.19
  678. if (!Array.prototype.map) {
  679. Array.prototype.map = function(callback, thisArg) {
  680. var T, A, k;
  681. if (this == null) {
  682. throw new TypeError(" this is null or not defined");
  683. }
  684. // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
  685. var O = Object(this);
  686. // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
  687. // 3. Let len be ToUint32(lenValue).
  688. var len = O.length >>> 0;
  689. // 4. If IsCallable(callback) is false, throw a TypeError exception.
  690. // See: http://es5.github.com/#x9.11
  691. if (typeof callback !== "function") {
  692. throw new TypeError(callback + " is not a function");
  693. }
  694. // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
  695. if (thisArg) {
  696. T = thisArg;
  697. }
  698. // 6. Let A be a new array created as if by the expression new Array(len) where Array is
  699. // the standard built-in constructor with that name and len is the value of len.
  700. A = new Array(len);
  701. // 7. Let k be 0
  702. k = 0;
  703. // 8. Repeat, while k < len
  704. while(k < len) {
  705. var kValue, mappedValue;
  706. // a. Let Pk be ToString(k).
  707. // This is implicit for LHS operands of the in operator
  708. // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
  709. // This step can be combined with c
  710. // c. If kPresent is true, then
  711. if (k in O) {
  712. // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
  713. kValue = O[ k ];
  714. // ii. Let mappedValue be the result of calling the Call internal method of callback
  715. // with T as the this value and argument list containing kValue, k, and O.
  716. mappedValue = callback.call(T, kValue, k, O);
  717. // iii. Call the DefineOwnProperty internal method of A with arguments
  718. // Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
  719. // and false.
  720. // In browsers that support Object.defineProperty, use the following:
  721. // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });
  722. // For best browser support, use the following:
  723. A[ k ] = mappedValue;
  724. }
  725. // d. Increase k by 1.
  726. k++;
  727. }
  728. // 9. return A
  729. return A;
  730. };
  731. }
  732. // Internet Explorer 8 and older does not support Array.filter, so we define it
  733. // here in that case.
  734. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
  735. if (!Array.prototype.filter) {
  736. Array.prototype.filter = function(fun /*, thisp */) {
  737. "use strict";
  738. if (this == null) {
  739. throw new TypeError();
  740. }
  741. var t = Object(this);
  742. var len = t.length >>> 0;
  743. if (typeof fun != "function") {
  744. throw new TypeError();
  745. }
  746. var res = [];
  747. var thisp = arguments[1];
  748. for (var i = 0; i < len; i++) {
  749. if (i in t) {
  750. var val = t[i]; // in case fun mutates this
  751. if (fun.call(thisp, val, i, t))
  752. res.push(val);
  753. }
  754. }
  755. return res;
  756. };
  757. }
  758. // Internet Explorer 8 and older does not support Object.keys, so we define it
  759. // here in that case.
  760. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys
  761. if (!Object.keys) {
  762. Object.keys = (function () {
  763. var hasOwnProperty = Object.prototype.hasOwnProperty,
  764. hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
  765. dontEnums = [
  766. 'toString',
  767. 'toLocaleString',
  768. 'valueOf',
  769. 'hasOwnProperty',
  770. 'isPrototypeOf',
  771. 'propertyIsEnumerable',
  772. 'constructor'
  773. ],
  774. dontEnumsLength = dontEnums.length;
  775. return function (obj) {
  776. if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
  777. throw new TypeError('Object.keys called on non-object');
  778. }
  779. var result = [];
  780. for (var prop in obj) {
  781. if (hasOwnProperty.call(obj, prop)) result.push(prop);
  782. }
  783. if (hasDontEnumBug) {
  784. for (var i=0; i < dontEnumsLength; i++) {
  785. if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
  786. }
  787. }
  788. return result;
  789. }
  790. })()
  791. }
  792. // Internet Explorer 8 and older does not support Array.isArray,
  793. // so we define it here in that case.
  794. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray
  795. if(!Array.isArray) {
  796. Array.isArray = function (vArg) {
  797. return Object.prototype.toString.call(vArg) === "[object Array]";
  798. };
  799. }
  800. // Internet Explorer 8 and older does not support Function.bind,
  801. // so we define it here in that case.
  802. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
  803. if (!Function.prototype.bind) {
  804. Function.prototype.bind = function (oThis) {
  805. if (typeof this !== "function") {
  806. // closest thing possible to the ECMAScript 5 internal IsCallable function
  807. throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
  808. }
  809. var aArgs = Array.prototype.slice.call(arguments, 1),
  810. fToBind = this,
  811. fNOP = function () {},
  812. fBound = function () {
  813. return fToBind.apply(this instanceof fNOP && oThis
  814. ? this
  815. : oThis,
  816. aArgs.concat(Array.prototype.slice.call(arguments)));
  817. };
  818. fNOP.prototype = this.prototype;
  819. fBound.prototype = new fNOP();
  820. return fBound;
  821. };
  822. }
  823. // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create
  824. if (!Object.create) {
  825. Object.create = function (o) {
  826. if (arguments.length > 1) {
  827. throw new Error('Object.create implementation only accepts the first parameter.');
  828. }
  829. function F() {}
  830. F.prototype = o;
  831. return new F();
  832. };
  833. }
  834. /**
  835. * Event listener (singleton)
  836. */
  837. // TODO: replace usage of the event listener for the EventBus
  838. var events = {
  839. 'listeners': [],
  840. /**
  841. * Find a single listener by its object
  842. * @param {Object} object
  843. * @return {Number} index -1 when not found
  844. */
  845. 'indexOf': function (object) {
  846. var listeners = this.listeners;
  847. for (var i = 0, iMax = this.listeners.length; i < iMax; i++) {
  848. var listener = listeners[i];
  849. if (listener && listener.object == object) {
  850. return i;
  851. }
  852. }
  853. return -1;
  854. },
  855. /**
  856. * Add an event listener
  857. * @param {Object} object
  858. * @param {String} event The name of an event, for example 'select'
  859. * @param {function} callback The callback method, called when the
  860. * event takes place
  861. */
  862. 'addListener': function (object, event, callback) {
  863. var index = this.indexOf(object);
  864. var listener = this.listeners[index];
  865. if (!listener) {
  866. listener = {
  867. 'object': object,
  868. 'events': {}
  869. };
  870. this.listeners.push(listener);
  871. }
  872. var callbacks = listener.events[event];
  873. if (!callbacks) {
  874. callbacks = [];
  875. listener.events[event] = callbacks;
  876. }
  877. // add the callback if it does not yet exist
  878. if (callbacks.indexOf(callback) == -1) {
  879. callbacks.push(callback);
  880. }
  881. },
  882. /**
  883. * Remove an event listener
  884. * @param {Object} object
  885. * @param {String} event The name of an event, for example 'select'
  886. * @param {function} callback The registered callback method
  887. */
  888. 'removeListener': function (object, event, callback) {
  889. var index = this.indexOf(object);
  890. var listener = this.listeners[index];
  891. if (listener) {
  892. var callbacks = listener.events[event];
  893. if (callbacks) {
  894. index = callbacks.indexOf(callback);
  895. if (index != -1) {
  896. callbacks.splice(index, 1);
  897. }
  898. // remove the array when empty
  899. if (callbacks.length == 0) {
  900. delete listener.events[event];
  901. }
  902. }
  903. // count the number of registered events. remove listener when empty
  904. var count = 0;
  905. var events = listener.events;
  906. for (var e in events) {
  907. if (events.hasOwnProperty(e)) {
  908. count++;
  909. }
  910. }
  911. if (count == 0) {
  912. delete this.listeners[index];
  913. }
  914. }
  915. },
  916. /**
  917. * Remove all registered event listeners
  918. */
  919. 'removeAllListeners': function () {
  920. this.listeners = [];
  921. },
  922. /**
  923. * Trigger an event. All registered event handlers will be called
  924. * @param {Object} object
  925. * @param {String} event
  926. * @param {Object} properties (optional)
  927. */
  928. 'trigger': function (object, event, properties) {
  929. var index = this.indexOf(object);
  930. var listener = this.listeners[index];
  931. if (listener) {
  932. var callbacks = listener.events[event];
  933. if (callbacks) {
  934. for (var i = 0, iMax = callbacks.length; i < iMax; i++) {
  935. callbacks[i](properties);
  936. }
  937. }
  938. }
  939. }
  940. };
  941. /**
  942. * An event bus can be used to emit events, and to subscribe to events
  943. * @constructor EventBus
  944. */
  945. function EventBus() {
  946. this.subscriptions = [];
  947. }
  948. /**
  949. * Subscribe to an event
  950. * @param {String | RegExp} event The event can be a regular expression, or
  951. * a string with wildcards, like 'server.*'.
  952. * @param {function} callback. Callback are called with three parameters:
  953. * {String} event, {*} [data], {*} [source]
  954. * @param {*} [target]
  955. * @returns {String} id A subscription id
  956. */
  957. EventBus.prototype.on = function (event, callback, target) {
  958. var regexp = (event instanceof RegExp) ?
  959. event :
  960. new RegExp(event.replace('*', '\\w+'));
  961. var subscription = {
  962. id: util.randomUUID(),
  963. event: event,
  964. regexp: regexp,
  965. callback: (typeof callback === 'function') ? callback : null,
  966. target: target
  967. };
  968. this.subscriptions.push(subscription);
  969. return subscription.id;
  970. };
  971. /**
  972. * Unsubscribe from an event
  973. * @param {String | Object} filter Filter for subscriptions to be removed
  974. * Filter can be a string containing a
  975. * subscription id, or an object containing
  976. * one or more of the fields id, event,
  977. * callback, and target.
  978. */
  979. EventBus.prototype.off = function (filter) {
  980. var i = 0;
  981. while (i < this.subscriptions.length) {
  982. var subscription = this.subscriptions[i];
  983. var match = true;
  984. if (filter instanceof Object) {
  985. // filter is an object. All fields must match
  986. for (var prop in filter) {
  987. if (filter.hasOwnProperty(prop)) {
  988. if (filter[prop] !== subscription[prop]) {
  989. match = false;
  990. }
  991. }
  992. }
  993. }
  994. else {
  995. // filter is a string, filter on id
  996. match = (subscription.id == filter);
  997. }
  998. if (match) {
  999. this.subscriptions.splice(i, 1);
  1000. }
  1001. else {
  1002. i++;
  1003. }
  1004. }
  1005. };
  1006. /**
  1007. * Emit an event
  1008. * @param {String} event
  1009. * @param {*} [data]
  1010. * @param {*} [source]
  1011. */
  1012. EventBus.prototype.emit = function (event, data, source) {
  1013. for (var i =0; i < this.subscriptions.length; i++) {
  1014. var subscription = this.subscriptions[i];
  1015. if (subscription.regexp.test(event)) {
  1016. if (subscription.callback) {
  1017. subscription.callback(event, data, source);
  1018. }
  1019. }
  1020. }
  1021. };
  1022. /**
  1023. * DataSet
  1024. *
  1025. * Usage:
  1026. * var dataSet = new DataSet({
  1027. * fieldId: '_id',
  1028. * convert: {
  1029. * // ...
  1030. * }
  1031. * });
  1032. *
  1033. * dataSet.add(item);
  1034. * dataSet.add(data);
  1035. * dataSet.update(item);
  1036. * dataSet.update(data);
  1037. * dataSet.remove(id);
  1038. * dataSet.remove(ids);
  1039. * var data = dataSet.get();
  1040. * var data = dataSet.get(id);
  1041. * var data = dataSet.get(ids);
  1042. * var data = dataSet.get(ids, options, data);
  1043. * dataSet.clear();
  1044. *
  1045. * A data set can:
  1046. * - add/remove/update data
  1047. * - gives triggers upon changes in the data
  1048. * - can import/export data in various data formats
  1049. *
  1050. * @param {Object} [options] Available options:
  1051. * {String} fieldId Field name of the id in the
  1052. * items, 'id' by default.
  1053. * {Object.<String, String} convert
  1054. * A map with field names as key,
  1055. * and the field type as value.
  1056. * @constructor DataSet
  1057. */
  1058. // TODO: add a DataSet constructor DataSet(data, options)
  1059. function DataSet (options) {
  1060. this.id = util.randomUUID();
  1061. this.options = options || {};
  1062. this.data = {}; // map with data indexed by id
  1063. this.fieldId = this.options.fieldId || 'id'; // name of the field containing id
  1064. this.convert = {}; // field types by field name
  1065. if (this.options.convert) {
  1066. for (var field in this.options.convert) {
  1067. if (this.options.convert.hasOwnProperty(field)) {
  1068. var value = this.options.convert[field];
  1069. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1070. this.convert[field] = 'Date';
  1071. }
  1072. else {
  1073. this.convert[field] = value;
  1074. }
  1075. }
  1076. }
  1077. }
  1078. // event subscribers
  1079. this.subscribers = {};
  1080. this.internalIds = {}; // internally generated id's
  1081. }
  1082. /**
  1083. * Subscribe to an event, add an event listener
  1084. * @param {String} event Event name. Available events: 'put', 'update',
  1085. * 'remove'
  1086. * @param {function} callback Callback method. Called with three parameters:
  1087. * {String} event
  1088. * {Object | null} params
  1089. * {String | Number} senderId
  1090. */
  1091. DataSet.prototype.subscribe = function (event, callback) {
  1092. var subscribers = this.subscribers[event];
  1093. if (!subscribers) {
  1094. subscribers = [];
  1095. this.subscribers[event] = subscribers;
  1096. }
  1097. subscribers.push({
  1098. callback: callback
  1099. });
  1100. };
  1101. /**
  1102. * Unsubscribe from an event, remove an event listener
  1103. * @param {String} event
  1104. * @param {function} callback
  1105. */
  1106. DataSet.prototype.unsubscribe = function (event, callback) {
  1107. var subscribers = this.subscribers[event];
  1108. if (subscribers) {
  1109. this.subscribers[event] = subscribers.filter(function (listener) {
  1110. return (listener.callback != callback);
  1111. });
  1112. }
  1113. };
  1114. /**
  1115. * Trigger an event
  1116. * @param {String} event
  1117. * @param {Object | null} params
  1118. * @param {String} [senderId] Optional id of the sender.
  1119. * @private
  1120. */
  1121. DataSet.prototype._trigger = function (event, params, senderId) {
  1122. if (event == '*') {
  1123. throw new Error('Cannot trigger event *');
  1124. }
  1125. var subscribers = [];
  1126. if (event in this.subscribers) {
  1127. subscribers = subscribers.concat(this.subscribers[event]);
  1128. }
  1129. if ('*' in this.subscribers) {
  1130. subscribers = subscribers.concat(this.subscribers['*']);
  1131. }
  1132. for (var i = 0; i < subscribers.length; i++) {
  1133. var subscriber = subscribers[i];
  1134. if (subscriber.callback) {
  1135. subscriber.callback(event, params, senderId || null);
  1136. }
  1137. }
  1138. };
  1139. /**
  1140. * Add data.
  1141. * Adding an item will fail when there already is an item with the same id.
  1142. * @param {Object | Array | DataTable} data
  1143. * @param {String} [senderId] Optional sender id
  1144. * @return {Array} addedIds Array with the ids of the added items
  1145. */
  1146. DataSet.prototype.add = function (data, senderId) {
  1147. var addedIds = [],
  1148. id,
  1149. me = this;
  1150. if (data instanceof Array) {
  1151. // Array
  1152. for (var i = 0, len = data.length; i < len; i++) {
  1153. id = me._addItem(data[i]);
  1154. addedIds.push(id);
  1155. }
  1156. }
  1157. else if (util.isDataTable(data)) {
  1158. // Google DataTable
  1159. var columns = this._getColumnNames(data);
  1160. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1161. var item = {};
  1162. for (var col = 0, cols = columns.length; col < cols; col++) {
  1163. var field = columns[col];
  1164. item[field] = data.getValue(row, col);
  1165. }
  1166. id = me._addItem(item);
  1167. addedIds.push(id);
  1168. }
  1169. }
  1170. else if (data instanceof Object) {
  1171. // Single item
  1172. id = me._addItem(data);
  1173. addedIds.push(id);
  1174. }
  1175. else {
  1176. throw new Error('Unknown dataType');
  1177. }
  1178. if (addedIds.length) {
  1179. this._trigger('add', {items: addedIds}, senderId);
  1180. }
  1181. return addedIds;
  1182. };
  1183. /**
  1184. * Update existing items. When an item does not exist, it will be created
  1185. * @param {Object | Array | DataTable} data
  1186. * @param {String} [senderId] Optional sender id
  1187. * @return {Array} updatedIds The ids of the added or updated items
  1188. */
  1189. DataSet.prototype.update = function (data, senderId) {
  1190. var addedIds = [],
  1191. updatedIds = [],
  1192. me = this,
  1193. fieldId = me.fieldId;
  1194. var addOrUpdate = function (item) {
  1195. var id = item[fieldId];
  1196. if (me.data[id]) {
  1197. // update item
  1198. id = me._updateItem(item);
  1199. updatedIds.push(id);
  1200. }
  1201. else {
  1202. // add new item
  1203. id = me._addItem(item);
  1204. addedIds.push(id);
  1205. }
  1206. };
  1207. if (data instanceof Array) {
  1208. // Array
  1209. for (var i = 0, len = data.length; i < len; i++) {
  1210. addOrUpdate(data[i]);
  1211. }
  1212. }
  1213. else if (util.isDataTable(data)) {
  1214. // Google DataTable
  1215. var columns = this._getColumnNames(data);
  1216. for (var row = 0, rows = data.getNumberOfRows(); row < rows; row++) {
  1217. var item = {};
  1218. for (var col = 0, cols = columns.length; col < cols; col++) {
  1219. var field = columns[col];
  1220. item[field] = data.getValue(row, col);
  1221. }
  1222. addOrUpdate(item);
  1223. }
  1224. }
  1225. else if (data instanceof Object) {
  1226. // Single item
  1227. addOrUpdate(data);
  1228. }
  1229. else {
  1230. throw new Error('Unknown dataType');
  1231. }
  1232. if (addedIds.length) {
  1233. this._trigger('add', {items: addedIds}, senderId);
  1234. }
  1235. if (updatedIds.length) {
  1236. this._trigger('update', {items: updatedIds}, senderId);
  1237. }
  1238. return addedIds.concat(updatedIds);
  1239. };
  1240. /**
  1241. * Get a data item or multiple items.
  1242. *
  1243. * Usage:
  1244. *
  1245. * get()
  1246. * get(options: Object)
  1247. * get(options: Object, data: Array | DataTable)
  1248. *
  1249. * get(id: Number | String)
  1250. * get(id: Number | String, options: Object)
  1251. * get(id: Number | String, options: Object, data: Array | DataTable)
  1252. *
  1253. * get(ids: Number[] | String[])
  1254. * get(ids: Number[] | String[], options: Object)
  1255. * get(ids: Number[] | String[], options: Object, data: Array | DataTable)
  1256. *
  1257. * Where:
  1258. *
  1259. * {Number | String} id The id of an item
  1260. * {Number[] | String{}} ids An array with ids of items
  1261. * {Object} options An Object with options. Available options:
  1262. * {String} [type] Type of data to be returned. Can
  1263. * be 'DataTable' or 'Array' (default)
  1264. * {Object.<String, String>} [convert]
  1265. * {String[]} [fields] field names to be returned
  1266. * {function} [filter] filter items
  1267. * {String | function} [order] Order the items by
  1268. * a field name or custom sort function.
  1269. * {Array | DataTable} [data] If provided, items will be appended to this
  1270. * array or table. Required in case of Google
  1271. * DataTable.
  1272. *
  1273. * @throws Error
  1274. */
  1275. DataSet.prototype.get = function (args) {
  1276. var me = this;
  1277. // parse the arguments
  1278. var id, ids, options, data;
  1279. var firstType = util.getType(arguments[0]);
  1280. if (firstType == 'String' || firstType == 'Number') {
  1281. // get(id [, options] [, data])
  1282. id = arguments[0];
  1283. options = arguments[1];
  1284. data = arguments[2];
  1285. }
  1286. else if (firstType == 'Array') {
  1287. // get(ids [, options] [, data])
  1288. ids = arguments[0];
  1289. options = arguments[1];
  1290. data = arguments[2];
  1291. }
  1292. else {
  1293. // get([, options] [, data])
  1294. options = arguments[0];
  1295. data = arguments[1];
  1296. }
  1297. // determine the return type
  1298. var type;
  1299. if (options && options.type) {
  1300. type = (options.type == 'DataTable') ? 'DataTable' : 'Array';
  1301. if (data && (type != util.getType(data))) {
  1302. throw new Error('Type of parameter "data" (' + util.getType(data) + ') ' +
  1303. 'does not correspond with specified options.type (' + options.type + ')');
  1304. }
  1305. if (type == 'DataTable' && !util.isDataTable(data)) {
  1306. throw new Error('Parameter "data" must be a DataTable ' +
  1307. 'when options.type is "DataTable"');
  1308. }
  1309. }
  1310. else if (data) {
  1311. type = (util.getType(data) == 'DataTable') ? 'DataTable' : 'Array';
  1312. }
  1313. else {
  1314. type = 'Array';
  1315. }
  1316. // build options
  1317. var convert = options && options.convert || this.options.convert;
  1318. var filter = options && options.filter;
  1319. var items = [], item, itemId, i, len;
  1320. // convert items
  1321. if (id != undefined) {
  1322. // return a single item
  1323. item = me._getItem(id, convert);
  1324. if (filter && !filter(item)) {
  1325. item = null;
  1326. }
  1327. }
  1328. else if (ids != undefined) {
  1329. // return a subset of items
  1330. for (i = 0, len = ids.length; i < len; i++) {
  1331. item = me._getItem(ids[i], convert);
  1332. if (!filter || filter(item)) {
  1333. items.push(item);
  1334. }
  1335. }
  1336. }
  1337. else {
  1338. // return all items
  1339. for (itemId in this.data) {
  1340. if (this.data.hasOwnProperty(itemId)) {
  1341. item = me._getItem(itemId, convert);
  1342. if (!filter || filter(item)) {
  1343. items.push(item);
  1344. }
  1345. }
  1346. }
  1347. }
  1348. // order the results
  1349. if (options && options.order && id == undefined) {
  1350. this._sort(items, options.order);
  1351. }
  1352. // filter fields of the items
  1353. if (options && options.fields) {
  1354. var fields = options.fields;
  1355. if (id != undefined) {
  1356. item = this._filterFields(item, fields);
  1357. }
  1358. else {
  1359. for (i = 0, len = items.length; i < len; i++) {
  1360. items[i] = this._filterFields(items[i], fields);
  1361. }
  1362. }
  1363. }
  1364. // return the results
  1365. if (type == 'DataTable') {
  1366. var columns = this._getColumnNames(data);
  1367. if (id != undefined) {
  1368. // append a single item to the data table
  1369. me._appendRow(data, columns, item);
  1370. }
  1371. else {
  1372. // copy the items to the provided data table
  1373. for (i = 0, len = items.length; i < len; i++) {
  1374. me._appendRow(data, columns, items[i]);
  1375. }
  1376. }
  1377. return data;
  1378. }
  1379. else {
  1380. // return an array
  1381. if (id != undefined) {
  1382. // a single item
  1383. return item;
  1384. }
  1385. else {
  1386. // multiple items
  1387. if (data) {
  1388. // copy the items to the provided array
  1389. for (i = 0, len = items.length; i < len; i++) {
  1390. data.push(items[i]);
  1391. }
  1392. return data;
  1393. }
  1394. else {
  1395. // just return our array
  1396. return items;
  1397. }
  1398. }
  1399. }
  1400. };
  1401. /**
  1402. * Get ids of all items or from a filtered set of items.
  1403. * @param {Object} [options] An Object with options. Available options:
  1404. * {function} [filter] filter items
  1405. * {String | function} [order] Order the items by
  1406. * a field name or custom sort function.
  1407. * @return {Array} ids
  1408. */
  1409. DataSet.prototype.getIds = function (options) {
  1410. var data = this.data,
  1411. filter = options && options.filter,
  1412. order = options && options.order,
  1413. convert = options && options.convert || this.options.convert,
  1414. i,
  1415. len,
  1416. id,
  1417. item,
  1418. items,
  1419. ids = [];
  1420. if (filter) {
  1421. // get filtered items
  1422. if (order) {
  1423. // create ordered list
  1424. items = [];
  1425. for (id in data) {
  1426. if (data.hasOwnProperty(id)) {
  1427. item = this._getItem(id, convert);
  1428. if (filter(item)) {
  1429. items.push(item);
  1430. }
  1431. }
  1432. }
  1433. this._sort(items, order);
  1434. for (i = 0, len = items.length; i < len; i++) {
  1435. ids[i] = items[i][this.fieldId];
  1436. }
  1437. }
  1438. else {
  1439. // create unordered list
  1440. for (id in data) {
  1441. if (data.hasOwnProperty(id)) {
  1442. item = this._getItem(id, convert);
  1443. if (filter(item)) {
  1444. ids.push(item[this.fieldId]);
  1445. }
  1446. }
  1447. }
  1448. }
  1449. }
  1450. else {
  1451. // get all items
  1452. if (order) {
  1453. // create an ordered list
  1454. items = [];
  1455. for (id in data) {
  1456. if (data.hasOwnProperty(id)) {
  1457. items.push(data[id]);
  1458. }
  1459. }
  1460. this._sort(items, order);
  1461. for (i = 0, len = items.length; i < len; i++) {
  1462. ids[i] = items[i][this.fieldId];
  1463. }
  1464. }
  1465. else {
  1466. // create unordered list
  1467. for (id in data) {
  1468. if (data.hasOwnProperty(id)) {
  1469. item = data[id];
  1470. ids.push(item[this.fieldId]);
  1471. }
  1472. }
  1473. }
  1474. }
  1475. return ids;
  1476. };
  1477. /**
  1478. * Execute a callback function for every item in the dataset.
  1479. * The order of the items is not determined.
  1480. * @param {function} callback
  1481. * @param {Object} [options] Available options:
  1482. * {Object.<String, String>} [convert]
  1483. * {String[]} [fields] filter fields
  1484. * {function} [filter] filter items
  1485. * {String | function} [order] Order the items by
  1486. * a field name or custom sort function.
  1487. */
  1488. DataSet.prototype.forEach = function (callback, options) {
  1489. var filter = options && options.filter,
  1490. convert = options && options.convert || this.options.convert,
  1491. data = this.data,
  1492. item,
  1493. id;
  1494. if (options && options.order) {
  1495. // execute forEach on ordered list
  1496. var items = this.get(options);
  1497. for (var i = 0, len = items.length; i < len; i++) {
  1498. item = items[i];
  1499. id = item[this.fieldId];
  1500. callback(item, id);
  1501. }
  1502. }
  1503. else {
  1504. // unordered
  1505. for (id in data) {
  1506. if (data.hasOwnProperty(id)) {
  1507. item = this._getItem(id, convert);
  1508. if (!filter || filter(item)) {
  1509. callback(item, id);
  1510. }
  1511. }
  1512. }
  1513. }
  1514. };
  1515. /**
  1516. * Map every item in the dataset.
  1517. * @param {function} callback
  1518. * @param {Object} [options] Available options:
  1519. * {Object.<String, String>} [convert]
  1520. * {String[]} [fields] filter fields
  1521. * {function} [filter] filter items
  1522. * {String | function} [order] Order the items by
  1523. * a field name or custom sort function.
  1524. * @return {Object[]} mappedItems
  1525. */
  1526. DataSet.prototype.map = function (callback, options) {
  1527. var filter = options && options.filter,
  1528. convert = options && options.convert || this.options.convert,
  1529. mappedItems = [],
  1530. data = this.data,
  1531. item;
  1532. // convert and filter items
  1533. for (var id in data) {
  1534. if (data.hasOwnProperty(id)) {
  1535. item = this._getItem(id, convert);
  1536. if (!filter || filter(item)) {
  1537. mappedItems.push(callback(item, id));
  1538. }
  1539. }
  1540. }
  1541. // order items
  1542. if (options && options.order) {
  1543. this._sort(mappedItems, options.order);
  1544. }
  1545. return mappedItems;
  1546. };
  1547. /**
  1548. * Filter the fields of an item
  1549. * @param {Object} item
  1550. * @param {String[]} fields Field names
  1551. * @return {Object} filteredItem
  1552. * @private
  1553. */
  1554. DataSet.prototype._filterFields = function (item, fields) {
  1555. var filteredItem = {};
  1556. for (var field in item) {
  1557. if (item.hasOwnProperty(field) && (fields.indexOf(field) != -1)) {
  1558. filteredItem[field] = item[field];
  1559. }
  1560. }
  1561. return filteredItem;
  1562. };
  1563. /**
  1564. * Sort the provided array with items
  1565. * @param {Object[]} items
  1566. * @param {String | function} order A field name or custom sort function.
  1567. * @private
  1568. */
  1569. DataSet.prototype._sort = function (items, order) {
  1570. if (util.isString(order)) {
  1571. // order by provided field name
  1572. var name = order; // field name
  1573. items.sort(function (a, b) {
  1574. var av = a[name];
  1575. var bv = b[name];
  1576. return (av > bv) ? 1 : ((av < bv) ? -1 : 0);
  1577. });
  1578. }
  1579. else if (typeof order === 'function') {
  1580. // order by sort function
  1581. items.sort(order);
  1582. }
  1583. // TODO: extend order by an Object {field:String, direction:String}
  1584. // where direction can be 'asc' or 'desc'
  1585. else {
  1586. throw new TypeError('Order must be a function or a string');
  1587. }
  1588. };
  1589. /**
  1590. * Remove an object by pointer or by id
  1591. * @param {String | Number | Object | Array} id Object or id, or an array with
  1592. * objects or ids to be removed
  1593. * @param {String} [senderId] Optional sender id
  1594. * @return {Array} removedIds
  1595. */
  1596. DataSet.prototype.remove = function (id, senderId) {
  1597. var removedIds = [],
  1598. i, len, removedId;
  1599. if (id instanceof Array) {
  1600. for (i = 0, len = id.length; i < len; i++) {
  1601. removedId = this._remove(id[i]);
  1602. if (removedId != null) {
  1603. removedIds.push(removedId);
  1604. }
  1605. }
  1606. }
  1607. else {
  1608. removedId = this._remove(id);
  1609. if (removedId != null) {
  1610. removedIds.push(removedId);
  1611. }
  1612. }
  1613. if (removedIds.length) {
  1614. this._trigger('remove', {items: removedIds}, senderId);
  1615. }
  1616. return removedIds;
  1617. };
  1618. /**
  1619. * Remove an item by its id
  1620. * @param {Number | String | Object} id id or item
  1621. * @returns {Number | String | null} id
  1622. * @private
  1623. */
  1624. DataSet.prototype._remove = function (id) {
  1625. if (util.isNumber(id) || util.isString(id)) {
  1626. if (this.data[id]) {
  1627. delete this.data[id];
  1628. delete this.internalIds[id];
  1629. return id;
  1630. }
  1631. }
  1632. else if (id instanceof Object) {
  1633. var itemId = id[this.fieldId];
  1634. if (itemId && this.data[itemId]) {
  1635. delete this.data[itemId];
  1636. delete this.internalIds[itemId];
  1637. return itemId;
  1638. }
  1639. }
  1640. return null;
  1641. };
  1642. /**
  1643. * Clear the data
  1644. * @param {String} [senderId] Optional sender id
  1645. * @return {Array} removedIds The ids of all removed items
  1646. */
  1647. DataSet.prototype.clear = function (senderId) {
  1648. var ids = Object.keys(this.data);
  1649. this.data = {};
  1650. this.internalIds = {};
  1651. this._trigger('remove', {items: ids}, senderId);
  1652. return ids;
  1653. };
  1654. /**
  1655. * Find the item with maximum value of a specified field
  1656. * @param {String} field
  1657. * @return {Object | null} item Item containing max value, or null if no items
  1658. */
  1659. DataSet.prototype.max = function (field) {
  1660. var data = this.data,
  1661. max = null,
  1662. maxField = null;
  1663. for (var id in data) {
  1664. if (data.hasOwnProperty(id)) {
  1665. var item = data[id];
  1666. var itemField = item[field];
  1667. if (itemField != null && (!max || itemField > maxField)) {
  1668. max = item;
  1669. maxField = itemField;
  1670. }
  1671. }
  1672. }
  1673. return max;
  1674. };
  1675. /**
  1676. * Find the item with minimum value of a specified field
  1677. * @param {String} field
  1678. * @return {Object | null} item Item containing max value, or null if no items
  1679. */
  1680. DataSet.prototype.min = function (field) {
  1681. var data = this.data,
  1682. min = null,
  1683. minField = null;
  1684. for (var id in data) {
  1685. if (data.hasOwnProperty(id)) {
  1686. var item = data[id];
  1687. var itemField = item[field];
  1688. if (itemField != null && (!min || itemField < minField)) {
  1689. min = item;
  1690. minField = itemField;
  1691. }
  1692. }
  1693. }
  1694. return min;
  1695. };
  1696. /**
  1697. * Find all distinct values of a specified field
  1698. * @param {String} field
  1699. * @return {Array} values Array containing all distinct values. If the data
  1700. * items do not contain the specified field, an array
  1701. * containing a single value undefined is returned.
  1702. * The returned array is unordered.
  1703. */
  1704. DataSet.prototype.distinct = function (field) {
  1705. var data = this.data,
  1706. values = [],
  1707. fieldType = this.options.convert[field],
  1708. count = 0;
  1709. for (var prop in data) {
  1710. if (data.hasOwnProperty(prop)) {
  1711. var item = data[prop];
  1712. var value = util.convert(item[field], fieldType);
  1713. var exists = false;
  1714. for (var i = 0; i < count; i++) {
  1715. if (values[i] == value) {
  1716. exists = true;
  1717. break;
  1718. }
  1719. }
  1720. if (!exists) {
  1721. values[count] = value;
  1722. count++;
  1723. }
  1724. }
  1725. }
  1726. return values;
  1727. };
  1728. /**
  1729. * Add a single item. Will fail when an item with the same id already exists.
  1730. * @param {Object} item
  1731. * @return {String} id
  1732. * @private
  1733. */
  1734. DataSet.prototype._addItem = function (item) {
  1735. var id = item[this.fieldId];
  1736. if (id != undefined) {
  1737. // check whether this id is already taken
  1738. if (this.data[id]) {
  1739. // item already exists
  1740. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  1741. }
  1742. }
  1743. else {
  1744. // generate an id
  1745. id = util.randomUUID();
  1746. item[this.fieldId] = id;
  1747. this.internalIds[id] = item;
  1748. }
  1749. var d = {};
  1750. for (var field in item) {
  1751. if (item.hasOwnProperty(field)) {
  1752. var fieldType = this.convert[field]; // type may be undefined
  1753. d[field] = util.convert(item[field], fieldType);
  1754. }
  1755. }
  1756. this.data[id] = d;
  1757. return id;
  1758. };
  1759. /**
  1760. * Get an item. Fields can be converted to a specific type
  1761. * @param {String} id
  1762. * @param {Object.<String, String>} [convert] field types to convert
  1763. * @return {Object | null} item
  1764. * @private
  1765. */
  1766. DataSet.prototype._getItem = function (id, convert) {
  1767. var field, value;
  1768. // get the item from the dataset
  1769. var raw = this.data[id];
  1770. if (!raw) {
  1771. return null;
  1772. }
  1773. // convert the items field types
  1774. var converted = {},
  1775. fieldId = this.fieldId,
  1776. internalIds = this.internalIds;
  1777. if (convert) {
  1778. for (field in raw) {
  1779. if (raw.hasOwnProperty(field)) {
  1780. value = raw[field];
  1781. // output all fields, except internal ids
  1782. if ((field != fieldId) || !(value in internalIds)) {
  1783. converted[field] = util.convert(value, convert[field]);
  1784. }
  1785. }
  1786. }
  1787. }
  1788. else {
  1789. // no field types specified, no converting needed
  1790. for (field in raw) {
  1791. if (raw.hasOwnProperty(field)) {
  1792. value = raw[field];
  1793. // output all fields, except internal ids
  1794. if ((field != fieldId) || !(value in internalIds)) {
  1795. converted[field] = value;
  1796. }
  1797. }
  1798. }
  1799. }
  1800. return converted;
  1801. };
  1802. /**
  1803. * Update a single item: merge with existing item.
  1804. * Will fail when the item has no id, or when there does not exist an item
  1805. * with the same id.
  1806. * @param {Object} item
  1807. * @return {String} id
  1808. * @private
  1809. */
  1810. DataSet.prototype._updateItem = function (item) {
  1811. var id = item[this.fieldId];
  1812. if (id == undefined) {
  1813. throw new Error('Cannot update item: item has no id (item: ' + JSON.stringify(item) + ')');
  1814. }
  1815. var d = this.data[id];
  1816. if (!d) {
  1817. // item doesn't exist
  1818. throw new Error('Cannot update item: no item with id ' + id + ' found');
  1819. }
  1820. // merge with current item
  1821. for (var field in item) {
  1822. if (item.hasOwnProperty(field)) {
  1823. var fieldType = this.convert[field]; // type may be undefined
  1824. d[field] = util.convert(item[field], fieldType);
  1825. }
  1826. }
  1827. return id;
  1828. };
  1829. /**
  1830. * Get an array with the column names of a Google DataTable
  1831. * @param {DataTable} dataTable
  1832. * @return {String[]} columnNames
  1833. * @private
  1834. */
  1835. DataSet.prototype._getColumnNames = function (dataTable) {
  1836. var columns = [];
  1837. for (var col = 0, cols = dataTable.getNumberOfColumns(); col < cols; col++) {
  1838. columns[col] = dataTable.getColumnId(col) || dataTable.getColumnLabel(col);
  1839. }
  1840. return columns;
  1841. };
  1842. /**
  1843. * Append an item as a row to the dataTable
  1844. * @param dataTable
  1845. * @param columns
  1846. * @param item
  1847. * @private
  1848. */
  1849. DataSet.prototype._appendRow = function (dataTable, columns, item) {
  1850. var row = dataTable.addRow();
  1851. for (var col = 0, cols = columns.length; col < cols; col++) {
  1852. var field = columns[col];
  1853. dataTable.setValue(row, col, item[field]);
  1854. }
  1855. };
  1856. /**
  1857. * DataView
  1858. *
  1859. * a dataview offers a filtered view on a dataset or an other dataview.
  1860. *
  1861. * @param {DataSet | DataView} data
  1862. * @param {Object} [options] Available options: see method get
  1863. *
  1864. * @constructor DataView
  1865. */
  1866. function DataView (data, options) {
  1867. this.id = util.randomUUID();
  1868. this.data = null;
  1869. this.ids = {}; // ids of the items currently in memory (just contains a boolean true)
  1870. this.options = options || {};
  1871. this.fieldId = 'id'; // name of the field containing id
  1872. this.subscribers = {}; // event subscribers
  1873. var me = this;
  1874. this.listener = function () {
  1875. me._onEvent.apply(me, arguments);
  1876. };
  1877. this.setData(data);
  1878. }
  1879. /**
  1880. * Set a data source for the view
  1881. * @param {DataSet | DataView} data
  1882. */
  1883. DataView.prototype.setData = function (data) {
  1884. var ids, dataItems, i, len;
  1885. if (this.data) {
  1886. // unsubscribe from current dataset
  1887. if (this.data.unsubscribe) {
  1888. this.data.unsubscribe('*', this.listener);
  1889. }
  1890. // trigger a remove of all items in memory
  1891. ids = [];
  1892. for (var id in this.ids) {
  1893. if (this.ids.hasOwnProperty(id)) {
  1894. ids.push(id);
  1895. }
  1896. }
  1897. this.ids = {};
  1898. this._trigger('remove', {items: ids});
  1899. }
  1900. this.data = data;
  1901. if (this.data) {
  1902. // update fieldId
  1903. this.fieldId = this.options.fieldId ||
  1904. (this.data && this.data.options && this.data.options.fieldId) ||
  1905. 'id';
  1906. // trigger an add of all added items
  1907. ids = this.data.getIds({filter: this.options && this.options.filter});
  1908. for (i = 0, len = ids.length; i < len; i++) {
  1909. id = ids[i];
  1910. this.ids[id] = true;
  1911. }
  1912. this._trigger('add', {items: ids});
  1913. // subscribe to new dataset
  1914. if (this.data.subscribe) {
  1915. this.data.subscribe('*', this.listener);
  1916. }
  1917. }
  1918. };
  1919. /**
  1920. * Get data from the data view
  1921. *
  1922. * Usage:
  1923. *
  1924. * get()
  1925. * get(options: Object)
  1926. * get(options: Object, data: Array | DataTable)
  1927. *
  1928. * get(id: Number)
  1929. * get(id: Number, options: Object)
  1930. * get(id: Number, options: Object, data: Array | DataTable)
  1931. *
  1932. * get(ids: Number[])
  1933. * get(ids: Number[], options: Object)
  1934. * get(ids: Number[], options: Object, data: Array | DataTable)
  1935. *
  1936. * Where:
  1937. *
  1938. * {Number | String} id The id of an item
  1939. * {Number[] | String{}} ids An array with ids of items
  1940. * {Object} options An Object with options. Available options:
  1941. * {String} [type] Type of data to be returned. Can
  1942. * be 'DataTable' or 'Array' (default)
  1943. * {Object.<String, String>} [convert]
  1944. * {String[]} [fields] field names to be returned
  1945. * {function} [filter] filter items
  1946. * {String | function} [order] Order the items by
  1947. * a field name or custom sort function.
  1948. * {Array | DataTable} [data] If provided, items will be appended to this
  1949. * array or table. Required in case of Google
  1950. * DataTable.
  1951. * @param args
  1952. */
  1953. DataView.prototype.get = function (args) {
  1954. var me = this;
  1955. // parse the arguments
  1956. var ids, options, data;
  1957. var firstType = util.getType(arguments[0]);
  1958. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  1959. // get(id(s) [, options] [, data])
  1960. ids = arguments[0]; // can be a single id or an array with ids
  1961. options = arguments[1];
  1962. data = arguments[2];
  1963. }
  1964. else {
  1965. // get([, options] [, data])
  1966. options = arguments[0];
  1967. data = arguments[1];
  1968. }
  1969. // extend the options with the default options and provided options
  1970. var viewOptions = util.extend({}, this.options, options);
  1971. // create a combined filter method when needed
  1972. if (this.options.filter && options && options.filter) {
  1973. viewOptions.filter = function (item) {
  1974. return me.options.filter(item) && options.filter(item);
  1975. }
  1976. }
  1977. // build up the call to the linked data set
  1978. var getArguments = [];
  1979. if (ids != undefined) {
  1980. getArguments.push(ids);
  1981. }
  1982. getArguments.push(viewOptions);
  1983. getArguments.push(data);
  1984. return this.data && this.data.get.apply(this.data, getArguments);
  1985. };
  1986. /**
  1987. * Get ids of all items or from a filtered set of items.
  1988. * @param {Object} [options] An Object with options. Available options:
  1989. * {function} [filter] filter items
  1990. * {String | function} [order] Order the items by
  1991. * a field name or custom sort function.
  1992. * @return {Array} ids
  1993. */
  1994. DataView.prototype.getIds = function (options) {
  1995. var ids;
  1996. if (this.data) {
  1997. var defaultFilter = this.options.filter;
  1998. var filter;
  1999. if (options && options.filter) {
  2000. if (defaultFilter) {
  2001. filter = function (item) {
  2002. return defaultFilter(item) && options.filter(item);
  2003. }
  2004. }
  2005. else {
  2006. filter = options.filter;
  2007. }
  2008. }
  2009. else {
  2010. filter = defaultFilter;
  2011. }
  2012. ids = this.data.getIds({
  2013. filter: filter,
  2014. order: options && options.order
  2015. });
  2016. }
  2017. else {
  2018. ids = [];
  2019. }
  2020. return ids;
  2021. };
  2022. /**
  2023. * Event listener. Will propagate all events from the connected data set to
  2024. * the subscribers of the DataView, but will filter the items and only trigger
  2025. * when there are changes in the filtered data set.
  2026. * @param {String} event
  2027. * @param {Object | null} params
  2028. * @param {String} senderId
  2029. * @private
  2030. */
  2031. DataView.prototype._onEvent = function (event, params, senderId) {
  2032. var i, len, id, item,
  2033. ids = params && params.items,
  2034. data = this.data,
  2035. added = [],
  2036. updated = [],
  2037. removed = [];
  2038. if (ids && data) {
  2039. switch (event) {
  2040. case 'add':
  2041. // filter the ids of the added items
  2042. for (i = 0, len = ids.length; i < len; i++) {
  2043. id = ids[i];
  2044. item = this.get(id);
  2045. if (item) {
  2046. this.ids[id] = true;
  2047. added.push(id);
  2048. }
  2049. }
  2050. break;
  2051. case 'update':
  2052. // determine the event from the views viewpoint: an updated
  2053. // item can be added, updated, or removed from this view.
  2054. for (i = 0, len = ids.length; i < len; i++) {
  2055. id = ids[i];
  2056. item = this.get(id);
  2057. if (item) {
  2058. if (this.ids[id]) {
  2059. updated.push(id);
  2060. }
  2061. else {
  2062. this.ids[id] = true;
  2063. added.push(id);
  2064. }
  2065. }
  2066. else {
  2067. if (this.ids[id]) {
  2068. delete this.ids[id];
  2069. removed.push(id);
  2070. }
  2071. else {
  2072. // nothing interesting for me :-(
  2073. }
  2074. }
  2075. }
  2076. break;
  2077. case 'remove':
  2078. // filter the ids of the removed items
  2079. for (i = 0, len = ids.length; i < len; i++) {
  2080. id = ids[i];
  2081. if (this.ids[id]) {
  2082. delete this.ids[id];
  2083. removed.push(id);
  2084. }
  2085. }
  2086. break;
  2087. }
  2088. if (added.length) {
  2089. this._trigger('add', {items: added}, senderId);
  2090. }
  2091. if (updated.length) {
  2092. this._trigger('update', {items: updated}, senderId);
  2093. }
  2094. if (removed.length) {
  2095. this._trigger('remove', {items: removed}, senderId);
  2096. }
  2097. }
  2098. };
  2099. // copy subscription functionality from DataSet
  2100. DataView.prototype.subscribe = DataSet.prototype.subscribe;
  2101. DataView.prototype.unsubscribe = DataSet.prototype.unsubscribe;
  2102. DataView.prototype._trigger = DataSet.prototype._trigger;
  2103. /**
  2104. * @constructor TimeStep
  2105. * The class TimeStep is an iterator for dates. You provide a start date and an
  2106. * end date. The class itself determines the best scale (step size) based on the
  2107. * provided start Date, end Date, and minimumStep.
  2108. *
  2109. * If minimumStep is provided, the step size is chosen as close as possible
  2110. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2111. * provided, the scale is set to 1 DAY.
  2112. * The minimumStep should correspond with the onscreen size of about 6 characters
  2113. *
  2114. * Alternatively, you can set a scale by hand.
  2115. * After creation, you can initialize the class by executing first(). Then you
  2116. * can iterate from the start date to the end date via next(). You can check if
  2117. * the end date is reached with the function hasNext(). After each step, you can
  2118. * retrieve the current date via getCurrent().
  2119. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  2120. * days, to years.
  2121. *
  2122. * Version: 1.2
  2123. *
  2124. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  2125. * or new Date(2010, 9, 21, 23, 45, 00)
  2126. * @param {Date} [end] The end date
  2127. * @param {Number} [minimumStep] Optional. Minimum step size in milliseconds
  2128. */
  2129. TimeStep = function(start, end, minimumStep) {
  2130. // variables
  2131. this.current = new Date();
  2132. this._start = new Date();
  2133. this._end = new Date();
  2134. this.autoScale = true;
  2135. this.scale = TimeStep.SCALE.DAY;
  2136. this.step = 1;
  2137. // initialize the range
  2138. this.setRange(start, end, minimumStep);
  2139. };
  2140. /// enum scale
  2141. TimeStep.SCALE = {
  2142. MILLISECOND: 1,
  2143. SECOND: 2,
  2144. MINUTE: 3,
  2145. HOUR: 4,
  2146. DAY: 5,
  2147. WEEKDAY: 6,
  2148. MONTH: 7,
  2149. YEAR: 8
  2150. };
  2151. /**
  2152. * Set a new range
  2153. * If minimumStep is provided, the step size is chosen as close as possible
  2154. * to the minimumStep but larger than minimumStep. If minimumStep is not
  2155. * provided, the scale is set to 1 DAY.
  2156. * The minimumStep should correspond with the onscreen size of about 6 characters
  2157. * @param {Date} [start] The start date and time.
  2158. * @param {Date} [end] The end date and time.
  2159. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  2160. */
  2161. TimeStep.prototype.setRange = function(start, end, minimumStep) {
  2162. if (!(start instanceof Date) || !(end instanceof Date)) {
  2163. //throw "No legal start or end date in method setRange";
  2164. return;
  2165. }
  2166. this._start = (start != undefined) ? new Date(start.valueOf()) : new Date();
  2167. this._end = (end != undefined) ? new Date(end.valueOf()) : new Date();
  2168. if (this.autoScale) {
  2169. this.setMinimumStep(minimumStep);
  2170. }
  2171. };
  2172. /**
  2173. * Set the range iterator to the start date.
  2174. */
  2175. TimeStep.prototype.first = function() {
  2176. this.current = new Date(this._start.valueOf());
  2177. this.roundToMinor();
  2178. };
  2179. /**
  2180. * Round the current date to the first minor date value
  2181. * This must be executed once when the current date is set to start Date
  2182. */
  2183. TimeStep.prototype.roundToMinor = function() {
  2184. // round to floor
  2185. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  2186. //noinspection FallthroughInSwitchStatementJS
  2187. switch (this.scale) {
  2188. case TimeStep.SCALE.YEAR:
  2189. this.current.setFullYear(this.step * Math.floor(this.current.getFullYear() / this.step));
  2190. this.current.setMonth(0);
  2191. case TimeStep.SCALE.MONTH: this.current.setDate(1);
  2192. case TimeStep.SCALE.DAY: // intentional fall through
  2193. case TimeStep.SCALE.WEEKDAY: this.current.setHours(0);
  2194. case TimeStep.SCALE.HOUR: this.current.setMinutes(0);
  2195. case TimeStep.SCALE.MINUTE: this.current.setSeconds(0);
  2196. case TimeStep.SCALE.SECOND: this.current.setMilliseconds(0);
  2197. //case TimeStep.SCALE.MILLISECOND: // nothing to do for milliseconds
  2198. }
  2199. if (this.step != 1) {
  2200. // round down to the first minor value that is a multiple of the current step size
  2201. switch (this.scale) {
  2202. case TimeStep.SCALE.MILLISECOND: this.current.setMilliseconds(this.current.getMilliseconds() - this.current.getMilliseconds() % this.step); break;
  2203. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() - this.current.getSeconds() % this.step); break;
  2204. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() - this.current.getMinutes() % this.step); break;
  2205. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() - this.current.getHours() % this.step); break;
  2206. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2207. case TimeStep.SCALE.DAY: this.current.setDate((this.current.getDate()-1) - (this.current.getDate()-1) % this.step + 1); break;
  2208. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() - this.current.getMonth() % this.step); break;
  2209. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() - this.current.getFullYear() % this.step); break;
  2210. default: break;
  2211. }
  2212. }
  2213. };
  2214. /**
  2215. * Check if the there is a next step
  2216. * @return {boolean} true if the current date has not passed the end date
  2217. */
  2218. TimeStep.prototype.hasNext = function () {
  2219. return (this.current.valueOf() <= this._end.valueOf());
  2220. };
  2221. /**
  2222. * Do the next step
  2223. */
  2224. TimeStep.prototype.next = function() {
  2225. var prev = this.current.valueOf();
  2226. // Two cases, needed to prevent issues with switching daylight savings
  2227. // (end of March and end of October)
  2228. if (this.current.getMonth() < 6) {
  2229. switch (this.scale) {
  2230. case TimeStep.SCALE.MILLISECOND:
  2231. this.current = new Date(this.current.valueOf() + this.step); break;
  2232. case TimeStep.SCALE.SECOND: this.current = new Date(this.current.valueOf() + this.step * 1000); break;
  2233. case TimeStep.SCALE.MINUTE: this.current = new Date(this.current.valueOf() + this.step * 1000 * 60); break;
  2234. case TimeStep.SCALE.HOUR:
  2235. this.current = new Date(this.current.valueOf() + this.step * 1000 * 60 * 60);
  2236. // in case of skipping an hour for daylight savings, adjust the hour again (else you get: 0h 5h 9h ... instead of 0h 4h 8h ...)
  2237. var h = this.current.getHours();
  2238. this.current.setHours(h - (h % this.step));
  2239. break;
  2240. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2241. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2242. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2243. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2244. default: break;
  2245. }
  2246. }
  2247. else {
  2248. switch (this.scale) {
  2249. case TimeStep.SCALE.MILLISECOND: this.current = new Date(this.current.valueOf() + this.step); break;
  2250. case TimeStep.SCALE.SECOND: this.current.setSeconds(this.current.getSeconds() + this.step); break;
  2251. case TimeStep.SCALE.MINUTE: this.current.setMinutes(this.current.getMinutes() + this.step); break;
  2252. case TimeStep.SCALE.HOUR: this.current.setHours(this.current.getHours() + this.step); break;
  2253. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2254. case TimeStep.SCALE.DAY: this.current.setDate(this.current.getDate() + this.step); break;
  2255. case TimeStep.SCALE.MONTH: this.current.setMonth(this.current.getMonth() + this.step); break;
  2256. case TimeStep.SCALE.YEAR: this.current.setFullYear(this.current.getFullYear() + this.step); break;
  2257. default: break;
  2258. }
  2259. }
  2260. if (this.step != 1) {
  2261. // round down to the correct major value
  2262. switch (this.scale) {
  2263. case TimeStep.SCALE.MILLISECOND: if(this.current.getMilliseconds() < this.step) this.current.setMilliseconds(0); break;
  2264. case TimeStep.SCALE.SECOND: if(this.current.getSeconds() < this.step) this.current.setSeconds(0); break;
  2265. case TimeStep.SCALE.MINUTE: if(this.current.getMinutes() < this.step) this.current.setMinutes(0); break;
  2266. case TimeStep.SCALE.HOUR: if(this.current.getHours() < this.step) this.current.setHours(0); break;
  2267. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2268. case TimeStep.SCALE.DAY: if(this.current.getDate() < this.step+1) this.current.setDate(1); break;
  2269. case TimeStep.SCALE.MONTH: if(this.current.getMonth() < this.step) this.current.setMonth(0); break;
  2270. case TimeStep.SCALE.YEAR: break; // nothing to do for year
  2271. default: break;
  2272. }
  2273. }
  2274. // safety mechanism: if current time is still unchanged, move to the end
  2275. if (this.current.valueOf() == prev) {
  2276. this.current = new Date(this._end.valueOf());
  2277. }
  2278. };
  2279. /**
  2280. * Get the current datetime
  2281. * @return {Date} current The current date
  2282. */
  2283. TimeStep.prototype.getCurrent = function() {
  2284. return this.current;
  2285. };
  2286. /**
  2287. * Set a custom scale. Autoscaling will be disabled.
  2288. * For example setScale(SCALE.MINUTES, 5) will result
  2289. * in minor steps of 5 minutes, and major steps of an hour.
  2290. *
  2291. * @param {TimeStep.SCALE} newScale
  2292. * A scale. Choose from SCALE.MILLISECOND,
  2293. * SCALE.SECOND, SCALE.MINUTE, SCALE.HOUR,
  2294. * SCALE.WEEKDAY, SCALE.DAY, SCALE.MONTH,
  2295. * SCALE.YEAR.
  2296. * @param {Number} newStep A step size, by default 1. Choose for
  2297. * example 1, 2, 5, or 10.
  2298. */
  2299. TimeStep.prototype.setScale = function(newScale, newStep) {
  2300. this.scale = newScale;
  2301. if (newStep > 0) {
  2302. this.step = newStep;
  2303. }
  2304. this.autoScale = false;
  2305. };
  2306. /**
  2307. * Enable or disable autoscaling
  2308. * @param {boolean} enable If true, autoascaling is set true
  2309. */
  2310. TimeStep.prototype.setAutoScale = function (enable) {
  2311. this.autoScale = enable;
  2312. };
  2313. /**
  2314. * Automatically determine the scale that bests fits the provided minimum step
  2315. * @param {Number} [minimumStep] The minimum step size in milliseconds
  2316. */
  2317. TimeStep.prototype.setMinimumStep = function(minimumStep) {
  2318. if (minimumStep == undefined) {
  2319. return;
  2320. }
  2321. var stepYear = (1000 * 60 * 60 * 24 * 30 * 12);
  2322. var stepMonth = (1000 * 60 * 60 * 24 * 30);
  2323. var stepDay = (1000 * 60 * 60 * 24);
  2324. var stepHour = (1000 * 60 * 60);
  2325. var stepMinute = (1000 * 60);
  2326. var stepSecond = (1000);
  2327. var stepMillisecond= (1);
  2328. // find the smallest step that is larger than the provided minimumStep
  2329. if (stepYear*1000 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1000;}
  2330. if (stepYear*500 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 500;}
  2331. if (stepYear*100 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 100;}
  2332. if (stepYear*50 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 50;}
  2333. if (stepYear*10 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 10;}
  2334. if (stepYear*5 > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 5;}
  2335. if (stepYear > minimumStep) {this.scale = TimeStep.SCALE.YEAR; this.step = 1;}
  2336. if (stepMonth*3 > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 3;}
  2337. if (stepMonth > minimumStep) {this.scale = TimeStep.SCALE.MONTH; this.step = 1;}
  2338. if (stepDay*5 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 5;}
  2339. if (stepDay*2 > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 2;}
  2340. if (stepDay > minimumStep) {this.scale = TimeStep.SCALE.DAY; this.step = 1;}
  2341. if (stepDay/2 > minimumStep) {this.scale = TimeStep.SCALE.WEEKDAY; this.step = 1;}
  2342. if (stepHour*4 > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 4;}
  2343. if (stepHour > minimumStep) {this.scale = TimeStep.SCALE.HOUR; this.step = 1;}
  2344. if (stepMinute*15 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 15;}
  2345. if (stepMinute*10 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 10;}
  2346. if (stepMinute*5 > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 5;}
  2347. if (stepMinute > minimumStep) {this.scale = TimeStep.SCALE.MINUTE; this.step = 1;}
  2348. if (stepSecond*15 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 15;}
  2349. if (stepSecond*10 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 10;}
  2350. if (stepSecond*5 > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 5;}
  2351. if (stepSecond > minimumStep) {this.scale = TimeStep.SCALE.SECOND; this.step = 1;}
  2352. if (stepMillisecond*200 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 200;}
  2353. if (stepMillisecond*100 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 100;}
  2354. if (stepMillisecond*50 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 50;}
  2355. if (stepMillisecond*10 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 10;}
  2356. if (stepMillisecond*5 > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 5;}
  2357. if (stepMillisecond > minimumStep) {this.scale = TimeStep.SCALE.MILLISECOND; this.step = 1;}
  2358. };
  2359. /**
  2360. * Snap a date to a rounded value. The snap intervals are dependent on the
  2361. * current scale and step.
  2362. * @param {Date} date the date to be snapped
  2363. */
  2364. TimeStep.prototype.snap = function(date) {
  2365. if (this.scale == TimeStep.SCALE.YEAR) {
  2366. var year = date.getFullYear() + Math.round(date.getMonth() / 12);
  2367. date.setFullYear(Math.round(year / this.step) * this.step);
  2368. date.setMonth(0);
  2369. date.setDate(0);
  2370. date.setHours(0);
  2371. date.setMinutes(0);
  2372. date.setSeconds(0);
  2373. date.setMilliseconds(0);
  2374. }
  2375. else if (this.scale == TimeStep.SCALE.MONTH) {
  2376. if (date.getDate() > 15) {
  2377. date.setDate(1);
  2378. date.setMonth(date.getMonth() + 1);
  2379. // important: first set Date to 1, after that change the month.
  2380. }
  2381. else {
  2382. date.setDate(1);
  2383. }
  2384. date.setHours(0);
  2385. date.setMinutes(0);
  2386. date.setSeconds(0);
  2387. date.setMilliseconds(0);
  2388. }
  2389. else if (this.scale == TimeStep.SCALE.DAY ||
  2390. this.scale == TimeStep.SCALE.WEEKDAY) {
  2391. //noinspection FallthroughInSwitchStatementJS
  2392. switch (this.step) {
  2393. case 5:
  2394. case 2:
  2395. date.setHours(Math.round(date.getHours() / 24) * 24); break;
  2396. default:
  2397. date.setHours(Math.round(date.getHours() / 12) * 12); break;
  2398. }
  2399. date.setMinutes(0);
  2400. date.setSeconds(0);
  2401. date.setMilliseconds(0);
  2402. }
  2403. else if (this.scale == TimeStep.SCALE.HOUR) {
  2404. switch (this.step) {
  2405. case 4:
  2406. date.setMinutes(Math.round(date.getMinutes() / 60) * 60); break;
  2407. default:
  2408. date.setMinutes(Math.round(date.getMinutes() / 30) * 30); break;
  2409. }
  2410. date.setSeconds(0);
  2411. date.setMilliseconds(0);
  2412. } else if (this.scale == TimeStep.SCALE.MINUTE) {
  2413. //noinspection FallthroughInSwitchStatementJS
  2414. switch (this.step) {
  2415. case 15:
  2416. case 10:
  2417. date.setMinutes(Math.round(date.getMinutes() / 5) * 5);
  2418. date.setSeconds(0);
  2419. break;
  2420. case 5:
  2421. date.setSeconds(Math.round(date.getSeconds() / 60) * 60); break;
  2422. default:
  2423. date.setSeconds(Math.round(date.getSeconds() / 30) * 30); break;
  2424. }
  2425. date.setMilliseconds(0);
  2426. }
  2427. else if (this.scale == TimeStep.SCALE.SECOND) {
  2428. //noinspection FallthroughInSwitchStatementJS
  2429. switch (this.step) {
  2430. case 15:
  2431. case 10:
  2432. date.setSeconds(Math.round(date.getSeconds() / 5) * 5);
  2433. date.setMilliseconds(0);
  2434. break;
  2435. case 5:
  2436. date.setMilliseconds(Math.round(date.getMilliseconds() / 1000) * 1000); break;
  2437. default:
  2438. date.setMilliseconds(Math.round(date.getMilliseconds() / 500) * 500); break;
  2439. }
  2440. }
  2441. else if (this.scale == TimeStep.SCALE.MILLISECOND) {
  2442. var step = this.step > 5 ? this.step / 2 : 1;
  2443. date.setMilliseconds(Math.round(date.getMilliseconds() / step) * step);
  2444. }
  2445. };
  2446. /**
  2447. * Check if the current value is a major value (for example when the step
  2448. * is DAY, a major value is each first day of the MONTH)
  2449. * @return {boolean} true if current date is major, else false.
  2450. */
  2451. TimeStep.prototype.isMajor = function() {
  2452. switch (this.scale) {
  2453. case TimeStep.SCALE.MILLISECOND:
  2454. return (this.current.getMilliseconds() == 0);
  2455. case TimeStep.SCALE.SECOND:
  2456. return (this.current.getSeconds() == 0);
  2457. case TimeStep.SCALE.MINUTE:
  2458. return (this.current.getHours() == 0) && (this.current.getMinutes() == 0);
  2459. // Note: this is no bug. Major label is equal for both minute and hour scale
  2460. case TimeStep.SCALE.HOUR:
  2461. return (this.current.getHours() == 0);
  2462. case TimeStep.SCALE.WEEKDAY: // intentional fall through
  2463. case TimeStep.SCALE.DAY:
  2464. return (this.current.getDate() == 1);
  2465. case TimeStep.SCALE.MONTH:
  2466. return (this.current.getMonth() == 0);
  2467. case TimeStep.SCALE.YEAR:
  2468. return false;
  2469. default:
  2470. return false;
  2471. }
  2472. };
  2473. /**
  2474. * Returns formatted text for the minor axislabel, depending on the current
  2475. * date and the scale. For example when scale is MINUTE, the current time is
  2476. * formatted as "hh:mm".
  2477. * @param {Date} [date] custom date. if not provided, current date is taken
  2478. */
  2479. TimeStep.prototype.getLabelMinor = function(date) {
  2480. if (date == undefined) {
  2481. date = this.current;
  2482. }
  2483. switch (this.scale) {
  2484. case TimeStep.SCALE.MILLISECOND: return moment(date).format('SSS');
  2485. case TimeStep.SCALE.SECOND: return moment(date).format('s');
  2486. case TimeStep.SCALE.MINUTE: return moment(date).format('HH:mm');
  2487. case TimeStep.SCALE.HOUR: return moment(date).format('HH:mm');
  2488. case TimeStep.SCALE.WEEKDAY: return moment(date).format('ddd D');
  2489. case TimeStep.SCALE.DAY: return moment(date).format('D');
  2490. case TimeStep.SCALE.MONTH: return moment(date).format('MMM');
  2491. case TimeStep.SCALE.YEAR: return moment(date).format('YYYY');
  2492. default: return '';
  2493. }
  2494. };
  2495. /**
  2496. * Returns formatted text for the major axis label, depending on the current
  2497. * date and the scale. For example when scale is MINUTE, the major scale is
  2498. * hours, and the hour will be formatted as "hh".
  2499. * @param {Date} [date] custom date. if not provided, current date is taken
  2500. */
  2501. TimeStep.prototype.getLabelMajor = function(date) {
  2502. if (date == undefined) {
  2503. date = this.current;
  2504. }
  2505. //noinspection FallthroughInSwitchStatementJS
  2506. switch (this.scale) {
  2507. case TimeStep.SCALE.MILLISECOND:return moment(date).format('HH:mm:ss');
  2508. case TimeStep.SCALE.SECOND: return moment(date).format('D MMMM HH:mm');
  2509. case TimeStep.SCALE.MINUTE:
  2510. case TimeStep.SCALE.HOUR: return moment(date).format('ddd D MMMM');
  2511. case TimeStep.SCALE.WEEKDAY:
  2512. case TimeStep.SCALE.DAY: return moment(date).format('MMMM YYYY');
  2513. case TimeStep.SCALE.MONTH: return moment(date).format('YYYY');
  2514. case TimeStep.SCALE.YEAR: return '';
  2515. default: return '';
  2516. }
  2517. };
  2518. /**
  2519. * @constructor Stack
  2520. * Stacks items on top of each other.
  2521. * @param {ItemSet} parent
  2522. * @param {Object} [options]
  2523. */
  2524. function Stack (parent, options) {
  2525. this.parent = parent;
  2526. this.options = options || {};
  2527. this.defaultOptions = {
  2528. order: function (a, b) {
  2529. //return (b.width - a.width) || (a.left - b.left); // TODO: cleanup
  2530. // Order: ranges over non-ranges, ranged ordered by width, and
  2531. // lastly ordered by start.
  2532. if (a instanceof ItemRange) {
  2533. if (b instanceof ItemRange) {
  2534. var aInt = (a.data.end - a.data.start);
  2535. var bInt = (b.data.end - b.data.start);
  2536. return (aInt - bInt) || (a.data.start - b.data.start);
  2537. }
  2538. else {
  2539. return -1;
  2540. }
  2541. }
  2542. else {
  2543. if (b instanceof ItemRange) {
  2544. return 1;
  2545. }
  2546. else {
  2547. return (a.data.start - b.data.start);
  2548. }
  2549. }
  2550. },
  2551. margin: {
  2552. item: 10
  2553. }
  2554. };
  2555. this.ordered = []; // ordered items
  2556. }
  2557. /**
  2558. * Set options for the stack
  2559. * @param {Object} options Available options:
  2560. * {ItemSet} parent
  2561. * {Number} margin
  2562. * {function} order Stacking order
  2563. */
  2564. Stack.prototype.setOptions = function setOptions (options) {
  2565. util.extend(this.options, options);
  2566. // TODO: register on data changes at the connected parent itemset, and update the changed part only and immediately
  2567. };
  2568. /**
  2569. * Stack the items such that they don't overlap. The items will have a minimal
  2570. * distance equal to options.margin.item.
  2571. */
  2572. Stack.prototype.update = function update() {
  2573. this._order();
  2574. this._stack();
  2575. };
  2576. /**
  2577. * Order the items. The items are ordered by width first, and by left position
  2578. * second.
  2579. * If a custom order function has been provided via the options, then this will
  2580. * be used.
  2581. * @private
  2582. */
  2583. Stack.prototype._order = function _order () {
  2584. var items = this.parent.items;
  2585. if (!items) {
  2586. throw new Error('Cannot stack items: parent does not contain items');
  2587. }
  2588. // TODO: store the sorted items, to have less work later on
  2589. var ordered = [];
  2590. var index = 0;
  2591. // items is a map (no array)
  2592. util.forEach(items, function (item) {
  2593. if (item.visible) {
  2594. ordered[index] = item;
  2595. index++;
  2596. }
  2597. });
  2598. //if a customer stack order function exists, use it.
  2599. var order = this.options.order || this.defaultOptions.order;
  2600. if (!(typeof order === 'function')) {
  2601. throw new Error('Option order must be a function');
  2602. }
  2603. ordered.sort(order);
  2604. this.ordered = ordered;
  2605. };
  2606. /**
  2607. * Adjust vertical positions of the events such that they don't overlap each
  2608. * other.
  2609. * @private
  2610. */
  2611. Stack.prototype._stack = function _stack () {
  2612. var i,
  2613. iMax,
  2614. ordered = this.ordered,
  2615. options = this.options,
  2616. orientation = options.orientation || this.defaultOptions.orientation,
  2617. axisOnTop = (orientation == 'top'),
  2618. margin;
  2619. if (options.margin && options.margin.item !== undefined) {
  2620. margin = options.margin.item;
  2621. }
  2622. else {
  2623. margin = this.defaultOptions.margin.item
  2624. }
  2625. // calculate new, non-overlapping positions
  2626. for (i = 0, iMax = ordered.length; i < iMax; i++) {
  2627. var item = ordered[i];
  2628. var collidingItem = null;
  2629. do {
  2630. // TODO: optimize checking for overlap. when there is a gap without items,
  2631. // you only need to check for items from the next item on, not from zero
  2632. collidingItem = this.checkOverlap(ordered, i, 0, i - 1, margin);
  2633. if (collidingItem != null) {
  2634. // There is a collision. Reposition the event above the colliding element
  2635. if (axisOnTop) {
  2636. item.top = collidingItem.top + collidingItem.height + margin;
  2637. }
  2638. else {
  2639. item.top = collidingItem.top - item.height - margin;
  2640. }
  2641. }
  2642. } while (collidingItem);
  2643. }
  2644. };
  2645. /**
  2646. * Check if the destiny position of given item overlaps with any
  2647. * of the other items from index itemStart to itemEnd.
  2648. * @param {Array} items Array with items
  2649. * @param {int} itemIndex Number of the item to be checked for overlap
  2650. * @param {int} itemStart First item to be checked.
  2651. * @param {int} itemEnd Last item to be checked.
  2652. * @return {Object | null} colliding item, or undefined when no collisions
  2653. * @param {Number} margin A minimum required margin.
  2654. * If margin is provided, the two items will be
  2655. * marked colliding when they overlap or
  2656. * when the margin between the two is smaller than
  2657. * the requested margin.
  2658. */
  2659. Stack.prototype.checkOverlap = function checkOverlap (items, itemIndex,
  2660. itemStart, itemEnd, margin) {
  2661. var collision = this.collision;
  2662. // we loop from end to start, as we suppose that the chance of a
  2663. // collision is larger for items at the end, so check these first.
  2664. var a = items[itemIndex];
  2665. for (var i = itemEnd; i >= itemStart; i--) {
  2666. var b = items[i];
  2667. if (collision(a, b, margin)) {
  2668. if (i != itemIndex) {
  2669. return b;
  2670. }
  2671. }
  2672. }
  2673. return null;
  2674. };
  2675. /**
  2676. * Test if the two provided items collide
  2677. * The items must have parameters left, width, top, and height.
  2678. * @param {Component} a The first item
  2679. * @param {Component} b The second item
  2680. * @param {Number} margin A minimum required margin.
  2681. * If margin is provided, the two items will be
  2682. * marked colliding when they overlap or
  2683. * when the margin between the two is smaller than
  2684. * the requested margin.
  2685. * @return {boolean} true if a and b collide, else false
  2686. */
  2687. Stack.prototype.collision = function collision (a, b, margin) {
  2688. var a_width;
  2689. var b_width;
  2690. if (a.props.content !== undefined && a.width < a.props.content.width)
  2691. a_width = a.props.content.width;
  2692. else
  2693. a_width = a.width;
  2694. if (b.props.content !== undefined && b.width < b.props.content.width)
  2695. b_width = b.props.content.width;
  2696. else
  2697. b_width = b.width
  2698. return ((a.left - margin) < (b.left + b_width) &&
  2699. (a.left + a_width + margin) > b.left &&
  2700. (a.top - margin) < (b.top + b.height) &&
  2701. (a.top + a.height + margin) > b.top);
  2702. };
  2703. /**
  2704. * @constructor Range
  2705. * A Range controls a numeric range with a start and end value.
  2706. * The Range adjusts the range based on mouse events or programmatic changes,
  2707. * and triggers events when the range is changing or has been changed.
  2708. * @param {Object} [options] See description at Range.setOptions
  2709. * @extends Controller
  2710. */
  2711. function Range(options) {
  2712. this.id = util.randomUUID();
  2713. this.start = 0; // Number
  2714. this.end = 0; // Number
  2715. this.options = {
  2716. min: null,
  2717. max: null,
  2718. zoomMin: null,
  2719. zoomMax: null
  2720. };
  2721. this.listeners = [];
  2722. this.setOptions(options);
  2723. }
  2724. /**
  2725. * Set options for the range controller
  2726. * @param {Object} options Available options:
  2727. * {Number} start Set start value of the range
  2728. * {Number} end Set end value of the range
  2729. * {Number} min Minimum value for start
  2730. * {Number} max Maximum value for end
  2731. * {Number} zoomMin Set a minimum value for
  2732. * (end - start).
  2733. * {Number} zoomMax Set a maximum value for
  2734. * (end - start).
  2735. */
  2736. Range.prototype.setOptions = function (options) {
  2737. util.extend(this.options, options);
  2738. if (options.start != null || options.end != null) {
  2739. this.setRange(options.start, options.end);
  2740. }
  2741. };
  2742. /**
  2743. * Add listeners for mouse and touch events to the component
  2744. * @param {Component} component
  2745. * @param {String} event Available events: 'move', 'zoom'
  2746. * @param {String} direction Available directions: 'horizontal', 'vertical'
  2747. */
  2748. Range.prototype.subscribe = function (component, event, direction) {
  2749. var me = this;
  2750. var listener;
  2751. if (direction != 'horizontal' && direction != 'vertical') {
  2752. throw new TypeError('Unknown direction "' + direction + '". ' +
  2753. 'Choose "horizontal" or "vertical".');
  2754. }
  2755. //noinspection FallthroughInSwitchStatementJS
  2756. if (event == 'move') {
  2757. listener = {
  2758. component: component,
  2759. event: event,
  2760. direction: direction,
  2761. callback: function (event) {
  2762. me._onMouseDown(event, listener);
  2763. },
  2764. params: {}
  2765. };
  2766. component.on('mousedown', listener.callback);
  2767. me.listeners.push(listener);
  2768. }
  2769. else if (event == 'zoom') {
  2770. listener = {
  2771. component: component,
  2772. event: event,
  2773. direction: direction,
  2774. callback: function (event) {
  2775. me._onMouseWheel(event, listener);
  2776. },
  2777. params: {}
  2778. };
  2779. component.on('mousewheel', listener.callback);
  2780. me.listeners.push(listener);
  2781. }
  2782. else {
  2783. throw new TypeError('Unknown event "' + event + '". ' +
  2784. 'Choose "move" or "zoom".');
  2785. }
  2786. };
  2787. /**
  2788. * Event handler
  2789. * @param {String} event name of the event, for example 'click', 'mousemove'
  2790. * @param {function} callback callback handler, invoked with the raw HTML Event
  2791. * as parameter.
  2792. */
  2793. Range.prototype.on = function (event, callback) {
  2794. events.addListener(this, event, callback);
  2795. };
  2796. /**
  2797. * Trigger an event
  2798. * @param {String} event name of the event, available events: 'rangechange',
  2799. * 'rangechanged'
  2800. * @private
  2801. */
  2802. Range.prototype._trigger = function (event) {
  2803. events.trigger(this, event, {
  2804. start: this.start,
  2805. end: this.end
  2806. });
  2807. };
  2808. /**
  2809. * Set a new start and end range
  2810. * @param {Number} start
  2811. * @param {Number} end
  2812. */
  2813. Range.prototype.setRange = function(start, end) {
  2814. var changed = this._applyRange(start, end);
  2815. if (changed) {
  2816. this._trigger('rangechange');
  2817. this._trigger('rangechanged');
  2818. }
  2819. };
  2820. /**
  2821. * Set a new start and end range. This method is the same as setRange, but
  2822. * does not trigger a range change and range changed event, and it returns
  2823. * true when the range is changed
  2824. * @param {Number} start
  2825. * @param {Number} end
  2826. * @return {Boolean} changed
  2827. * @private
  2828. */
  2829. Range.prototype._applyRange = function(start, end) {
  2830. var newStart = (start != null) ? util.convert(start, 'Number') : this.start;
  2831. var newEnd = (end != null) ? util.convert(end, 'Number') : this.end;
  2832. var diff;
  2833. // check for valid number
  2834. if (isNaN(newStart)) {
  2835. throw new Error('Invalid start "' + start + '"');
  2836. }
  2837. if (isNaN(newEnd)) {
  2838. throw new Error('Invalid end "' + end + '"');
  2839. }
  2840. // prevent start < end
  2841. if (newEnd < newStart) {
  2842. newEnd = newStart;
  2843. }
  2844. // prevent start < min
  2845. if (this.options.min != null) {
  2846. var min = this.options.min.valueOf();
  2847. if (newStart < min) {
  2848. diff = (min - newStart);
  2849. newStart += diff;
  2850. newEnd += diff;
  2851. }
  2852. }
  2853. // prevent end > max
  2854. if (this.options.max != null) {
  2855. var max = this.options.max.valueOf();
  2856. if (newEnd > max) {
  2857. diff = (newEnd - max);
  2858. newStart -= diff;
  2859. newEnd -= diff;
  2860. }
  2861. }
  2862. // prevent (end-start) > zoomMin
  2863. if (this.options.zoomMin != null) {
  2864. var zoomMin = this.options.zoomMin.valueOf();
  2865. if (zoomMin < 0) {
  2866. zoomMin = 0;
  2867. }
  2868. if ((newEnd - newStart) < zoomMin) {
  2869. if ((this.end - this.start) > zoomMin) {
  2870. // zoom to the minimum
  2871. diff = (zoomMin - (newEnd - newStart));
  2872. newStart -= diff / 2;
  2873. newEnd += diff / 2;
  2874. }
  2875. else {
  2876. // ingore this action, we are already zoomed to the minimum
  2877. newStart = this.start;
  2878. newEnd = this.end;
  2879. }
  2880. }
  2881. }
  2882. // prevent (end-start) > zoomMin
  2883. if (this.options.zoomMax != null) {
  2884. var zoomMax = this.options.zoomMax.valueOf();
  2885. if (zoomMax < 0) {
  2886. zoomMax = 0;
  2887. }
  2888. if ((newEnd - newStart) > zoomMax) {
  2889. if ((this.end - this.start) < zoomMax) {
  2890. // zoom to the maximum
  2891. diff = ((newEnd - newStart) - zoomMax);
  2892. newStart += diff / 2;
  2893. newEnd -= diff / 2;
  2894. }
  2895. else {
  2896. // ingore this action, we are already zoomed to the maximum
  2897. newStart = this.start;
  2898. newEnd = this.end;
  2899. }
  2900. }
  2901. }
  2902. var changed = (this.start != newStart || this.end != newEnd);
  2903. this.start = newStart;
  2904. this.end = newEnd;
  2905. return changed;
  2906. };
  2907. /**
  2908. * Retrieve the current range.
  2909. * @return {Object} An object with start and end properties
  2910. */
  2911. Range.prototype.getRange = function() {
  2912. return {
  2913. start: this.start,
  2914. end: this.end
  2915. };
  2916. };
  2917. /**
  2918. * Calculate the conversion offset and factor for current range, based on
  2919. * the provided width
  2920. * @param {Number} width
  2921. * @returns {{offset: number, factor: number}} conversion
  2922. */
  2923. Range.prototype.conversion = function (width) {
  2924. var start = this.start;
  2925. var end = this.end;
  2926. return Range.conversion(this.start, this.end, width);
  2927. };
  2928. /**
  2929. * Static method to calculate the conversion offset and factor for a range,
  2930. * based on the provided start, end, and width
  2931. * @param {Number} start
  2932. * @param {Number} end
  2933. * @param {Number} width
  2934. * @returns {{offset: number, factor: number}} conversion
  2935. */
  2936. Range.conversion = function (start, end, width) {
  2937. if (width != 0 && (end - start != 0)) {
  2938. return {
  2939. offset: start,
  2940. factor: width / (end - start)
  2941. }
  2942. }
  2943. else {
  2944. return {
  2945. offset: 0,
  2946. factor: 1
  2947. };
  2948. }
  2949. };
  2950. /**
  2951. * Start moving horizontally or vertically
  2952. * @param {Event} event
  2953. * @param {Object} listener Listener containing the component and params
  2954. * @private
  2955. */
  2956. Range.prototype._onMouseDown = function(event, listener) {
  2957. event = event || window.event;
  2958. var params = listener.params;
  2959. // only react on left mouse button down
  2960. var leftButtonDown = event.which ? (event.which == 1) : (event.button == 1);
  2961. if (!leftButtonDown) {
  2962. return;
  2963. }
  2964. // get mouse position
  2965. params.mouseX = util.getPageX(event);
  2966. params.mouseY = util.getPageY(event);
  2967. params.previousLeft = 0;
  2968. params.previousOffset = 0;
  2969. params.moved = false;
  2970. params.start = this.start;
  2971. params.end = this.end;
  2972. var frame = listener.component.frame;
  2973. if (frame) {
  2974. frame.style.cursor = 'move';
  2975. }
  2976. // add event listeners to handle moving the contents
  2977. // we store the function onmousemove and onmouseup in the timeaxis,
  2978. // so we can remove the eventlisteners lateron in the function onmouseup
  2979. var me = this;
  2980. if (!params.onMouseMove) {
  2981. params.onMouseMove = function (event) {
  2982. me._onMouseMove(event, listener);
  2983. };
  2984. util.addEventListener(document, "mousemove", params.onMouseMove);
  2985. }
  2986. if (!params.onMouseUp) {
  2987. params.onMouseUp = function (event) {
  2988. me._onMouseUp(event, listener);
  2989. };
  2990. util.addEventListener(document, "mouseup", params.onMouseUp);
  2991. }
  2992. util.preventDefault(event);
  2993. };
  2994. /**
  2995. * Perform moving operating.
  2996. * This function activated from within the funcion TimeAxis._onMouseDown().
  2997. * @param {Event} event
  2998. * @param {Object} listener
  2999. * @private
  3000. */
  3001. Range.prototype._onMouseMove = function (event, listener) {
  3002. event = event || window.event;
  3003. var params = listener.params;
  3004. // calculate change in mouse position
  3005. var mouseX = util.getPageX(event);
  3006. var mouseY = util.getPageY(event);
  3007. if (params.mouseX == undefined) {
  3008. params.mouseX = mouseX;
  3009. }
  3010. if (params.mouseY == undefined) {
  3011. params.mouseY = mouseY;
  3012. }
  3013. var diffX = mouseX - params.mouseX;
  3014. var diffY = mouseY - params.mouseY;
  3015. var diff = (listener.direction == 'horizontal') ? diffX : diffY;
  3016. // if mouse movement is big enough, register it as a "moved" event
  3017. if (Math.abs(diff) >= 1) {
  3018. params.moved = true;
  3019. }
  3020. var interval = (params.end - params.start);
  3021. var width = (listener.direction == 'horizontal') ?
  3022. listener.component.width : listener.component.height;
  3023. var diffRange = -diff / width * interval;
  3024. this._applyRange(params.start + diffRange, params.end + diffRange);
  3025. // fire a rangechange event
  3026. this._trigger('rangechange');
  3027. util.preventDefault(event);
  3028. };
  3029. /**
  3030. * Stop moving operating.
  3031. * This function activated from within the function Range._onMouseDown().
  3032. * @param {event} event
  3033. * @param {Object} listener
  3034. * @private
  3035. */
  3036. Range.prototype._onMouseUp = function (event, listener) {
  3037. event = event || window.event;
  3038. var params = listener.params;
  3039. if (listener.component.frame) {
  3040. listener.component.frame.style.cursor = 'auto';
  3041. }
  3042. // remove event listeners here, important for Safari
  3043. if (params.onMouseMove) {
  3044. util.removeEventListener(document, "mousemove", params.onMouseMove);
  3045. params.onMouseMove = null;
  3046. }
  3047. if (params.onMouseUp) {
  3048. util.removeEventListener(document, "mouseup", params.onMouseUp);
  3049. params.onMouseUp = null;
  3050. }
  3051. //util.preventDefault(event);
  3052. if (params.moved) {
  3053. // fire a rangechanged event
  3054. this._trigger('rangechanged');
  3055. }
  3056. };
  3057. /**
  3058. * Event handler for mouse wheel event, used to zoom
  3059. * Code from http://adomas.org/javascript-mouse-wheel/
  3060. * @param {Event} event
  3061. * @param {Object} listener
  3062. * @private
  3063. */
  3064. Range.prototype._onMouseWheel = function(event, listener) {
  3065. event = event || window.event;
  3066. // retrieve delta
  3067. var delta = 0;
  3068. if (event.wheelDelta) { /* IE/Opera. */
  3069. delta = event.wheelDelta / 120;
  3070. } else if (event.detail) { /* Mozilla case. */
  3071. // In Mozilla, sign of delta is different than in IE.
  3072. // Also, delta is multiple of 3.
  3073. delta = -event.detail / 3;
  3074. }
  3075. // If delta is nonzero, handle it.
  3076. // Basically, delta is now positive if wheel was scrolled up,
  3077. // and negative, if wheel was scrolled down.
  3078. if (delta) {
  3079. var me = this;
  3080. var zoom = function () {
  3081. // perform the zoom action. Delta is normally 1 or -1
  3082. var zoomFactor = delta / 5.0;
  3083. var zoomAround = null;
  3084. var frame = listener.component.frame;
  3085. if (frame) {
  3086. var size, conversion;
  3087. if (listener.direction == 'horizontal') {
  3088. size = listener.component.width;
  3089. conversion = me.conversion(size);
  3090. var frameLeft = util.getAbsoluteLeft(frame);
  3091. var mouseX = util.getPageX(event);
  3092. zoomAround = (mouseX - frameLeft) / conversion.factor + conversion.offset;
  3093. }
  3094. else {
  3095. size = listener.component.height;
  3096. conversion = me.conversion(size);
  3097. var frameTop = util.getAbsoluteTop(frame);
  3098. var mouseY = util.getPageY(event);
  3099. zoomAround = ((frameTop + size - mouseY) - frameTop) / conversion.factor + conversion.offset;
  3100. }
  3101. }
  3102. me.zoom(zoomFactor, zoomAround);
  3103. };
  3104. zoom();
  3105. }
  3106. // Prevent default actions caused by mouse wheel.
  3107. // That might be ugly, but we handle scrolls somehow
  3108. // anyway, so don't bother here...
  3109. util.preventDefault(event);
  3110. };
  3111. /**
  3112. * Zoom the range the given zoomfactor in or out. Start and end date will
  3113. * be adjusted, and the timeline will be redrawn. You can optionally give a
  3114. * date around which to zoom.
  3115. * For example, try zoomfactor = 0.1 or -0.1
  3116. * @param {Number} zoomFactor Zooming amount. Positive value will zoom in,
  3117. * negative value will zoom out
  3118. * @param {Number} zoomAround Value around which will be zoomed. Optional
  3119. */
  3120. Range.prototype.zoom = function(zoomFactor, zoomAround) {
  3121. // if zoomAroundDate is not provided, take it half between start Date and end Date
  3122. if (zoomAround == null) {
  3123. zoomAround = (this.start + this.end) / 2;
  3124. }
  3125. // prevent zoom factor larger than 1 or smaller than -1 (larger than 1 will
  3126. // result in a start>=end )
  3127. if (zoomFactor >= 1) {
  3128. zoomFactor = 0.9;
  3129. }
  3130. if (zoomFactor <= -1) {
  3131. zoomFactor = -0.9;
  3132. }
  3133. // adjust a negative factor such that zooming in with 0.1 equals zooming
  3134. // out with a factor -0.1
  3135. if (zoomFactor < 0) {
  3136. zoomFactor = zoomFactor / (1 + zoomFactor);
  3137. }
  3138. // zoom start and end relative to the zoomAround value
  3139. var startDiff = (this.start - zoomAround);
  3140. var endDiff = (this.end - zoomAround);
  3141. // calculate new start and end
  3142. var newStart = this.start - startDiff * zoomFactor;
  3143. var newEnd = this.end - endDiff * zoomFactor;
  3144. this.setRange(newStart, newEnd);
  3145. };
  3146. /**
  3147. * Move the range with a given factor to the left or right. Start and end
  3148. * value will be adjusted. For example, try moveFactor = 0.1 or -0.1
  3149. * @param {Number} moveFactor Moving amount. Positive value will move right,
  3150. * negative value will move left
  3151. */
  3152. Range.prototype.move = function(moveFactor) {
  3153. // zoom start Date and end Date relative to the zoomAroundDate
  3154. var diff = (this.end - this.start);
  3155. // apply new values
  3156. var newStart = this.start + diff * moveFactor;
  3157. var newEnd = this.end + diff * moveFactor;
  3158. // TODO: reckon with min and max range
  3159. this.start = newStart;
  3160. this.end = newEnd;
  3161. };
  3162. /**
  3163. * @constructor Controller
  3164. *
  3165. * A Controller controls the reflows and repaints of all visual components
  3166. */
  3167. function Controller () {
  3168. this.id = util.randomUUID();
  3169. this.components = {};
  3170. this.repaintTimer = undefined;
  3171. this.reflowTimer = undefined;
  3172. }
  3173. /**
  3174. * Add a component to the controller
  3175. * @param {Component} component
  3176. */
  3177. Controller.prototype.add = function add(component) {
  3178. // validate the component
  3179. if (component.id == undefined) {
  3180. throw new Error('Component has no field id');
  3181. }
  3182. if (!(component instanceof Component) && !(component instanceof Controller)) {
  3183. throw new TypeError('Component must be an instance of ' +
  3184. 'prototype Component or Controller');
  3185. }
  3186. // add the component
  3187. component.controller = this;
  3188. this.components[component.id] = component;
  3189. };
  3190. /**
  3191. * Remove a component from the controller
  3192. * @param {Component | String} component
  3193. */
  3194. Controller.prototype.remove = function remove(component) {
  3195. var id;
  3196. for (id in this.components) {
  3197. if (this.components.hasOwnProperty(id)) {
  3198. if (id == component || this.components[id] == component) {
  3199. break;
  3200. }
  3201. }
  3202. }
  3203. if (id) {
  3204. delete this.components[id];
  3205. }
  3206. };
  3207. /**
  3208. * Request a reflow. The controller will schedule a reflow
  3209. * @param {Boolean} [force] If true, an immediate reflow is forced. Default
  3210. * is false.
  3211. */
  3212. Controller.prototype.requestReflow = function requestReflow(force) {
  3213. if (force) {
  3214. this.reflow();
  3215. }
  3216. else {
  3217. if (!this.reflowTimer) {
  3218. var me = this;
  3219. this.reflowTimer = setTimeout(function () {
  3220. me.reflowTimer = undefined;
  3221. me.reflow();
  3222. }, 0);
  3223. }
  3224. }
  3225. };
  3226. /**
  3227. * Request a repaint. The controller will schedule a repaint
  3228. * @param {Boolean} [force] If true, an immediate repaint is forced. Default
  3229. * is false.
  3230. */
  3231. Controller.prototype.requestRepaint = function requestRepaint(force) {
  3232. if (force) {
  3233. this.repaint();
  3234. }
  3235. else {
  3236. if (!this.repaintTimer) {
  3237. var me = this;
  3238. this.repaintTimer = setTimeout(function () {
  3239. me.repaintTimer = undefined;
  3240. me.repaint();
  3241. }, 0);
  3242. }
  3243. }
  3244. };
  3245. /**
  3246. * Repaint all components
  3247. */
  3248. Controller.prototype.repaint = function repaint() {
  3249. var changed = false;
  3250. // cancel any running repaint request
  3251. if (this.repaintTimer) {
  3252. clearTimeout(this.repaintTimer);
  3253. this.repaintTimer = undefined;
  3254. }
  3255. var done = {};
  3256. function repaint(component, id) {
  3257. if (!(id in done)) {
  3258. // first repaint the components on which this component is dependent
  3259. if (component.depends) {
  3260. component.depends.forEach(function (dep) {
  3261. repaint(dep, dep.id);
  3262. });
  3263. }
  3264. if (component.parent) {
  3265. repaint(component.parent, component.parent.id);
  3266. }
  3267. // repaint the component itself and mark as done
  3268. changed = component.repaint() || changed;
  3269. done[id] = true;
  3270. }
  3271. }
  3272. util.forEach(this.components, repaint);
  3273. // immediately reflow when needed
  3274. if (changed) {
  3275. this.reflow();
  3276. }
  3277. // TODO: limit the number of nested reflows/repaints, prevent loop
  3278. };
  3279. /**
  3280. * Reflow all components
  3281. */
  3282. Controller.prototype.reflow = function reflow() {
  3283. var resized = false;
  3284. // cancel any running repaint request
  3285. if (this.reflowTimer) {
  3286. clearTimeout(this.reflowTimer);
  3287. this.reflowTimer = undefined;
  3288. }
  3289. var done = {};
  3290. function reflow(component, id) {
  3291. if (!(id in done)) {
  3292. // first reflow the components on which this component is dependent
  3293. if (component.depends) {
  3294. component.depends.forEach(function (dep) {
  3295. reflow(dep, dep.id);
  3296. });
  3297. }
  3298. if (component.parent) {
  3299. reflow(component.parent, component.parent.id);
  3300. }
  3301. // reflow the component itself and mark as done
  3302. resized = component.reflow() || resized;
  3303. done[id] = true;
  3304. }
  3305. }
  3306. util.forEach(this.components, reflow);
  3307. // immediately repaint when needed
  3308. if (resized) {
  3309. this.repaint();
  3310. }
  3311. // TODO: limit the number of nested reflows/repaints, prevent loop
  3312. };
  3313. /**
  3314. * Prototype for visual components
  3315. */
  3316. function Component () {
  3317. this.id = null;
  3318. this.parent = null;
  3319. this.depends = null;
  3320. this.controller = null;
  3321. this.options = null;
  3322. this.frame = null; // main DOM element
  3323. this.top = 0;
  3324. this.left = 0;
  3325. this.width = 0;
  3326. this.height = 0;
  3327. }
  3328. /**
  3329. * Set parameters for the frame. Parameters will be merged in current parameter
  3330. * set.
  3331. * @param {Object} options Available parameters:
  3332. * {String | function} [className]
  3333. * {EventBus} [eventBus]
  3334. * {String | Number | function} [left]
  3335. * {String | Number | function} [top]
  3336. * {String | Number | function} [width]
  3337. * {String | Number | function} [height]
  3338. */
  3339. Component.prototype.setOptions = function setOptions(options) {
  3340. if (options) {
  3341. util.extend(this.options, options);
  3342. if (this.controller) {
  3343. this.requestRepaint();
  3344. this.requestReflow();
  3345. }
  3346. }
  3347. };
  3348. /**
  3349. * Get an option value by name
  3350. * The function will first check this.options object, and else will check
  3351. * this.defaultOptions.
  3352. * @param {String} name
  3353. * @return {*} value
  3354. */
  3355. Component.prototype.getOption = function getOption(name) {
  3356. var value;
  3357. if (this.options) {
  3358. value = this.options[name];
  3359. }
  3360. if (value === undefined && this.defaultOptions) {
  3361. value = this.defaultOptions[name];
  3362. }
  3363. return value;
  3364. };
  3365. /**
  3366. * Get the container element of the component, which can be used by a child to
  3367. * add its own widgets. Not all components do have a container for childs, in
  3368. * that case null is returned.
  3369. * @returns {HTMLElement | null} container
  3370. */
  3371. // TODO: get rid of the getContainer and getFrame methods, provide these via the options
  3372. Component.prototype.getContainer = function getContainer() {
  3373. // should be implemented by the component
  3374. return null;
  3375. };
  3376. /**
  3377. * Get the frame element of the component, the outer HTML DOM element.
  3378. * @returns {HTMLElement | null} frame
  3379. */
  3380. Component.prototype.getFrame = function getFrame() {
  3381. return this.frame;
  3382. };
  3383. /**
  3384. * Repaint the component
  3385. * @return {Boolean} changed
  3386. */
  3387. Component.prototype.repaint = function repaint() {
  3388. // should be implemented by the component
  3389. return false;
  3390. };
  3391. /**
  3392. * Reflow the component
  3393. * @return {Boolean} resized
  3394. */
  3395. Component.prototype.reflow = function reflow() {
  3396. // should be implemented by the component
  3397. return false;
  3398. };
  3399. /**
  3400. * Hide the component from the DOM
  3401. * @return {Boolean} changed
  3402. */
  3403. Component.prototype.hide = function hide() {
  3404. if (this.frame && this.frame.parentNode) {
  3405. this.frame.parentNode.removeChild(this.frame);
  3406. return true;
  3407. }
  3408. else {
  3409. return false;
  3410. }
  3411. };
  3412. /**
  3413. * Show the component in the DOM (when not already visible).
  3414. * A repaint will be executed when the component is not visible
  3415. * @return {Boolean} changed
  3416. */
  3417. Component.prototype.show = function show() {
  3418. if (!this.frame || !this.frame.parentNode) {
  3419. return this.repaint();
  3420. }
  3421. else {
  3422. return false;
  3423. }
  3424. };
  3425. /**
  3426. * Request a repaint. The controller will schedule a repaint
  3427. */
  3428. Component.prototype.requestRepaint = function requestRepaint() {
  3429. if (this.controller) {
  3430. this.controller.requestRepaint();
  3431. }
  3432. else {
  3433. throw new Error('Cannot request a repaint: no controller configured');
  3434. // TODO: just do a repaint when no parent is configured?
  3435. }
  3436. };
  3437. /**
  3438. * Request a reflow. The controller will schedule a reflow
  3439. */
  3440. Component.prototype.requestReflow = function requestReflow() {
  3441. if (this.controller) {
  3442. this.controller.requestReflow();
  3443. }
  3444. else {
  3445. throw new Error('Cannot request a reflow: no controller configured');
  3446. // TODO: just do a reflow when no parent is configured?
  3447. }
  3448. };
  3449. /**
  3450. * A panel can contain components
  3451. * @param {Component} [parent]
  3452. * @param {Component[]} [depends] Components on which this components depends
  3453. * (except for the parent)
  3454. * @param {Object} [options] Available parameters:
  3455. * {String | Number | function} [left]
  3456. * {String | Number | function} [top]
  3457. * {String | Number | function} [width]
  3458. * {String | Number | function} [height]
  3459. * {String | function} [className]
  3460. * @constructor Panel
  3461. * @extends Component
  3462. */
  3463. function Panel(parent, depends, options) {
  3464. this.id = util.randomUUID();
  3465. this.parent = parent;
  3466. this.depends = depends;
  3467. this.options = options || {};
  3468. }
  3469. Panel.prototype = new Component();
  3470. /**
  3471. * Set options. Will extend the current options.
  3472. * @param {Object} [options] Available parameters:
  3473. * {String | function} [className]
  3474. * {String | Number | function} [left]
  3475. * {String | Number | function} [top]
  3476. * {String | Number | function} [width]
  3477. * {String | Number | function} [height]
  3478. */
  3479. Panel.prototype.setOptions = Component.prototype.setOptions;
  3480. /**
  3481. * Get the container element of the panel, which can be used by a child to
  3482. * add its own widgets.
  3483. * @returns {HTMLElement} container
  3484. */
  3485. Panel.prototype.getContainer = function () {
  3486. return this.frame;
  3487. };
  3488. /**
  3489. * Repaint the component
  3490. * @return {Boolean} changed
  3491. */
  3492. Panel.prototype.repaint = function () {
  3493. var changed = 0,
  3494. update = util.updateProperty,
  3495. asSize = util.option.asSize,
  3496. options = this.options,
  3497. frame = this.frame;
  3498. if (!frame) {
  3499. frame = document.createElement('div');
  3500. frame.className = 'panel';
  3501. var className = options.className;
  3502. if (className) {
  3503. if (typeof className == 'function') {
  3504. util.addClassName(frame, String(className()));
  3505. }
  3506. else {
  3507. util.addClassName(frame, String(className));
  3508. }
  3509. }
  3510. this.frame = frame;
  3511. changed += 1;
  3512. }
  3513. if (!frame.parentNode) {
  3514. if (!this.parent) {
  3515. throw new Error('Cannot repaint panel: no parent attached');
  3516. }
  3517. var parentContainer = this.parent.getContainer();
  3518. if (!parentContainer) {
  3519. throw new Error('Cannot repaint panel: parent has no container element');
  3520. }
  3521. parentContainer.appendChild(frame);
  3522. changed += 1;
  3523. }
  3524. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3525. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3526. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3527. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3528. return (changed > 0);
  3529. };
  3530. /**
  3531. * Reflow the component
  3532. * @return {Boolean} resized
  3533. */
  3534. Panel.prototype.reflow = function () {
  3535. var changed = 0,
  3536. update = util.updateProperty,
  3537. frame = this.frame;
  3538. if (frame) {
  3539. changed += update(this, 'top', frame.offsetTop);
  3540. changed += update(this, 'left', frame.offsetLeft);
  3541. changed += update(this, 'width', frame.offsetWidth);
  3542. changed += update(this, 'height', frame.offsetHeight);
  3543. }
  3544. else {
  3545. changed += 1;
  3546. }
  3547. return (changed > 0);
  3548. };
  3549. /**
  3550. * A root panel can hold components. The root panel must be initialized with
  3551. * a DOM element as container.
  3552. * @param {HTMLElement} container
  3553. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  3554. * @constructor RootPanel
  3555. * @extends Panel
  3556. */
  3557. function RootPanel(container, options) {
  3558. this.id = util.randomUUID();
  3559. this.container = container;
  3560. this.options = options || {};
  3561. this.defaultOptions = {
  3562. autoResize: true
  3563. };
  3564. this.listeners = {}; // event listeners
  3565. }
  3566. RootPanel.prototype = new Panel();
  3567. /**
  3568. * Set options. Will extend the current options.
  3569. * @param {Object} [options] Available parameters:
  3570. * {String | function} [className]
  3571. * {String | Number | function} [left]
  3572. * {String | Number | function} [top]
  3573. * {String | Number | function} [width]
  3574. * {String | Number | function} [height]
  3575. * {Boolean | function} [autoResize]
  3576. */
  3577. RootPanel.prototype.setOptions = Component.prototype.setOptions;
  3578. /**
  3579. * Repaint the component
  3580. * @return {Boolean} changed
  3581. */
  3582. RootPanel.prototype.repaint = function () {
  3583. var changed = 0,
  3584. update = util.updateProperty,
  3585. asSize = util.option.asSize,
  3586. options = this.options,
  3587. frame = this.frame;
  3588. if (!frame) {
  3589. frame = document.createElement('div');
  3590. frame.className = 'vis timeline rootpanel';
  3591. var className = options.className;
  3592. if (className) {
  3593. util.addClassName(frame, util.option.asString(className));
  3594. }
  3595. this.frame = frame;
  3596. changed += 1;
  3597. }
  3598. if (!frame.parentNode) {
  3599. if (!this.container) {
  3600. throw new Error('Cannot repaint root panel: no container attached');
  3601. }
  3602. this.container.appendChild(frame);
  3603. changed += 1;
  3604. }
  3605. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3606. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3607. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3608. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3609. this._updateEventEmitters();
  3610. this._updateWatch();
  3611. return (changed > 0);
  3612. };
  3613. /**
  3614. * Reflow the component
  3615. * @return {Boolean} resized
  3616. */
  3617. RootPanel.prototype.reflow = function () {
  3618. var changed = 0,
  3619. update = util.updateProperty,
  3620. frame = this.frame;
  3621. if (frame) {
  3622. changed += update(this, 'top', frame.offsetTop);
  3623. changed += update(this, 'left', frame.offsetLeft);
  3624. changed += update(this, 'width', frame.offsetWidth);
  3625. changed += update(this, 'height', frame.offsetHeight);
  3626. }
  3627. else {
  3628. changed += 1;
  3629. }
  3630. return (changed > 0);
  3631. };
  3632. /**
  3633. * Update watching for resize, depending on the current option
  3634. * @private
  3635. */
  3636. RootPanel.prototype._updateWatch = function () {
  3637. var autoResize = this.getOption('autoResize');
  3638. if (autoResize) {
  3639. this._watch();
  3640. }
  3641. else {
  3642. this._unwatch();
  3643. }
  3644. };
  3645. /**
  3646. * Watch for changes in the size of the frame. On resize, the Panel will
  3647. * automatically redraw itself.
  3648. * @private
  3649. */
  3650. RootPanel.prototype._watch = function () {
  3651. var me = this;
  3652. this._unwatch();
  3653. var checkSize = function () {
  3654. var autoResize = me.getOption('autoResize');
  3655. if (!autoResize) {
  3656. // stop watching when the option autoResize is changed to false
  3657. me._unwatch();
  3658. return;
  3659. }
  3660. if (me.frame) {
  3661. // check whether the frame is resized
  3662. if ((me.frame.clientWidth != me.width) ||
  3663. (me.frame.clientHeight != me.height)) {
  3664. me.requestReflow();
  3665. }
  3666. }
  3667. };
  3668. // TODO: automatically cleanup the event listener when the frame is deleted
  3669. util.addEventListener(window, 'resize', checkSize);
  3670. this.watchTimer = setInterval(checkSize, 1000);
  3671. };
  3672. /**
  3673. * Stop watching for a resize of the frame.
  3674. * @private
  3675. */
  3676. RootPanel.prototype._unwatch = function () {
  3677. if (this.watchTimer) {
  3678. clearInterval(this.watchTimer);
  3679. this.watchTimer = undefined;
  3680. }
  3681. // TODO: remove event listener on window.resize
  3682. };
  3683. /**
  3684. * Event handler
  3685. * @param {String} event name of the event, for example 'click', 'mousemove'
  3686. * @param {function} callback callback handler, invoked with the raw HTML Event
  3687. * as parameter.
  3688. */
  3689. RootPanel.prototype.on = function (event, callback) {
  3690. // register the listener at this component
  3691. var arr = this.listeners[event];
  3692. if (!arr) {
  3693. arr = [];
  3694. this.listeners[event] = arr;
  3695. }
  3696. arr.push(callback);
  3697. this._updateEventEmitters();
  3698. };
  3699. /**
  3700. * Update the event listeners for all event emitters
  3701. * @private
  3702. */
  3703. RootPanel.prototype._updateEventEmitters = function () {
  3704. if (this.listeners) {
  3705. var me = this;
  3706. util.forEach(this.listeners, function (listeners, event) {
  3707. if (!me.emitters) {
  3708. me.emitters = {};
  3709. }
  3710. if (!(event in me.emitters)) {
  3711. // create event
  3712. var frame = me.frame;
  3713. if (frame) {
  3714. //console.log('Created a listener for event ' + event + ' on component ' + me.id); // TODO: cleanup logging
  3715. var callback = function(event) {
  3716. listeners.forEach(function (listener) {
  3717. // TODO: filter on event target!
  3718. listener(event);
  3719. });
  3720. };
  3721. me.emitters[event] = callback;
  3722. util.addEventListener(frame, event, callback);
  3723. }
  3724. }
  3725. });
  3726. // TODO: be able to delete event listeners
  3727. // TODO: be able to move event listeners to a parent when available
  3728. }
  3729. };
  3730. /**
  3731. * A horizontal time axis
  3732. * @param {Component} parent
  3733. * @param {Component[]} [depends] Components on which this components depends
  3734. * (except for the parent)
  3735. * @param {Object} [options] See TimeAxis.setOptions for the available
  3736. * options.
  3737. * @constructor TimeAxis
  3738. * @extends Component
  3739. */
  3740. function TimeAxis (parent, depends, options) {
  3741. this.id = util.randomUUID();
  3742. this.parent = parent;
  3743. this.depends = depends;
  3744. this.dom = {
  3745. majorLines: [],
  3746. majorTexts: [],
  3747. minorLines: [],
  3748. minorTexts: [],
  3749. redundant: {
  3750. majorLines: [],
  3751. majorTexts: [],
  3752. minorLines: [],
  3753. minorTexts: []
  3754. }
  3755. };
  3756. this.props = {
  3757. range: {
  3758. start: 0,
  3759. end: 0,
  3760. minimumStep: 0
  3761. },
  3762. lineTop: 0
  3763. };
  3764. this.options = options || {};
  3765. this.defaultOptions = {
  3766. orientation: 'bottom', // supported: 'top', 'bottom'
  3767. // TODO: implement timeaxis orientations 'left' and 'right'
  3768. showMinorLabels: true,
  3769. showMajorLabels: true
  3770. };
  3771. this.conversion = null;
  3772. this.range = null;
  3773. }
  3774. TimeAxis.prototype = new Component();
  3775. // TODO: comment options
  3776. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  3777. /**
  3778. * Set a range (start and end)
  3779. * @param {Range | Object} range A Range or an object containing start and end.
  3780. */
  3781. TimeAxis.prototype.setRange = function (range) {
  3782. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  3783. throw new TypeError('Range must be an instance of Range, ' +
  3784. 'or an object containing start and end.');
  3785. }
  3786. this.range = range;
  3787. };
  3788. /**
  3789. * Convert a position on screen (pixels) to a datetime
  3790. * @param {int} x Position on the screen in pixels
  3791. * @return {Date} time The datetime the corresponds with given position x
  3792. */
  3793. TimeAxis.prototype.toTime = function(x) {
  3794. var conversion = this.conversion;
  3795. return new Date(x / conversion.factor + conversion.offset);
  3796. };
  3797. /**
  3798. * Convert a datetime (Date object) into a position on the screen
  3799. * @param {Date} time A date
  3800. * @return {int} x The position on the screen in pixels which corresponds
  3801. * with the given date.
  3802. * @private
  3803. */
  3804. TimeAxis.prototype.toScreen = function(time) {
  3805. var conversion = this.conversion;
  3806. return (time.valueOf() - conversion.offset) * conversion.factor;
  3807. };
  3808. /**
  3809. * Repaint the component
  3810. * @return {Boolean} changed
  3811. */
  3812. TimeAxis.prototype.repaint = function () {
  3813. var changed = 0,
  3814. update = util.updateProperty,
  3815. asSize = util.option.asSize,
  3816. options = this.options,
  3817. orientation = this.getOption('orientation'),
  3818. props = this.props,
  3819. step = this.step;
  3820. var frame = this.frame;
  3821. if (!frame) {
  3822. frame = document.createElement('div');
  3823. this.frame = frame;
  3824. changed += 1;
  3825. }
  3826. frame.className = 'axis ' + orientation;
  3827. // TODO: custom className?
  3828. if (!frame.parentNode) {
  3829. if (!this.parent) {
  3830. throw new Error('Cannot repaint time axis: no parent attached');
  3831. }
  3832. var parentContainer = this.parent.getContainer();
  3833. if (!parentContainer) {
  3834. throw new Error('Cannot repaint time axis: parent has no container element');
  3835. }
  3836. parentContainer.appendChild(frame);
  3837. changed += 1;
  3838. }
  3839. var parent = frame.parentNode;
  3840. if (parent) {
  3841. var beforeChild = frame.nextSibling;
  3842. parent.removeChild(frame); // take frame offline while updating (is almost twice as fast)
  3843. var defaultTop = (orientation == 'bottom' && this.props.parentHeight && this.height) ?
  3844. (this.props.parentHeight - this.height) + 'px' :
  3845. '0px';
  3846. changed += update(frame.style, 'top', asSize(options.top, defaultTop));
  3847. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3848. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3849. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  3850. // get characters width and height
  3851. this._repaintMeasureChars();
  3852. if (this.step) {
  3853. this._repaintStart();
  3854. step.first();
  3855. var xFirstMajorLabel = undefined;
  3856. var max = 0;
  3857. while (step.hasNext() && max < 1000) {
  3858. max++;
  3859. var cur = step.getCurrent(),
  3860. x = this.toScreen(cur),
  3861. isMajor = step.isMajor();
  3862. // TODO: lines must have a width, such that we can create css backgrounds
  3863. if (this.getOption('showMinorLabels')) {
  3864. this._repaintMinorText(x, step.getLabelMinor());
  3865. }
  3866. if (isMajor && this.getOption('showMajorLabels')) {
  3867. if (x > 0) {
  3868. if (xFirstMajorLabel == undefined) {
  3869. xFirstMajorLabel = x;
  3870. }
  3871. this._repaintMajorText(x, step.getLabelMajor());
  3872. }
  3873. this._repaintMajorLine(x);
  3874. }
  3875. else {
  3876. this._repaintMinorLine(x);
  3877. }
  3878. step.next();
  3879. }
  3880. // create a major label on the left when needed
  3881. if (this.getOption('showMajorLabels')) {
  3882. var leftTime = this.toTime(0),
  3883. leftText = step.getLabelMajor(leftTime),
  3884. widthText = leftText.length * (props.majorCharWidth || 10) + 10; // upper bound estimation
  3885. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3886. this._repaintMajorText(0, leftText);
  3887. }
  3888. }
  3889. this._repaintEnd();
  3890. }
  3891. this._repaintLine();
  3892. // put frame online again
  3893. if (beforeChild) {
  3894. parent.insertBefore(frame, beforeChild);
  3895. }
  3896. else {
  3897. parent.appendChild(frame)
  3898. }
  3899. }
  3900. return (changed > 0);
  3901. };
  3902. /**
  3903. * Start a repaint. Move all DOM elements to a redundant list, where they
  3904. * can be picked for re-use, or can be cleaned up in the end
  3905. * @private
  3906. */
  3907. TimeAxis.prototype._repaintStart = function () {
  3908. var dom = this.dom,
  3909. redundant = dom.redundant;
  3910. redundant.majorLines = dom.majorLines;
  3911. redundant.majorTexts = dom.majorTexts;
  3912. redundant.minorLines = dom.minorLines;
  3913. redundant.minorTexts = dom.minorTexts;
  3914. dom.majorLines = [];
  3915. dom.majorTexts = [];
  3916. dom.minorLines = [];
  3917. dom.minorTexts = [];
  3918. };
  3919. /**
  3920. * End a repaint. Cleanup leftover DOM elements in the redundant list
  3921. * @private
  3922. */
  3923. TimeAxis.prototype._repaintEnd = function () {
  3924. util.forEach(this.dom.redundant, function (arr) {
  3925. while (arr.length) {
  3926. var elem = arr.pop();
  3927. if (elem && elem.parentNode) {
  3928. elem.parentNode.removeChild(elem);
  3929. }
  3930. }
  3931. });
  3932. };
  3933. /**
  3934. * Create a minor label for the axis at position x
  3935. * @param {Number} x
  3936. * @param {String} text
  3937. * @private
  3938. */
  3939. TimeAxis.prototype._repaintMinorText = function (x, text) {
  3940. // reuse redundant label
  3941. var label = this.dom.redundant.minorTexts.shift();
  3942. if (!label) {
  3943. // create new label
  3944. var content = document.createTextNode('');
  3945. label = document.createElement('div');
  3946. label.appendChild(content);
  3947. label.className = 'text minor';
  3948. this.frame.appendChild(label);
  3949. }
  3950. this.dom.minorTexts.push(label);
  3951. label.childNodes[0].nodeValue = text;
  3952. label.style.left = x + 'px';
  3953. label.style.top = this.props.minorLabelTop + 'px';
  3954. //label.title = title; // TODO: this is a heavy operation
  3955. };
  3956. /**
  3957. * Create a Major label for the axis at position x
  3958. * @param {Number} x
  3959. * @param {String} text
  3960. * @private
  3961. */
  3962. TimeAxis.prototype._repaintMajorText = function (x, text) {
  3963. // reuse redundant label
  3964. var label = this.dom.redundant.majorTexts.shift();
  3965. if (!label) {
  3966. // create label
  3967. var content = document.createTextNode(text);
  3968. label = document.createElement('div');
  3969. label.className = 'text major';
  3970. label.appendChild(content);
  3971. this.frame.appendChild(label);
  3972. }
  3973. this.dom.majorTexts.push(label);
  3974. label.childNodes[0].nodeValue = text;
  3975. label.style.top = this.props.majorLabelTop + 'px';
  3976. label.style.left = x + 'px';
  3977. //label.title = title; // TODO: this is a heavy operation
  3978. };
  3979. /**
  3980. * Create a minor line for the axis at position x
  3981. * @param {Number} x
  3982. * @private
  3983. */
  3984. TimeAxis.prototype._repaintMinorLine = function (x) {
  3985. // reuse redundant line
  3986. var line = this.dom.redundant.minorLines.shift();
  3987. if (!line) {
  3988. // create vertical line
  3989. line = document.createElement('div');
  3990. line.className = 'grid vertical minor';
  3991. this.frame.appendChild(line);
  3992. }
  3993. this.dom.minorLines.push(line);
  3994. var props = this.props;
  3995. line.style.top = props.minorLineTop + 'px';
  3996. line.style.height = props.minorLineHeight + 'px';
  3997. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  3998. };
  3999. /**
  4000. * Create a Major line for the axis at position x
  4001. * @param {Number} x
  4002. * @private
  4003. */
  4004. TimeAxis.prototype._repaintMajorLine = function (x) {
  4005. // reuse redundant line
  4006. var line = this.dom.redundant.majorLines.shift();
  4007. if (!line) {
  4008. // create vertical line
  4009. line = document.createElement('DIV');
  4010. line.className = 'grid vertical major';
  4011. this.frame.appendChild(line);
  4012. }
  4013. this.dom.majorLines.push(line);
  4014. var props = this.props;
  4015. line.style.top = props.majorLineTop + 'px';
  4016. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  4017. line.style.height = props.majorLineHeight + 'px';
  4018. };
  4019. /**
  4020. * Repaint the horizontal line for the axis
  4021. * @private
  4022. */
  4023. TimeAxis.prototype._repaintLine = function() {
  4024. var line = this.dom.line,
  4025. frame = this.frame,
  4026. options = this.options;
  4027. // line before all axis elements
  4028. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  4029. if (line) {
  4030. // put this line at the end of all childs
  4031. frame.removeChild(line);
  4032. frame.appendChild(line);
  4033. }
  4034. else {
  4035. // create the axis line
  4036. line = document.createElement('div');
  4037. line.className = 'grid horizontal major';
  4038. frame.appendChild(line);
  4039. this.dom.line = line;
  4040. }
  4041. line.style.top = this.props.lineTop + 'px';
  4042. }
  4043. else {
  4044. if (line && axis.parentElement) {
  4045. frame.removeChild(axis.line);
  4046. delete this.dom.line;
  4047. }
  4048. }
  4049. };
  4050. /**
  4051. * Create characters used to determine the size of text on the axis
  4052. * @private
  4053. */
  4054. TimeAxis.prototype._repaintMeasureChars = function () {
  4055. // calculate the width and height of a single character
  4056. // this is used to calculate the step size, and also the positioning of the
  4057. // axis
  4058. var dom = this.dom,
  4059. text;
  4060. if (!dom.measureCharMinor) {
  4061. text = document.createTextNode('0');
  4062. var measureCharMinor = document.createElement('DIV');
  4063. measureCharMinor.className = 'text minor measure';
  4064. measureCharMinor.appendChild(text);
  4065. this.frame.appendChild(measureCharMinor);
  4066. dom.measureCharMinor = measureCharMinor;
  4067. }
  4068. if (!dom.measureCharMajor) {
  4069. text = document.createTextNode('0');
  4070. var measureCharMajor = document.createElement('DIV');
  4071. measureCharMajor.className = 'text major measure';
  4072. measureCharMajor.appendChild(text);
  4073. this.frame.appendChild(measureCharMajor);
  4074. dom.measureCharMajor = measureCharMajor;
  4075. }
  4076. };
  4077. /**
  4078. * Reflow the component
  4079. * @return {Boolean} resized
  4080. */
  4081. TimeAxis.prototype.reflow = function () {
  4082. var changed = 0,
  4083. update = util.updateProperty,
  4084. frame = this.frame,
  4085. range = this.range;
  4086. if (!range) {
  4087. throw new Error('Cannot repaint time axis: no range configured');
  4088. }
  4089. if (frame) {
  4090. changed += update(this, 'top', frame.offsetTop);
  4091. changed += update(this, 'left', frame.offsetLeft);
  4092. // calculate size of a character
  4093. var props = this.props,
  4094. showMinorLabels = this.getOption('showMinorLabels'),
  4095. showMajorLabels = this.getOption('showMajorLabels'),
  4096. measureCharMinor = this.dom.measureCharMinor,
  4097. measureCharMajor = this.dom.measureCharMajor;
  4098. if (measureCharMinor) {
  4099. props.minorCharHeight = measureCharMinor.clientHeight;
  4100. props.minorCharWidth = measureCharMinor.clientWidth;
  4101. }
  4102. if (measureCharMajor) {
  4103. props.majorCharHeight = measureCharMajor.clientHeight;
  4104. props.majorCharWidth = measureCharMajor.clientWidth;
  4105. }
  4106. var parentHeight = frame.parentNode ? frame.parentNode.offsetHeight : 0;
  4107. if (parentHeight != props.parentHeight) {
  4108. props.parentHeight = parentHeight;
  4109. changed += 1;
  4110. }
  4111. switch (this.getOption('orientation')) {
  4112. case 'bottom':
  4113. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4114. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4115. props.minorLabelTop = 0;
  4116. props.majorLabelTop = props.minorLabelTop + props.minorLabelHeight;
  4117. props.minorLineTop = -this.top;
  4118. props.minorLineHeight = Math.max(this.top + props.majorLabelHeight, 0);
  4119. props.minorLineWidth = 1; // TODO: really calculate width
  4120. props.majorLineTop = -this.top;
  4121. props.majorLineHeight = Math.max(this.top + props.minorLabelHeight + props.majorLabelHeight, 0);
  4122. props.majorLineWidth = 1; // TODO: really calculate width
  4123. props.lineTop = 0;
  4124. break;
  4125. case 'top':
  4126. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4127. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4128. props.majorLabelTop = 0;
  4129. props.minorLabelTop = props.majorLabelTop + props.majorLabelHeight;
  4130. props.minorLineTop = props.minorLabelTop;
  4131. props.minorLineHeight = Math.max(parentHeight - props.majorLabelHeight - this.top);
  4132. props.minorLineWidth = 1; // TODO: really calculate width
  4133. props.majorLineTop = 0;
  4134. props.majorLineHeight = Math.max(parentHeight - this.top);
  4135. props.majorLineWidth = 1; // TODO: really calculate width
  4136. props.lineTop = props.majorLabelHeight + props.minorLabelHeight;
  4137. break;
  4138. default:
  4139. throw new Error('Unkown orientation "' + this.getOption('orientation') + '"');
  4140. }
  4141. var height = props.minorLabelHeight + props.majorLabelHeight;
  4142. changed += update(this, 'width', frame.offsetWidth);
  4143. changed += update(this, 'height', height);
  4144. // calculate range and step
  4145. this._updateConversion();
  4146. var start = util.convert(range.start, 'Date'),
  4147. end = util.convert(range.end, 'Date'),
  4148. minimumStep = this.toTime((props.minorCharWidth || 10) * 5) - this.toTime(0);
  4149. this.step = new TimeStep(start, end, minimumStep);
  4150. changed += update(props.range, 'start', start.valueOf());
  4151. changed += update(props.range, 'end', end.valueOf());
  4152. changed += update(props.range, 'minimumStep', minimumStep.valueOf());
  4153. }
  4154. return (changed > 0);
  4155. };
  4156. /**
  4157. * Calculate the factor and offset to convert a position on screen to the
  4158. * corresponding date and vice versa.
  4159. * After the method _updateConversion is executed once, the methods toTime
  4160. * and toScreen can be used.
  4161. * @private
  4162. */
  4163. TimeAxis.prototype._updateConversion = function() {
  4164. var range = this.range;
  4165. if (!range) {
  4166. throw new Error('No range configured');
  4167. }
  4168. if (range.conversion) {
  4169. this.conversion = range.conversion(this.width);
  4170. }
  4171. else {
  4172. this.conversion = Range.conversion(range.start, range.end, this.width);
  4173. }
  4174. };
  4175. /**
  4176. * An ItemSet holds a set of items and ranges which can be displayed in a
  4177. * range. The width is determined by the parent of the ItemSet, and the height
  4178. * is determined by the size of the items.
  4179. * @param {Component} parent
  4180. * @param {Component[]} [depends] Components on which this components depends
  4181. * (except for the parent)
  4182. * @param {Object} [options] See ItemSet.setOptions for the available
  4183. * options.
  4184. * @constructor ItemSet
  4185. * @extends Panel
  4186. */
  4187. // TODO: improve performance by replacing all Array.forEach with a for loop
  4188. function ItemSet(parent, depends, options) {
  4189. this.id = util.randomUUID();
  4190. this.parent = parent;
  4191. this.depends = depends;
  4192. // one options object is shared by this itemset and all its items
  4193. this.options = options || {};
  4194. this.defaultOptions = {
  4195. type: 'box',
  4196. align: 'center',
  4197. orientation: 'bottom',
  4198. margin: {
  4199. axis: 20,
  4200. item: 10
  4201. },
  4202. padding: 5
  4203. };
  4204. this.dom = {};
  4205. var me = this;
  4206. this.itemsData = null; // DataSet
  4207. this.range = null; // Range or Object {start: number, end: number}
  4208. this.listeners = {
  4209. 'add': function (event, params, senderId) {
  4210. if (senderId != me.id) {
  4211. me._onAdd(params.items);
  4212. }
  4213. },
  4214. 'update': function (event, params, senderId) {
  4215. if (senderId != me.id) {
  4216. me._onUpdate(params.items);
  4217. }
  4218. },
  4219. 'remove': function (event, params, senderId) {
  4220. if (senderId != me.id) {
  4221. me._onRemove(params.items);
  4222. }
  4223. }
  4224. };
  4225. this.items = {}; // object with an Item for every data item
  4226. this.queue = {}; // queue with id/actions: 'add', 'update', 'delete'
  4227. this.stack = new Stack(this, Object.create(this.options));
  4228. this.conversion = null;
  4229. // TODO: ItemSet should also attach event listeners for rangechange and rangechanged, like timeaxis
  4230. }
  4231. ItemSet.prototype = new Panel();
  4232. // available item types will be registered here
  4233. ItemSet.types = {
  4234. box: ItemBox,
  4235. range: ItemRange,
  4236. point: ItemPoint
  4237. };
  4238. /**
  4239. * Set options for the ItemSet. Existing options will be extended/overwritten.
  4240. * @param {Object} [options] The following options are available:
  4241. * {String | function} [className]
  4242. * class name for the itemset
  4243. * {String} [type]
  4244. * Default type for the items. Choose from 'box'
  4245. * (default), 'point', or 'range'. The default
  4246. * Style can be overwritten by individual items.
  4247. * {String} align
  4248. * Alignment for the items, only applicable for
  4249. * ItemBox. Choose 'center' (default), 'left', or
  4250. * 'right'.
  4251. * {String} orientation
  4252. * Orientation of the item set. Choose 'top' or
  4253. * 'bottom' (default).
  4254. * {Number} margin.axis
  4255. * Margin between the axis and the items in pixels.
  4256. * Default is 20.
  4257. * {Number} margin.item
  4258. * Margin between items in pixels. Default is 10.
  4259. * {Number} padding
  4260. * Padding of the contents of an item in pixels.
  4261. * Must correspond with the items css. Default is 5.
  4262. */
  4263. ItemSet.prototype.setOptions = Component.prototype.setOptions;
  4264. /**
  4265. * Set range (start and end).
  4266. * @param {Range | Object} range A Range or an object containing start and end.
  4267. */
  4268. ItemSet.prototype.setRange = function setRange(range) {
  4269. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4270. throw new TypeError('Range must be an instance of Range, ' +
  4271. 'or an object containing start and end.');
  4272. }
  4273. this.range = range;
  4274. };
  4275. /**
  4276. * Repaint the component
  4277. * @return {Boolean} changed
  4278. */
  4279. ItemSet.prototype.repaint = function repaint() {
  4280. var changed = 0,
  4281. update = util.updateProperty,
  4282. asSize = util.option.asSize,
  4283. options = this.options,
  4284. orientation = this.getOption('orientation'),
  4285. defaultOptions = this.defaultOptions,
  4286. frame = this.frame;
  4287. if (!frame) {
  4288. frame = document.createElement('div');
  4289. frame.className = 'itemset';
  4290. var className = options.className;
  4291. if (className) {
  4292. util.addClassName(frame, util.option.asString(className));
  4293. }
  4294. // create background panel
  4295. var background = document.createElement('div');
  4296. background.className = 'background';
  4297. frame.appendChild(background);
  4298. this.dom.background = background;
  4299. // create foreground panel
  4300. var foreground = document.createElement('div');
  4301. foreground.className = 'foreground';
  4302. frame.appendChild(foreground);
  4303. this.dom.foreground = foreground;
  4304. // create axis panel
  4305. var axis = document.createElement('div');
  4306. axis.className = 'itemset-axis';
  4307. //frame.appendChild(axis);
  4308. this.dom.axis = axis;
  4309. this.frame = frame;
  4310. changed += 1;
  4311. }
  4312. if (!this.parent) {
  4313. throw new Error('Cannot repaint itemset: no parent attached');
  4314. }
  4315. var parentContainer = this.parent.getContainer();
  4316. if (!parentContainer) {
  4317. throw new Error('Cannot repaint itemset: parent has no container element');
  4318. }
  4319. if (!frame.parentNode) {
  4320. parentContainer.appendChild(frame);
  4321. changed += 1;
  4322. }
  4323. if (!this.dom.axis.parentNode) {
  4324. parentContainer.appendChild(this.dom.axis);
  4325. changed += 1;
  4326. }
  4327. // reposition frame
  4328. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  4329. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  4330. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  4331. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  4332. // reposition axis
  4333. changed += update(this.dom.axis.style, 'left', asSize(options.left, '0px'));
  4334. changed += update(this.dom.axis.style, 'width', asSize(options.width, '100%'));
  4335. if (orientation == 'bottom') {
  4336. changed += update(this.dom.axis.style, 'top', (this.height + this.top) + 'px');
  4337. }
  4338. else { // orientation == 'top'
  4339. changed += update(this.dom.axis.style, 'top', this.top + 'px');
  4340. }
  4341. this._updateConversion();
  4342. var me = this,
  4343. queue = this.queue,
  4344. itemsData = this.itemsData,
  4345. items = this.items,
  4346. dataOptions = {
  4347. fields: [(itemsData && itemsData.fieldId || 'id'), 'start', 'end', 'content', 'type']
  4348. };
  4349. // TODO: copy options from the itemset itself?
  4350. // show/hide added/changed/removed items
  4351. Object.keys(queue).forEach(function (id) {
  4352. //var entry = queue[id];
  4353. var action = queue[id];
  4354. var item = items[id];
  4355. //var item = entry.item;
  4356. //noinspection FallthroughInSwitchStatementJS
  4357. switch (action) {
  4358. case 'add':
  4359. case 'update':
  4360. var itemData = itemsData && itemsData.get(id, dataOptions);
  4361. if (itemData) {
  4362. var type = itemData.type ||
  4363. (itemData.start && itemData.end && 'range') ||
  4364. options.type ||
  4365. 'box';
  4366. var constructor = ItemSet.types[type];
  4367. // TODO: how to handle items with invalid data? hide them and give a warning? or throw an error?
  4368. if (item) {
  4369. // update item
  4370. if (!constructor || !(item instanceof constructor)) {
  4371. // item type has changed, hide and delete the item
  4372. changed += item.hide();
  4373. item = null;
  4374. }
  4375. else {
  4376. item.data = itemData; // TODO: create a method item.setData ?
  4377. changed++;
  4378. }
  4379. }
  4380. if (!item) {
  4381. // create item
  4382. if (constructor) {
  4383. item = new constructor(me, itemData, options, defaultOptions);
  4384. changed++;
  4385. }
  4386. else {
  4387. throw new TypeError('Unknown item type "' + type + '"');
  4388. }
  4389. }
  4390. // force a repaint (not only a reposition)
  4391. item.repaint();
  4392. items[id] = item;
  4393. }
  4394. // update queue
  4395. delete queue[id];
  4396. break;
  4397. case 'remove':
  4398. if (item) {
  4399. // remove DOM of the item
  4400. changed += item.hide();
  4401. }
  4402. // update lists
  4403. delete items[id];
  4404. delete queue[id];
  4405. break;
  4406. default:
  4407. console.log('Error: unknown action "' + action + '"');
  4408. }
  4409. });
  4410. // reposition all items. Show items only when in the visible area
  4411. util.forEach(this.items, function (item) {
  4412. if (item.visible) {
  4413. changed += item.show();
  4414. item.reposition();
  4415. }
  4416. else {
  4417. changed += item.hide();
  4418. }
  4419. });
  4420. return (changed > 0);
  4421. };
  4422. /**
  4423. * Get the foreground container element
  4424. * @return {HTMLElement} foreground
  4425. */
  4426. ItemSet.prototype.getForeground = function getForeground() {
  4427. return this.dom.foreground;
  4428. };
  4429. /**
  4430. * Get the background container element
  4431. * @return {HTMLElement} background
  4432. */
  4433. ItemSet.prototype.getBackground = function getBackground() {
  4434. return this.dom.background;
  4435. };
  4436. /**
  4437. * Get the axis container element
  4438. * @return {HTMLElement} axis
  4439. */
  4440. ItemSet.prototype.getAxis = function getAxis() {
  4441. return this.dom.axis;
  4442. };
  4443. /**
  4444. * Reflow the component
  4445. * @return {Boolean} resized
  4446. */
  4447. ItemSet.prototype.reflow = function reflow () {
  4448. var changed = 0,
  4449. options = this.options,
  4450. marginAxis = options.margin && options.margin.axis || this.defaultOptions.margin.axis,
  4451. marginItem = options.margin && options.margin.item || this.defaultOptions.margin.item,
  4452. update = util.updateProperty,
  4453. asNumber = util.option.asNumber,
  4454. asSize = util.option.asSize,
  4455. frame = this.frame;
  4456. if (frame) {
  4457. this._updateConversion();
  4458. util.forEach(this.items, function (item) {
  4459. changed += item.reflow();
  4460. });
  4461. // TODO: stack.update should be triggered via an event, in stack itself
  4462. // TODO: only update the stack when there are changed items
  4463. this.stack.update();
  4464. var maxHeight = asNumber(options.maxHeight);
  4465. var fixedHeight = (asSize(options.height) != null);
  4466. var height;
  4467. if (fixedHeight) {
  4468. height = frame.offsetHeight;
  4469. }
  4470. else {
  4471. // height is not specified, determine the height from the height and positioned items
  4472. var visibleItems = this.stack.ordered; // TODO: not so nice way to get the filtered items
  4473. if (visibleItems.length) {
  4474. var min = visibleItems[0].top;
  4475. var max = visibleItems[0].top + visibleItems[0].height;
  4476. util.forEach(visibleItems, function (item) {
  4477. min = Math.min(min, item.top);
  4478. max = Math.max(max, (item.top + item.height));
  4479. });
  4480. height = (max - min) + marginAxis + marginItem;
  4481. }
  4482. else {
  4483. height = marginAxis + marginItem;
  4484. }
  4485. }
  4486. if (maxHeight != null) {
  4487. height = Math.min(height, maxHeight);
  4488. }
  4489. changed += update(this, 'height', height);
  4490. // calculate height from items
  4491. changed += update(this, 'top', frame.offsetTop);
  4492. changed += update(this, 'left', frame.offsetLeft);
  4493. changed += update(this, 'width', frame.offsetWidth);
  4494. }
  4495. else {
  4496. changed += 1;
  4497. }
  4498. return (changed > 0);
  4499. };
  4500. /**
  4501. * Hide this component from the DOM
  4502. * @return {Boolean} changed
  4503. */
  4504. ItemSet.prototype.hide = function hide() {
  4505. var changed = false;
  4506. // remove the DOM
  4507. if (this.frame && this.frame.parentNode) {
  4508. this.frame.parentNode.removeChild(this.frame);
  4509. changed = true;
  4510. }
  4511. if (this.dom.axis && this.dom.axis.parentNode) {
  4512. this.dom.axis.parentNode.removeChild(this.dom.axis);
  4513. changed = true;
  4514. }
  4515. return changed;
  4516. };
  4517. /**
  4518. * Set items
  4519. * @param {vis.DataSet | null} items
  4520. */
  4521. ItemSet.prototype.setItems = function setItems(items) {
  4522. var me = this,
  4523. ids,
  4524. oldItemsData = this.itemsData;
  4525. // replace the dataset
  4526. if (!items) {
  4527. this.itemsData = null;
  4528. }
  4529. else if (items instanceof DataSet || items instanceof DataView) {
  4530. this.itemsData = items;
  4531. }
  4532. else {
  4533. throw new TypeError('Data must be an instance of DataSet');
  4534. }
  4535. if (oldItemsData) {
  4536. // unsubscribe from old dataset
  4537. util.forEach(this.listeners, function (callback, event) {
  4538. oldItemsData.unsubscribe(event, callback);
  4539. });
  4540. // remove all drawn items
  4541. ids = oldItemsData.getIds();
  4542. this._onRemove(ids);
  4543. }
  4544. if (this.itemsData) {
  4545. // subscribe to new dataset
  4546. var id = this.id;
  4547. util.forEach(this.listeners, function (callback, event) {
  4548. me.itemsData.subscribe(event, callback, id);
  4549. });
  4550. // draw all new items
  4551. ids = this.itemsData.getIds();
  4552. this._onAdd(ids);
  4553. }
  4554. };
  4555. /**
  4556. * Get the current items items
  4557. * @returns {vis.DataSet | null}
  4558. */
  4559. ItemSet.prototype.getItems = function getItems() {
  4560. return this.itemsData;
  4561. };
  4562. /**
  4563. * Handle updated items
  4564. * @param {Number[]} ids
  4565. * @private
  4566. */
  4567. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  4568. this._toQueue('update', ids);
  4569. };
  4570. /**
  4571. * Handle changed items
  4572. * @param {Number[]} ids
  4573. * @private
  4574. */
  4575. ItemSet.prototype._onAdd = function _onAdd(ids) {
  4576. this._toQueue('add', ids);
  4577. };
  4578. /**
  4579. * Handle removed items
  4580. * @param {Number[]} ids
  4581. * @private
  4582. */
  4583. ItemSet.prototype._onRemove = function _onRemove(ids) {
  4584. this._toQueue('remove', ids);
  4585. };
  4586. /**
  4587. * Put items in the queue to be added/updated/remove
  4588. * @param {String} action can be 'add', 'update', 'remove'
  4589. * @param {Number[]} ids
  4590. */
  4591. ItemSet.prototype._toQueue = function _toQueue(action, ids) {
  4592. var queue = this.queue;
  4593. ids.forEach(function (id) {
  4594. queue[id] = action;
  4595. });
  4596. if (this.controller) {
  4597. //this.requestReflow();
  4598. this.requestRepaint();
  4599. }
  4600. };
  4601. /**
  4602. * Calculate the factor and offset to convert a position on screen to the
  4603. * corresponding date and vice versa.
  4604. * After the method _updateConversion is executed once, the methods toTime
  4605. * and toScreen can be used.
  4606. * @private
  4607. */
  4608. ItemSet.prototype._updateConversion = function _updateConversion() {
  4609. var range = this.range;
  4610. if (!range) {
  4611. throw new Error('No range configured');
  4612. }
  4613. if (range.conversion) {
  4614. this.conversion = range.conversion(this.width);
  4615. }
  4616. else {
  4617. this.conversion = Range.conversion(range.start, range.end, this.width);
  4618. }
  4619. };
  4620. /**
  4621. * Convert a position on screen (pixels) to a datetime
  4622. * Before this method can be used, the method _updateConversion must be
  4623. * executed once.
  4624. * @param {int} x Position on the screen in pixels
  4625. * @return {Date} time The datetime the corresponds with given position x
  4626. */
  4627. ItemSet.prototype.toTime = function toTime(x) {
  4628. var conversion = this.conversion;
  4629. return new Date(x / conversion.factor + conversion.offset);
  4630. };
  4631. /**
  4632. * Convert a datetime (Date object) into a position on the screen
  4633. * Before this method can be used, the method _updateConversion must be
  4634. * executed once.
  4635. * @param {Date} time A date
  4636. * @return {int} x The position on the screen in pixels which corresponds
  4637. * with the given date.
  4638. */
  4639. ItemSet.prototype.toScreen = function toScreen(time) {
  4640. var conversion = this.conversion;
  4641. return (time.valueOf() - conversion.offset) * conversion.factor;
  4642. };
  4643. /**
  4644. * @constructor Item
  4645. * @param {ItemSet} parent
  4646. * @param {Object} data Object containing (optional) parameters type,
  4647. * start, end, content, group, className.
  4648. * @param {Object} [options] Options to set initial property values
  4649. * @param {Object} [defaultOptions] default options
  4650. * // TODO: describe available options
  4651. */
  4652. function Item (parent, data, options, defaultOptions) {
  4653. this.parent = parent;
  4654. this.data = data;
  4655. this.dom = null;
  4656. this.options = options || {};
  4657. this.defaultOptions = defaultOptions || {};
  4658. this.selected = false;
  4659. this.visible = false;
  4660. this.top = 0;
  4661. this.left = 0;
  4662. this.width = 0;
  4663. this.height = 0;
  4664. }
  4665. /**
  4666. * Select current item
  4667. */
  4668. Item.prototype.select = function select() {
  4669. this.selected = true;
  4670. };
  4671. /**
  4672. * Unselect current item
  4673. */
  4674. Item.prototype.unselect = function unselect() {
  4675. this.selected = false;
  4676. };
  4677. /**
  4678. * Show the Item in the DOM (when not already visible)
  4679. * @return {Boolean} changed
  4680. */
  4681. Item.prototype.show = function show() {
  4682. return false;
  4683. };
  4684. /**
  4685. * Hide the Item from the DOM (when visible)
  4686. * @return {Boolean} changed
  4687. */
  4688. Item.prototype.hide = function hide() {
  4689. return false;
  4690. };
  4691. /**
  4692. * Repaint the item
  4693. * @return {Boolean} changed
  4694. */
  4695. Item.prototype.repaint = function repaint() {
  4696. // should be implemented by the item
  4697. return false;
  4698. };
  4699. /**
  4700. * Reflow the item
  4701. * @return {Boolean} resized
  4702. */
  4703. Item.prototype.reflow = function reflow() {
  4704. // should be implemented by the item
  4705. return false;
  4706. };
  4707. /**
  4708. * @constructor ItemBox
  4709. * @extends Item
  4710. * @param {ItemSet} parent
  4711. * @param {Object} data Object containing parameters start
  4712. * content, className.
  4713. * @param {Object} [options] Options to set initial property values
  4714. * @param {Object} [defaultOptions] default options
  4715. * // TODO: describe available options
  4716. */
  4717. function ItemBox (parent, data, options, defaultOptions) {
  4718. this.props = {
  4719. dot: {
  4720. left: 0,
  4721. top: 0,
  4722. width: 0,
  4723. height: 0
  4724. },
  4725. line: {
  4726. top: 0,
  4727. left: 0,
  4728. width: 0,
  4729. height: 0
  4730. }
  4731. };
  4732. Item.call(this, parent, data, options, defaultOptions);
  4733. }
  4734. ItemBox.prototype = new Item (null, null);
  4735. /**
  4736. * Select the item
  4737. * @override
  4738. */
  4739. ItemBox.prototype.select = function select() {
  4740. this.selected = true;
  4741. // TODO: select and unselect
  4742. };
  4743. /**
  4744. * Unselect the item
  4745. * @override
  4746. */
  4747. ItemBox.prototype.unselect = function unselect() {
  4748. this.selected = false;
  4749. // TODO: select and unselect
  4750. };
  4751. /**
  4752. * Repaint the item
  4753. * @return {Boolean} changed
  4754. */
  4755. ItemBox.prototype.repaint = function repaint() {
  4756. // TODO: make an efficient repaint
  4757. var changed = false;
  4758. var dom = this.dom;
  4759. if (!dom) {
  4760. this._create();
  4761. dom = this.dom;
  4762. changed = true;
  4763. }
  4764. if (dom) {
  4765. if (!this.parent) {
  4766. throw new Error('Cannot repaint item: no parent attached');
  4767. }
  4768. var foreground = this.parent.getForeground();
  4769. if (!foreground) {
  4770. throw new Error('Cannot repaint time axis: ' +
  4771. 'parent has no foreground container element');
  4772. }
  4773. var background = this.parent.getBackground();
  4774. if (!background) {
  4775. throw new Error('Cannot repaint time axis: ' +
  4776. 'parent has no background container element');
  4777. }
  4778. var axis = this.parent.getAxis();
  4779. if (!background) {
  4780. throw new Error('Cannot repaint time axis: ' +
  4781. 'parent has no axis container element');
  4782. }
  4783. if (!dom.box.parentNode) {
  4784. foreground.appendChild(dom.box);
  4785. changed = true;
  4786. }
  4787. if (!dom.line.parentNode) {
  4788. background.appendChild(dom.line);
  4789. changed = true;
  4790. }
  4791. if (!dom.dot.parentNode) {
  4792. axis.appendChild(dom.dot);
  4793. changed = true;
  4794. }
  4795. // update contents
  4796. if (this.data.content != this.content) {
  4797. this.content = this.data.content;
  4798. if (this.content instanceof Element) {
  4799. dom.content.innerHTML = '';
  4800. dom.content.appendChild(this.content);
  4801. }
  4802. else if (this.data.content != undefined) {
  4803. dom.content.innerHTML = this.content;
  4804. }
  4805. else {
  4806. throw new Error('Property "content" missing in item ' + this.data.id);
  4807. }
  4808. changed = true;
  4809. }
  4810. // update class
  4811. var className = (this.data.className? ' ' + this.data.className : '') +
  4812. (this.selected ? ' selected' : '');
  4813. if (this.className != className) {
  4814. this.className = className;
  4815. dom.box.className = 'item box' + className;
  4816. dom.line.className = 'item line' + className;
  4817. dom.dot.className = 'item dot' + className;
  4818. changed = true;
  4819. }
  4820. }
  4821. return changed;
  4822. };
  4823. /**
  4824. * Show the item in the DOM (when not already visible). The items DOM will
  4825. * be created when needed.
  4826. * @return {Boolean} changed
  4827. */
  4828. ItemBox.prototype.show = function show() {
  4829. if (!this.dom || !this.dom.box.parentNode) {
  4830. return this.repaint();
  4831. }
  4832. else {
  4833. return false;
  4834. }
  4835. };
  4836. /**
  4837. * Hide the item from the DOM (when visible)
  4838. * @return {Boolean} changed
  4839. */
  4840. ItemBox.prototype.hide = function hide() {
  4841. var changed = false,
  4842. dom = this.dom;
  4843. if (dom) {
  4844. if (dom.box.parentNode) {
  4845. dom.box.parentNode.removeChild(dom.box);
  4846. changed = true;
  4847. }
  4848. if (dom.line.parentNode) {
  4849. dom.line.parentNode.removeChild(dom.line);
  4850. }
  4851. if (dom.dot.parentNode) {
  4852. dom.dot.parentNode.removeChild(dom.dot);
  4853. }
  4854. }
  4855. return changed;
  4856. };
  4857. /**
  4858. * Reflow the item: calculate its actual size and position from the DOM
  4859. * @return {boolean} resized returns true if the axis is resized
  4860. * @override
  4861. */
  4862. ItemBox.prototype.reflow = function reflow() {
  4863. var changed = 0,
  4864. update,
  4865. dom,
  4866. props,
  4867. options,
  4868. margin,
  4869. start,
  4870. align,
  4871. orientation,
  4872. top,
  4873. left,
  4874. data,
  4875. range;
  4876. if (this.data.start == undefined) {
  4877. throw new Error('Property "start" missing in item ' + this.data.id);
  4878. }
  4879. data = this.data;
  4880. range = this.parent && this.parent.range;
  4881. if (data && range) {
  4882. // TODO: account for the width of the item
  4883. var interval = (range.end - range.start);
  4884. this.visible = (data.start > range.start - interval) && (data.start < range.end + interval);
  4885. }
  4886. else {
  4887. this.visible = false;
  4888. }
  4889. if (this.visible) {
  4890. dom = this.dom;
  4891. if (dom) {
  4892. update = util.updateProperty;
  4893. props = this.props;
  4894. options = this.options;
  4895. start = this.parent.toScreen(this.data.start);
  4896. align = options.align || this.defaultOptions.align;
  4897. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  4898. orientation = options.orientation || this.defaultOptions.orientation;
  4899. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  4900. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  4901. changed += update(props.line, 'width', dom.line.offsetWidth);
  4902. changed += update(props.line, 'height', dom.line.offsetHeight);
  4903. changed += update(props.line, 'top', dom.line.offsetTop);
  4904. changed += update(this, 'width', dom.box.offsetWidth);
  4905. changed += update(this, 'height', dom.box.offsetHeight);
  4906. if (align == 'right') {
  4907. left = start - this.width;
  4908. }
  4909. else if (align == 'left') {
  4910. left = start;
  4911. }
  4912. else {
  4913. // default or 'center'
  4914. left = start - this.width / 2;
  4915. }
  4916. changed += update(this, 'left', left);
  4917. changed += update(props.line, 'left', start - props.line.width / 2);
  4918. changed += update(props.dot, 'left', start - props.dot.width / 2);
  4919. changed += update(props.dot, 'top', -props.dot.height / 2);
  4920. if (orientation == 'top') {
  4921. top = margin;
  4922. changed += update(this, 'top', top);
  4923. }
  4924. else {
  4925. // default or 'bottom'
  4926. var parentHeight = this.parent.height;
  4927. top = parentHeight - this.height - margin;
  4928. changed += update(this, 'top', top);
  4929. }
  4930. }
  4931. else {
  4932. changed += 1;
  4933. }
  4934. }
  4935. return (changed > 0);
  4936. };
  4937. /**
  4938. * Create an items DOM
  4939. * @private
  4940. */
  4941. ItemBox.prototype._create = function _create() {
  4942. var dom = this.dom;
  4943. if (!dom) {
  4944. this.dom = dom = {};
  4945. // create the box
  4946. dom.box = document.createElement('DIV');
  4947. // className is updated in repaint()
  4948. // contents box (inside the background box). used for making margins
  4949. dom.content = document.createElement('DIV');
  4950. dom.content.className = 'content';
  4951. dom.box.appendChild(dom.content);
  4952. // line to axis
  4953. dom.line = document.createElement('DIV');
  4954. dom.line.className = 'line';
  4955. // dot on axis
  4956. dom.dot = document.createElement('DIV');
  4957. dom.dot.className = 'dot';
  4958. }
  4959. };
  4960. /**
  4961. * Reposition the item, recalculate its left, top, and width, using the current
  4962. * range and size of the items itemset
  4963. * @override
  4964. */
  4965. ItemBox.prototype.reposition = function reposition() {
  4966. var dom = this.dom,
  4967. props = this.props,
  4968. orientation = this.options.orientation || this.defaultOptions.orientation;
  4969. if (dom) {
  4970. var box = dom.box,
  4971. line = dom.line,
  4972. dot = dom.dot;
  4973. box.style.left = this.left + 'px';
  4974. box.style.top = this.top + 'px';
  4975. line.style.left = props.line.left + 'px';
  4976. if (orientation == 'top') {
  4977. line.style.top = 0 + 'px';
  4978. line.style.height = this.top + 'px';
  4979. }
  4980. else {
  4981. // orientation 'bottom'
  4982. line.style.top = (this.top + this.height) + 'px';
  4983. line.style.height = Math.max(this.parent.height - this.top - this.height +
  4984. this.props.dot.height / 2, 0) + 'px';
  4985. }
  4986. dot.style.left = props.dot.left + 'px';
  4987. dot.style.top = props.dot.top + 'px';
  4988. }
  4989. };
  4990. /**
  4991. * @constructor ItemPoint
  4992. * @extends Item
  4993. * @param {ItemSet} parent
  4994. * @param {Object} data Object containing parameters start
  4995. * content, className.
  4996. * @param {Object} [options] Options to set initial property values
  4997. * @param {Object} [defaultOptions] default options
  4998. * // TODO: describe available options
  4999. */
  5000. function ItemPoint (parent, data, options, defaultOptions) {
  5001. this.props = {
  5002. dot: {
  5003. top: 0,
  5004. width: 0,
  5005. height: 0
  5006. },
  5007. content: {
  5008. height: 0,
  5009. marginLeft: 0
  5010. }
  5011. };
  5012. Item.call(this, parent, data, options, defaultOptions);
  5013. }
  5014. ItemPoint.prototype = new Item (null, null);
  5015. /**
  5016. * Select the item
  5017. * @override
  5018. */
  5019. ItemPoint.prototype.select = function select() {
  5020. this.selected = true;
  5021. // TODO: select and unselect
  5022. };
  5023. /**
  5024. * Unselect the item
  5025. * @override
  5026. */
  5027. ItemPoint.prototype.unselect = function unselect() {
  5028. this.selected = false;
  5029. // TODO: select and unselect
  5030. };
  5031. /**
  5032. * Repaint the item
  5033. * @return {Boolean} changed
  5034. */
  5035. ItemPoint.prototype.repaint = function repaint() {
  5036. // TODO: make an efficient repaint
  5037. var changed = false;
  5038. var dom = this.dom;
  5039. if (!dom) {
  5040. this._create();
  5041. dom = this.dom;
  5042. changed = true;
  5043. }
  5044. if (dom) {
  5045. if (!this.parent) {
  5046. throw new Error('Cannot repaint item: no parent attached');
  5047. }
  5048. var foreground = this.parent.getForeground();
  5049. if (!foreground) {
  5050. throw new Error('Cannot repaint time axis: ' +
  5051. 'parent has no foreground container element');
  5052. }
  5053. if (!dom.point.parentNode) {
  5054. foreground.appendChild(dom.point);
  5055. foreground.appendChild(dom.point);
  5056. changed = true;
  5057. }
  5058. // update contents
  5059. if (this.data.content != this.content) {
  5060. this.content = this.data.content;
  5061. if (this.content instanceof Element) {
  5062. dom.content.innerHTML = '';
  5063. dom.content.appendChild(this.content);
  5064. }
  5065. else if (this.data.content != undefined) {
  5066. dom.content.innerHTML = this.content;
  5067. }
  5068. else {
  5069. throw new Error('Property "content" missing in item ' + this.data.id);
  5070. }
  5071. changed = true;
  5072. }
  5073. // update class
  5074. var className = (this.data.className? ' ' + this.data.className : '') +
  5075. (this.selected ? ' selected' : '');
  5076. if (this.className != className) {
  5077. this.className = className;
  5078. dom.point.className = 'item point' + className;
  5079. changed = true;
  5080. }
  5081. }
  5082. return changed;
  5083. };
  5084. /**
  5085. * Show the item in the DOM (when not already visible). The items DOM will
  5086. * be created when needed.
  5087. * @return {Boolean} changed
  5088. */
  5089. ItemPoint.prototype.show = function show() {
  5090. if (!this.dom || !this.dom.point.parentNode) {
  5091. return this.repaint();
  5092. }
  5093. else {
  5094. return false;
  5095. }
  5096. };
  5097. /**
  5098. * Hide the item from the DOM (when visible)
  5099. * @return {Boolean} changed
  5100. */
  5101. ItemPoint.prototype.hide = function hide() {
  5102. var changed = false,
  5103. dom = this.dom;
  5104. if (dom) {
  5105. if (dom.point.parentNode) {
  5106. dom.point.parentNode.removeChild(dom.point);
  5107. changed = true;
  5108. }
  5109. }
  5110. return changed;
  5111. };
  5112. /**
  5113. * Reflow the item: calculate its actual size from the DOM
  5114. * @return {boolean} resized returns true if the axis is resized
  5115. * @override
  5116. */
  5117. ItemPoint.prototype.reflow = function reflow() {
  5118. var changed = 0,
  5119. update,
  5120. dom,
  5121. props,
  5122. options,
  5123. margin,
  5124. orientation,
  5125. start,
  5126. top,
  5127. data,
  5128. range;
  5129. if (this.data.start == undefined) {
  5130. throw new Error('Property "start" missing in item ' + this.data.id);
  5131. }
  5132. data = this.data;
  5133. range = this.parent && this.parent.range;
  5134. if (data && range) {
  5135. // TODO: account for the width of the item
  5136. var interval = (range.end - range.start);
  5137. this.visible = (data.start > range.start - interval) && (data.start < range.end);
  5138. }
  5139. else {
  5140. this.visible = false;
  5141. }
  5142. if (this.visible) {
  5143. dom = this.dom;
  5144. if (dom) {
  5145. update = util.updateProperty;
  5146. props = this.props;
  5147. options = this.options;
  5148. orientation = options.orientation || this.defaultOptions.orientation;
  5149. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5150. start = this.parent.toScreen(this.data.start);
  5151. changed += update(this, 'width', dom.point.offsetWidth);
  5152. changed += update(this, 'height', dom.point.offsetHeight);
  5153. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5154. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5155. changed += update(props.content, 'height', dom.content.offsetHeight);
  5156. if (orientation == 'top') {
  5157. top = margin;
  5158. }
  5159. else {
  5160. // default or 'bottom'
  5161. var parentHeight = this.parent.height;
  5162. top = Math.max(parentHeight - this.height - margin, 0);
  5163. }
  5164. changed += update(this, 'top', top);
  5165. changed += update(this, 'left', start - props.dot.width / 2);
  5166. changed += update(props.content, 'marginLeft', 1.5 * props.dot.width);
  5167. //changed += update(props.content, 'marginRight', 0.5 * props.dot.width); // TODO
  5168. changed += update(props.dot, 'top', (this.height - props.dot.height) / 2);
  5169. }
  5170. else {
  5171. changed += 1;
  5172. }
  5173. }
  5174. return (changed > 0);
  5175. };
  5176. /**
  5177. * Create an items DOM
  5178. * @private
  5179. */
  5180. ItemPoint.prototype._create = function _create() {
  5181. var dom = this.dom;
  5182. if (!dom) {
  5183. this.dom = dom = {};
  5184. // background box
  5185. dom.point = document.createElement('div');
  5186. // className is updated in repaint()
  5187. // contents box, right from the dot
  5188. dom.content = document.createElement('div');
  5189. dom.content.className = 'content';
  5190. dom.point.appendChild(dom.content);
  5191. // dot at start
  5192. dom.dot = document.createElement('div');
  5193. dom.dot.className = 'dot';
  5194. dom.point.appendChild(dom.dot);
  5195. }
  5196. };
  5197. /**
  5198. * Reposition the item, recalculate its left, top, and width, using the current
  5199. * range and size of the items itemset
  5200. * @override
  5201. */
  5202. ItemPoint.prototype.reposition = function reposition() {
  5203. var dom = this.dom,
  5204. props = this.props;
  5205. if (dom) {
  5206. dom.point.style.top = this.top + 'px';
  5207. dom.point.style.left = this.left + 'px';
  5208. dom.content.style.marginLeft = props.content.marginLeft + 'px';
  5209. //dom.content.style.marginRight = props.content.marginRight + 'px'; // TODO
  5210. dom.dot.style.top = props.dot.top + 'px';
  5211. }
  5212. };
  5213. /**
  5214. * @constructor ItemRange
  5215. * @extends Item
  5216. * @param {ItemSet} parent
  5217. * @param {Object} data Object containing parameters start, end
  5218. * content, className.
  5219. * @param {Object} [options] Options to set initial property values
  5220. * @param {Object} [defaultOptions] default options
  5221. * // TODO: describe available options
  5222. */
  5223. function ItemRange (parent, data, options, defaultOptions) {
  5224. this.props = {
  5225. content: {
  5226. left: 0,
  5227. width: 0
  5228. }
  5229. };
  5230. Item.call(this, parent, data, options, defaultOptions);
  5231. }
  5232. ItemRange.prototype = new Item (null, null);
  5233. /**
  5234. * Select the item
  5235. * @override
  5236. */
  5237. ItemRange.prototype.select = function select() {
  5238. this.selected = true;
  5239. // TODO: select and unselect
  5240. };
  5241. /**
  5242. * Unselect the item
  5243. * @override
  5244. */
  5245. ItemRange.prototype.unselect = function unselect() {
  5246. this.selected = false;
  5247. // TODO: select and unselect
  5248. };
  5249. /**
  5250. * Repaint the item
  5251. * @return {Boolean} changed
  5252. */
  5253. ItemRange.prototype.repaint = function repaint() {
  5254. // TODO: make an efficient repaint
  5255. var changed = false;
  5256. var dom = this.dom;
  5257. if (!dom) {
  5258. this._create();
  5259. dom = this.dom;
  5260. changed = true;
  5261. }
  5262. if (dom) {
  5263. if (!this.parent) {
  5264. throw new Error('Cannot repaint item: no parent attached');
  5265. }
  5266. var foreground = this.parent.getForeground();
  5267. if (!foreground) {
  5268. throw new Error('Cannot repaint time axis: ' +
  5269. 'parent has no foreground container element');
  5270. }
  5271. if (!dom.box.parentNode) {
  5272. foreground.appendChild(dom.box);
  5273. changed = true;
  5274. }
  5275. // update content
  5276. if (this.data.content != this.content) {
  5277. this.content = this.data.content;
  5278. if (this.content instanceof Element) {
  5279. dom.content.innerHTML = '';
  5280. dom.content.appendChild(this.content);
  5281. }
  5282. else if (this.data.content != undefined) {
  5283. dom.content.innerHTML = this.content;
  5284. }
  5285. else {
  5286. throw new Error('Property "content" missing in item ' + this.data.id);
  5287. }
  5288. changed = true;
  5289. }
  5290. // update class
  5291. var className = this.data.className ? ('' + this.data.className) : '';
  5292. if (this.className != className) {
  5293. this.className = className;
  5294. dom.box.className = 'item range' + className;
  5295. changed = true;
  5296. }
  5297. }
  5298. return changed;
  5299. };
  5300. /**
  5301. * Show the item in the DOM (when not already visible). The items DOM will
  5302. * be created when needed.
  5303. * @return {Boolean} changed
  5304. */
  5305. ItemRange.prototype.show = function show() {
  5306. if (!this.dom || !this.dom.box.parentNode) {
  5307. return this.repaint();
  5308. }
  5309. else {
  5310. return false;
  5311. }
  5312. };
  5313. /**
  5314. * Hide the item from the DOM (when visible)
  5315. * @return {Boolean} changed
  5316. */
  5317. ItemRange.prototype.hide = function hide() {
  5318. var changed = false,
  5319. dom = this.dom;
  5320. if (dom) {
  5321. if (dom.box.parentNode) {
  5322. dom.box.parentNode.removeChild(dom.box);
  5323. changed = true;
  5324. }
  5325. }
  5326. return changed;
  5327. };
  5328. /**
  5329. * Reflow the item: calculate its actual size from the DOM
  5330. * @return {boolean} resized returns true if the axis is resized
  5331. * @override
  5332. */
  5333. ItemRange.prototype.reflow = function reflow() {
  5334. var changed = 0,
  5335. dom,
  5336. props,
  5337. options,
  5338. margin,
  5339. padding,
  5340. parent,
  5341. start,
  5342. end,
  5343. data,
  5344. range,
  5345. update,
  5346. box,
  5347. parentWidth,
  5348. contentLeft,
  5349. orientation,
  5350. top;
  5351. if (this.data.start == undefined) {
  5352. throw new Error('Property "start" missing in item ' + this.data.id);
  5353. }
  5354. if (this.data.end == undefined) {
  5355. throw new Error('Property "end" missing in item ' + this.data.id);
  5356. }
  5357. data = this.data;
  5358. range = this.parent && this.parent.range;
  5359. if (data && range) {
  5360. // TODO: account for the width of the item. Take some margin
  5361. this.visible = (data.start < range.end) && (data.end > range.start);
  5362. }
  5363. else {
  5364. this.visible = false;
  5365. }
  5366. if (this.visible) {
  5367. dom = this.dom;
  5368. if (dom) {
  5369. props = this.props;
  5370. options = this.options;
  5371. parent = this.parent;
  5372. start = parent.toScreen(this.data.start);
  5373. end = parent.toScreen(this.data.end);
  5374. update = util.updateProperty;
  5375. box = dom.box;
  5376. parentWidth = parent.width;
  5377. orientation = options.orientation || this.defaultOptions.orientation;
  5378. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5379. padding = options.padding || this.defaultOptions.padding;
  5380. changed += update(props.content, 'width', dom.content.offsetWidth);
  5381. changed += update(this, 'height', box.offsetHeight);
  5382. // limit the width of the this, as browsers cannot draw very wide divs
  5383. if (start < -parentWidth) {
  5384. start = -parentWidth;
  5385. }
  5386. if (end > 2 * parentWidth) {
  5387. end = 2 * parentWidth;
  5388. }
  5389. // when range exceeds left of the window, position the contents at the left of the visible area
  5390. if (start < 0) {
  5391. contentLeft = Math.min(-start,
  5392. (end - start - props.content.width - 2 * padding));
  5393. // TODO: remove the need for options.padding. it's terrible.
  5394. }
  5395. else {
  5396. contentLeft = 0;
  5397. }
  5398. changed += update(props.content, 'left', contentLeft);
  5399. if (orientation == 'top') {
  5400. top = margin;
  5401. changed += update(this, 'top', top);
  5402. }
  5403. else {
  5404. // default or 'bottom'
  5405. top = parent.height - this.height - margin;
  5406. changed += update(this, 'top', top);
  5407. }
  5408. changed += update(this, 'left', start);
  5409. changed += update(this, 'width', Math.max(end - start, 1)); // TODO: reckon with border width;
  5410. }
  5411. else {
  5412. changed += 1;
  5413. }
  5414. }
  5415. return (changed > 0);
  5416. };
  5417. /**
  5418. * Create an items DOM
  5419. * @private
  5420. */
  5421. ItemRange.prototype._create = function _create() {
  5422. var dom = this.dom;
  5423. if (!dom) {
  5424. this.dom = dom = {};
  5425. // background box
  5426. dom.box = document.createElement('div');
  5427. // className is updated in repaint()
  5428. // contents box
  5429. dom.content = document.createElement('div');
  5430. dom.content.className = 'content';
  5431. dom.box.appendChild(dom.content);
  5432. }
  5433. };
  5434. /**
  5435. * Reposition the item, recalculate its left, top, and width, using the current
  5436. * range and size of the items itemset
  5437. * @override
  5438. */
  5439. ItemRange.prototype.reposition = function reposition() {
  5440. var dom = this.dom,
  5441. props = this.props;
  5442. if (dom) {
  5443. dom.box.style.top = this.top + 'px';
  5444. dom.box.style.left = this.left + 'px';
  5445. dom.box.style.width = this.width + 'px';
  5446. dom.content.style.left = props.content.left + 'px';
  5447. }
  5448. };
  5449. /**
  5450. * @constructor Group
  5451. * @param {GroupSet} parent
  5452. * @param {Number | String} groupId
  5453. * @param {Object} [options] Options to set initial property values
  5454. * // TODO: describe available options
  5455. * @extends Component
  5456. */
  5457. function Group (parent, groupId, options) {
  5458. this.id = util.randomUUID();
  5459. this.parent = parent;
  5460. this.groupId = groupId;
  5461. this.itemsData = null; // DataSet
  5462. this.itemset = null; // ItemSet
  5463. this.options = options || {};
  5464. this.options.top = 0;
  5465. this.props = {
  5466. label: {
  5467. width: 0,
  5468. height: 0
  5469. }
  5470. };
  5471. this.top = 0;
  5472. this.left = 0;
  5473. this.width = 0;
  5474. this.height = 0;
  5475. }
  5476. Group.prototype = new Component();
  5477. // TODO: comment
  5478. Group.prototype.setOptions = Component.prototype.setOptions;
  5479. /**
  5480. * Get the container element of the panel, which can be used by a child to
  5481. * add its own widgets.
  5482. * @returns {HTMLElement} container
  5483. */
  5484. Group.prototype.getContainer = function () {
  5485. return this.parent.getContainer();
  5486. };
  5487. /**
  5488. * Set item set for the group. The group will create a view on the itemset,
  5489. * filtered by the groups id.
  5490. * @param {DataSet | DataView} items
  5491. */
  5492. Group.prototype.setItems = function setItems(items) {
  5493. if (this.itemset) {
  5494. // remove current item set
  5495. this.itemset.hide();
  5496. this.itemset.setItems();
  5497. this.parent.controller.remove(this.itemset);
  5498. this.itemset = null;
  5499. }
  5500. if (items) {
  5501. var groupId = this.groupId;
  5502. var itemsetOptions = Object.create(this.options);
  5503. this.itemset = new ItemSet(this, null, itemsetOptions);
  5504. this.itemset.setRange(this.parent.range);
  5505. this.view = new DataView(items, {
  5506. filter: function (item) {
  5507. return item.group == groupId;
  5508. }
  5509. });
  5510. this.itemset.setItems(this.view);
  5511. this.parent.controller.add(this.itemset);
  5512. }
  5513. };
  5514. /**
  5515. * Repaint the item
  5516. * @return {Boolean} changed
  5517. */
  5518. Group.prototype.repaint = function repaint() {
  5519. return false;
  5520. };
  5521. /**
  5522. * Reflow the item
  5523. * @return {Boolean} resized
  5524. */
  5525. Group.prototype.reflow = function reflow() {
  5526. var changed = 0,
  5527. update = util.updateProperty;
  5528. changed += update(this, 'top', this.itemset ? this.itemset.top : 0);
  5529. changed += update(this, 'height', this.itemset ? this.itemset.height : 0);
  5530. // TODO: reckon with the height of the group label
  5531. if (this.label) {
  5532. var inner = this.label.firstChild;
  5533. changed += update(this.props.label, 'width', inner.clientWidth);
  5534. changed += update(this.props.label, 'height', inner.clientHeight);
  5535. }
  5536. else {
  5537. changed += update(this.props.label, 'width', 0);
  5538. changed += update(this.props.label, 'height', 0);
  5539. }
  5540. return (changed > 0);
  5541. };
  5542. /**
  5543. * An GroupSet holds a set of groups
  5544. * @param {Component} parent
  5545. * @param {Component[]} [depends] Components on which this components depends
  5546. * (except for the parent)
  5547. * @param {Object} [options] See GroupSet.setOptions for the available
  5548. * options.
  5549. * @constructor GroupSet
  5550. * @extends Panel
  5551. */
  5552. function GroupSet(parent, depends, options) {
  5553. this.id = util.randomUUID();
  5554. this.parent = parent;
  5555. this.depends = depends;
  5556. this.options = options || {};
  5557. this.range = null; // Range or Object {start: number, end: number}
  5558. this.itemsData = null; // DataSet with items
  5559. this.groupsData = null; // DataSet with groups
  5560. this.groups = {}; // map with groups
  5561. this.dom = {};
  5562. this.props = {
  5563. labels: {
  5564. width: 0
  5565. }
  5566. };
  5567. // TODO: implement right orientation of the labels
  5568. // changes in groups are queued key/value map containing id/action
  5569. this.queue = {};
  5570. var me = this;
  5571. this.listeners = {
  5572. 'add': function (event, params) {
  5573. me._onAdd(params.items);
  5574. },
  5575. 'update': function (event, params) {
  5576. me._onUpdate(params.items);
  5577. },
  5578. 'remove': function (event, params) {
  5579. me._onRemove(params.items);
  5580. }
  5581. };
  5582. }
  5583. GroupSet.prototype = new Panel();
  5584. /**
  5585. * Set options for the GroupSet. Existing options will be extended/overwritten.
  5586. * @param {Object} [options] The following options are available:
  5587. * {String | function} groupsOrder
  5588. * TODO: describe options
  5589. */
  5590. GroupSet.prototype.setOptions = Component.prototype.setOptions;
  5591. GroupSet.prototype.setRange = function (range) {
  5592. // TODO: implement setRange
  5593. };
  5594. /**
  5595. * Set items
  5596. * @param {vis.DataSet | null} items
  5597. */
  5598. GroupSet.prototype.setItems = function setItems(items) {
  5599. this.itemsData = items;
  5600. for (var id in this.groups) {
  5601. if (this.groups.hasOwnProperty(id)) {
  5602. var group = this.groups[id];
  5603. group.setItems(items);
  5604. }
  5605. }
  5606. };
  5607. /**
  5608. * Get items
  5609. * @return {vis.DataSet | null} items
  5610. */
  5611. GroupSet.prototype.getItems = function getItems() {
  5612. return this.itemsData;
  5613. };
  5614. /**
  5615. * Set range (start and end).
  5616. * @param {Range | Object} range A Range or an object containing start and end.
  5617. */
  5618. GroupSet.prototype.setRange = function setRange(range) {
  5619. this.range = range;
  5620. };
  5621. /**
  5622. * Set groups
  5623. * @param {vis.DataSet} groups
  5624. */
  5625. GroupSet.prototype.setGroups = function setGroups(groups) {
  5626. var me = this,
  5627. ids;
  5628. // unsubscribe from current dataset
  5629. if (this.groupsData) {
  5630. util.forEach(this.listeners, function (callback, event) {
  5631. me.groupsData.unsubscribe(event, callback);
  5632. });
  5633. // remove all drawn groups
  5634. ids = this.groupsData.getIds();
  5635. this._onRemove(ids);
  5636. }
  5637. // replace the dataset
  5638. if (!groups) {
  5639. this.groupsData = null;
  5640. }
  5641. else if (groups instanceof DataSet) {
  5642. this.groupsData = groups;
  5643. }
  5644. else {
  5645. this.groupsData = new DataSet({
  5646. convert: {
  5647. start: 'Date',
  5648. end: 'Date'
  5649. }
  5650. });
  5651. this.groupsData.add(groups);
  5652. }
  5653. if (this.groupsData) {
  5654. // subscribe to new dataset
  5655. var id = this.id;
  5656. util.forEach(this.listeners, function (callback, event) {
  5657. me.groupsData.subscribe(event, callback, id);
  5658. });
  5659. // draw all new groups
  5660. ids = this.groupsData.getIds();
  5661. this._onAdd(ids);
  5662. }
  5663. };
  5664. /**
  5665. * Get groups
  5666. * @return {vis.DataSet | null} groups
  5667. */
  5668. GroupSet.prototype.getGroups = function getGroups() {
  5669. return this.groupsData;
  5670. };
  5671. /**
  5672. * Repaint the component
  5673. * @return {Boolean} changed
  5674. */
  5675. GroupSet.prototype.repaint = function repaint() {
  5676. var changed = 0,
  5677. i, id, group, label,
  5678. update = util.updateProperty,
  5679. asSize = util.option.asSize,
  5680. asElement = util.option.asElement,
  5681. options = this.options,
  5682. frame = this.dom.frame,
  5683. labels = this.dom.labels;
  5684. // create frame
  5685. if (!this.parent) {
  5686. throw new Error('Cannot repaint groupset: no parent attached');
  5687. }
  5688. var parentContainer = this.parent.getContainer();
  5689. if (!parentContainer) {
  5690. throw new Error('Cannot repaint groupset: parent has no container element');
  5691. }
  5692. if (!frame) {
  5693. frame = document.createElement('div');
  5694. frame.className = 'groupset';
  5695. this.dom.frame = frame;
  5696. var className = options.className;
  5697. if (className) {
  5698. util.addClassName(frame, util.option.asString(className));
  5699. }
  5700. changed += 1;
  5701. }
  5702. if (!frame.parentNode) {
  5703. parentContainer.appendChild(frame);
  5704. changed += 1;
  5705. }
  5706. // create labels
  5707. var labelContainer = asElement(options.labelContainer);
  5708. if (!labelContainer) {
  5709. throw new Error('Cannot repaint groupset: option "labelContainer" not defined');
  5710. }
  5711. if (!labels) {
  5712. labels = document.createElement('div');
  5713. labels.className = 'labels';
  5714. //frame.appendChild(labels);
  5715. this.dom.labels = labels;
  5716. }
  5717. if (!labels.parentNode || labels.parentNode != labelContainer) {
  5718. if (labels.parentNode) {
  5719. labels.parentNode.removeChild(labels.parentNode);
  5720. }
  5721. labelContainer.appendChild(labels);
  5722. }
  5723. // reposition frame
  5724. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  5725. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  5726. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  5727. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  5728. // reposition labels
  5729. changed += update(labels.style, 'top', asSize(options.top, '0px'));
  5730. var me = this,
  5731. queue = this.queue,
  5732. groups = this.groups,
  5733. groupsData = this.groupsData;
  5734. // show/hide added/changed/removed groups
  5735. var ids = Object.keys(queue);
  5736. if (ids.length) {
  5737. ids.forEach(function (id) {
  5738. var action = queue[id];
  5739. var group = groups[id];
  5740. //noinspection FallthroughInSwitchStatementJS
  5741. switch (action) {
  5742. case 'add':
  5743. case 'update':
  5744. if (!group) {
  5745. var groupOptions = Object.create(me.options);
  5746. group = new Group(me, id, groupOptions);
  5747. group.setItems(me.itemsData); // attach items data
  5748. groups[id] = group;
  5749. me.controller.add(group);
  5750. }
  5751. // TODO: update group data
  5752. group.data = groupsData.get(id);
  5753. delete queue[id];
  5754. break;
  5755. case 'remove':
  5756. if (group) {
  5757. group.setItems(); // detach items data
  5758. delete groups[id];
  5759. me.controller.remove(group);
  5760. }
  5761. // update lists
  5762. delete queue[id];
  5763. break;
  5764. default:
  5765. console.log('Error: unknown action "' + action + '"');
  5766. }
  5767. });
  5768. // the groupset depends on each of the groups
  5769. //this.depends = this.groups; // TODO: gives a circular reference through the parent
  5770. // TODO: apply dependencies of the groupset
  5771. // update the top positions of the groups in the correct order
  5772. var orderedGroups = this.groupsData.getIds({
  5773. order: this.options.groupsOrder
  5774. });
  5775. for (i = 0; i < orderedGroups.length; i++) {
  5776. (function (group, prevGroup) {
  5777. var top = 0;
  5778. if (prevGroup) {
  5779. top = function () {
  5780. // TODO: top must reckon with options.maxHeight
  5781. return prevGroup.top + prevGroup.height;
  5782. }
  5783. }
  5784. group.setOptions({
  5785. top: top
  5786. });
  5787. })(groups[orderedGroups[i]], groups[orderedGroups[i - 1]]);
  5788. }
  5789. // (re)create the labels
  5790. while (labels.firstChild) {
  5791. labels.removeChild(labels.firstChild);
  5792. }
  5793. for (i = 0; i < orderedGroups.length; i++) {
  5794. id = orderedGroups[i];
  5795. label = this._createLabel(id);
  5796. labels.appendChild(label);
  5797. }
  5798. changed++;
  5799. }
  5800. // reposition the labels
  5801. // TODO: labels are not displayed correctly when orientation=='top'
  5802. // TODO: width of labelPanel is not immediately updated on a change in groups
  5803. for (id in groups) {
  5804. if (groups.hasOwnProperty(id)) {
  5805. group = groups[id];
  5806. label = group.label;
  5807. if (label) {
  5808. label.style.top = group.top + 'px';
  5809. label.style.height = group.height + 'px';
  5810. }
  5811. }
  5812. }
  5813. return (changed > 0);
  5814. };
  5815. /**
  5816. * Create a label for group with given id
  5817. * @param {Number} id
  5818. * @return {Element} label
  5819. * @private
  5820. */
  5821. GroupSet.prototype._createLabel = function(id) {
  5822. var group = this.groups[id];
  5823. var label = document.createElement('div');
  5824. label.className = 'label';
  5825. var inner = document.createElement('div');
  5826. inner.className = 'inner';
  5827. label.appendChild(inner);
  5828. var content = group.data && group.data.content;
  5829. if (content instanceof Element) {
  5830. inner.appendChild(content);
  5831. }
  5832. else if (content != undefined) {
  5833. inner.innerHTML = content;
  5834. }
  5835. var className = group.data && group.data.className;
  5836. if (className) {
  5837. util.addClassName(label, className);
  5838. }
  5839. group.label = label; // TODO: not so nice, parking labels in the group this way!!!
  5840. return label;
  5841. };
  5842. /**
  5843. * Get container element
  5844. * @return {HTMLElement} container
  5845. */
  5846. GroupSet.prototype.getContainer = function getContainer() {
  5847. return this.dom.frame;
  5848. };
  5849. /**
  5850. * Get the width of the group labels
  5851. * @return {Number} width
  5852. */
  5853. GroupSet.prototype.getLabelsWidth = function getContainer() {
  5854. return this.props.labels.width;
  5855. };
  5856. /**
  5857. * Reflow the component
  5858. * @return {Boolean} resized
  5859. */
  5860. GroupSet.prototype.reflow = function reflow() {
  5861. var changed = 0,
  5862. id, group,
  5863. options = this.options,
  5864. update = util.updateProperty,
  5865. asNumber = util.option.asNumber,
  5866. asSize = util.option.asSize,
  5867. frame = this.dom.frame;
  5868. if (frame) {
  5869. var maxHeight = asNumber(options.maxHeight);
  5870. var fixedHeight = (asSize(options.height) != null);
  5871. var height;
  5872. if (fixedHeight) {
  5873. height = frame.offsetHeight;
  5874. }
  5875. else {
  5876. // height is not specified, calculate the sum of the height of all groups
  5877. height = 0;
  5878. for (id in this.groups) {
  5879. if (this.groups.hasOwnProperty(id)) {
  5880. group = this.groups[id];
  5881. height += group.height;
  5882. }
  5883. }
  5884. }
  5885. if (maxHeight != null) {
  5886. height = Math.min(height, maxHeight);
  5887. }
  5888. changed += update(this, 'height', height);
  5889. changed += update(this, 'top', frame.offsetTop);
  5890. changed += update(this, 'left', frame.offsetLeft);
  5891. changed += update(this, 'width', frame.offsetWidth);
  5892. }
  5893. // calculate the maximum width of the labels
  5894. var width = 0;
  5895. for (id in this.groups) {
  5896. if (this.groups.hasOwnProperty(id)) {
  5897. group = this.groups[id];
  5898. var labelWidth = group.props && group.props.label && group.props.label.width || 0;
  5899. width = Math.max(width, labelWidth);
  5900. }
  5901. }
  5902. changed += update(this.props.labels, 'width', width);
  5903. return (changed > 0);
  5904. };
  5905. /**
  5906. * Hide the component from the DOM
  5907. * @return {Boolean} changed
  5908. */
  5909. GroupSet.prototype.hide = function hide() {
  5910. if (this.dom.frame && this.dom.frame.parentNode) {
  5911. this.dom.frame.parentNode.removeChild(this.dom.frame);
  5912. return true;
  5913. }
  5914. else {
  5915. return false;
  5916. }
  5917. };
  5918. /**
  5919. * Show the component in the DOM (when not already visible).
  5920. * A repaint will be executed when the component is not visible
  5921. * @return {Boolean} changed
  5922. */
  5923. GroupSet.prototype.show = function show() {
  5924. if (!this.dom.frame || !this.dom.frame.parentNode) {
  5925. return this.repaint();
  5926. }
  5927. else {
  5928. return false;
  5929. }
  5930. };
  5931. /**
  5932. * Handle updated groups
  5933. * @param {Number[]} ids
  5934. * @private
  5935. */
  5936. GroupSet.prototype._onUpdate = function _onUpdate(ids) {
  5937. this._toQueue(ids, 'update');
  5938. };
  5939. /**
  5940. * Handle changed groups
  5941. * @param {Number[]} ids
  5942. * @private
  5943. */
  5944. GroupSet.prototype._onAdd = function _onAdd(ids) {
  5945. this._toQueue(ids, 'add');
  5946. };
  5947. /**
  5948. * Handle removed groups
  5949. * @param {Number[]} ids
  5950. * @private
  5951. */
  5952. GroupSet.prototype._onRemove = function _onRemove(ids) {
  5953. this._toQueue(ids, 'remove');
  5954. };
  5955. /**
  5956. * Put groups in the queue to be added/updated/remove
  5957. * @param {Number[]} ids
  5958. * @param {String} action can be 'add', 'update', 'remove'
  5959. */
  5960. GroupSet.prototype._toQueue = function _toQueue(ids, action) {
  5961. var queue = this.queue;
  5962. ids.forEach(function (id) {
  5963. queue[id] = action;
  5964. });
  5965. if (this.controller) {
  5966. //this.requestReflow();
  5967. this.requestRepaint();
  5968. }
  5969. };
  5970. /**
  5971. * Create a timeline visualization
  5972. * @param {HTMLElement} container
  5973. * @param {vis.DataSet | Array | DataTable} [items]
  5974. * @param {Object} [options] See Timeline.setOptions for the available options.
  5975. * @constructor
  5976. */
  5977. function Timeline (container, items, options) {
  5978. var me = this;
  5979. this.options = util.extend({
  5980. orientation: 'bottom',
  5981. min: null,
  5982. max: null,
  5983. zoomMin: 10, // milliseconds
  5984. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  5985. // moveable: true, // TODO: option moveable
  5986. // zoomable: true, // TODO: option zoomable
  5987. showMinorLabels: true,
  5988. showMajorLabels: true,
  5989. autoResize: false
  5990. }, options);
  5991. // controller
  5992. this.controller = new Controller();
  5993. // root panel
  5994. if (!container) {
  5995. throw new Error('No container element provided');
  5996. }
  5997. var rootOptions = Object.create(this.options);
  5998. rootOptions.height = function () {
  5999. if (me.options.height) {
  6000. // fixed height
  6001. return me.options.height;
  6002. }
  6003. else {
  6004. // auto height
  6005. return me.timeaxis.height + me.content.height;
  6006. }
  6007. };
  6008. this.rootPanel = new RootPanel(container, rootOptions);
  6009. this.controller.add(this.rootPanel);
  6010. // item panel
  6011. var itemOptions = Object.create(this.options);
  6012. itemOptions.left = function () {
  6013. return me.labelPanel.width;
  6014. };
  6015. itemOptions.width = function () {
  6016. return me.rootPanel.width - me.labelPanel.width;
  6017. };
  6018. itemOptions.top = null;
  6019. itemOptions.height = null;
  6020. this.itemPanel = new Panel(this.rootPanel, [], itemOptions);
  6021. this.controller.add(this.itemPanel);
  6022. // label panel
  6023. var labelOptions = Object.create(this.options);
  6024. labelOptions.top = null;
  6025. labelOptions.left = null;
  6026. labelOptions.height = null;
  6027. labelOptions.width = function () {
  6028. if (me.content && typeof me.content.getLabelsWidth === 'function') {
  6029. return me.content.getLabelsWidth();
  6030. }
  6031. else {
  6032. return 0;
  6033. }
  6034. };
  6035. this.labelPanel = new Panel(this.rootPanel, [], labelOptions);
  6036. this.controller.add(this.labelPanel);
  6037. // range
  6038. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  6039. this.range = new Range({
  6040. start: now.clone().add('days', -3).valueOf(),
  6041. end: now.clone().add('days', 4).valueOf()
  6042. });
  6043. // TODO: reckon with options moveable and zoomable
  6044. this.range.subscribe(this.rootPanel, 'move', 'horizontal');
  6045. this.range.subscribe(this.rootPanel, 'zoom', 'horizontal');
  6046. this.range.on('rangechange', function () {
  6047. var force = true;
  6048. me.controller.requestReflow(force);
  6049. });
  6050. this.range.on('rangechanged', function () {
  6051. var force = true;
  6052. me.controller.requestReflow(force);
  6053. });
  6054. // TODO: put the listeners in setOptions, be able to dynamically change with options moveable and zoomable
  6055. // time axis
  6056. var timeaxisOptions = Object.create(rootOptions);
  6057. timeaxisOptions.range = this.range;
  6058. timeaxisOptions.left = null;
  6059. timeaxisOptions.top = null;
  6060. timeaxisOptions.width = '100%';
  6061. timeaxisOptions.height = null;
  6062. this.timeaxis = new TimeAxis(this.itemPanel, [], timeaxisOptions);
  6063. this.timeaxis.setRange(this.range);
  6064. this.controller.add(this.timeaxis);
  6065. // create itemset or groupset
  6066. this.setGroups(null);
  6067. this.itemsData = null; // DataSet
  6068. this.groupsData = null; // DataSet
  6069. // set data
  6070. if (items) {
  6071. this.setItems(items);
  6072. }
  6073. }
  6074. /**
  6075. * Set options
  6076. * @param {Object} options TODO: describe the available options
  6077. */
  6078. Timeline.prototype.setOptions = function (options) {
  6079. if (options) {
  6080. util.extend(this.options, options);
  6081. }
  6082. this.controller.reflow();
  6083. this.controller.repaint();
  6084. };
  6085. /**
  6086. * Set items
  6087. * @param {vis.DataSet | Array | DataTable | null} items
  6088. */
  6089. Timeline.prototype.setItems = function(items) {
  6090. var initialLoad = (this.itemsData == null);
  6091. // convert to type DataSet when needed
  6092. var newItemSet;
  6093. if (!items) {
  6094. newItemSet = null;
  6095. }
  6096. else if (items instanceof DataSet) {
  6097. newItemSet = items;
  6098. }
  6099. if (!(items instanceof DataSet)) {
  6100. newItemSet = new DataSet({
  6101. convert: {
  6102. start: 'Date',
  6103. end: 'Date'
  6104. }
  6105. });
  6106. newItemSet.add(items);
  6107. }
  6108. // set items
  6109. this.itemsData = newItemSet;
  6110. this.content.setItems(newItemSet);
  6111. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  6112. // apply the data range as range
  6113. var dataRange = this.getItemRange();
  6114. // add 5% on both sides
  6115. var min = dataRange.min;
  6116. var max = dataRange.max;
  6117. if (min != null && max != null) {
  6118. var interval = (max.valueOf() - min.valueOf());
  6119. min = new Date(min.valueOf() - interval * 0.05);
  6120. max = new Date(max.valueOf() + interval * 0.05);
  6121. }
  6122. // override specified start and/or end date
  6123. if (this.options.start != undefined) {
  6124. min = new Date(this.options.start.valueOf());
  6125. }
  6126. if (this.options.end != undefined) {
  6127. max = new Date(this.options.end.valueOf());
  6128. }
  6129. // apply range if there is a min or max available
  6130. if (min != null || max != null) {
  6131. this.range.setRange(min, max);
  6132. }
  6133. }
  6134. };
  6135. /**
  6136. * Set groups
  6137. * @param {vis.DataSet | Array | DataTable} groups
  6138. */
  6139. Timeline.prototype.setGroups = function(groups) {
  6140. var me = this;
  6141. this.groupsData = groups;
  6142. // switch content type between ItemSet or GroupSet when needed
  6143. var type = this.groupsData ? GroupSet : ItemSet;
  6144. if (!(this.content instanceof type)) {
  6145. // remove old content set
  6146. if (this.content) {
  6147. this.content.hide();
  6148. if (this.content.setItems) {
  6149. this.content.setItems(); // disconnect from items
  6150. }
  6151. if (this.content.setGroups) {
  6152. this.content.setGroups(); // disconnect from groups
  6153. }
  6154. this.controller.remove(this.content);
  6155. }
  6156. // create new content set
  6157. var options = Object.create(this.options);
  6158. util.extend(options, {
  6159. top: function () {
  6160. if (me.options.orientation == 'top') {
  6161. return me.timeaxis.height;
  6162. }
  6163. else {
  6164. return me.itemPanel.height - me.timeaxis.height - me.content.height;
  6165. }
  6166. },
  6167. left: null,
  6168. width: '100%',
  6169. height: function () {
  6170. if (me.options.height) {
  6171. return me.itemPanel.height - me.timeaxis.height;
  6172. }
  6173. else {
  6174. return null;
  6175. }
  6176. },
  6177. maxHeight: function () {
  6178. if (me.options.maxHeight) {
  6179. if (!util.isNumber(me.options.maxHeight)) {
  6180. throw new TypeError('Number expected for property maxHeight');
  6181. }
  6182. return me.options.maxHeight - me.timeaxis.height;
  6183. }
  6184. else {
  6185. return null;
  6186. }
  6187. },
  6188. labelContainer: function () {
  6189. return me.labelPanel.getContainer();
  6190. }
  6191. });
  6192. this.content = new type(this.itemPanel, [this.timeaxis], options);
  6193. if (this.content.setRange) {
  6194. this.content.setRange(this.range);
  6195. }
  6196. if (this.content.setItems) {
  6197. this.content.setItems(this.itemsData);
  6198. }
  6199. if (this.content.setGroups) {
  6200. this.content.setGroups(this.groupsData);
  6201. }
  6202. this.controller.add(this.content);
  6203. }
  6204. };
  6205. /**
  6206. * Get the data range of the item set.
  6207. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  6208. * When no minimum is found, min==null
  6209. * When no maximum is found, max==null
  6210. */
  6211. Timeline.prototype.getItemRange = function getItemRange() {
  6212. // calculate min from start filed
  6213. var itemsData = this.itemsData,
  6214. min = null,
  6215. max = null;
  6216. if (itemsData) {
  6217. // calculate the minimum value of the field 'start'
  6218. var minItem = itemsData.min('start');
  6219. min = minItem ? minItem.start.valueOf() : null;
  6220. // calculate maximum value of fields 'start' and 'end'
  6221. var maxStartItem = itemsData.max('start');
  6222. if (maxStartItem) {
  6223. max = maxStartItem.start.valueOf();
  6224. }
  6225. var maxEndItem = itemsData.max('end');
  6226. if (maxEndItem) {
  6227. if (max == null) {
  6228. max = maxEndItem.end.valueOf();
  6229. }
  6230. else {
  6231. max = Math.max(max, maxEndItem.end.valueOf());
  6232. }
  6233. }
  6234. }
  6235. return {
  6236. min: (min != null) ? new Date(min) : null,
  6237. max: (max != null) ? new Date(max) : null
  6238. };
  6239. };
  6240. (function(exports) {
  6241. /**
  6242. * Parse a text source containing data in DOT language into a JSON object.
  6243. * The object contains two lists: one with nodes and one with edges.
  6244. *
  6245. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  6246. *
  6247. * @param {String} data Text containing a graph in DOT-notation
  6248. * @return {Object} graph An object containing two parameters:
  6249. * {Object[]} nodes
  6250. * {Object[]} edges
  6251. */
  6252. function parseDOT (data) {
  6253. dot = data;
  6254. return parseGraph();
  6255. }
  6256. // token types enumeration
  6257. var TOKENTYPE = {
  6258. NULL : 0,
  6259. DELIMITER : 1,
  6260. IDENTIFIER: 2,
  6261. UNKNOWN : 3
  6262. };
  6263. // map with all delimiters
  6264. var DELIMITERS = {
  6265. '{': true,
  6266. '}': true,
  6267. '[': true,
  6268. ']': true,
  6269. ';': true,
  6270. '=': true,
  6271. ',': true,
  6272. '->': true,
  6273. '--': true
  6274. };
  6275. var dot = ''; // current dot file
  6276. var index = 0; // current index in dot file
  6277. var c = ''; // current token character in expr
  6278. var token = ''; // current token
  6279. var tokenType = TOKENTYPE.NULL; // type of the token
  6280. /**
  6281. * Get the first character from the dot file.
  6282. * The character is stored into the char c. If the end of the dot file is
  6283. * reached, the function puts an empty string in c.
  6284. */
  6285. function first() {
  6286. index = 0;
  6287. c = dot.charAt(0);
  6288. }
  6289. /**
  6290. * Get the next character from the dot file.
  6291. * The character is stored into the char c. If the end of the dot file is
  6292. * reached, the function puts an empty string in c.
  6293. */
  6294. function next() {
  6295. index++;
  6296. c = dot.charAt(index);
  6297. }
  6298. /**
  6299. * Preview the next character from the dot file.
  6300. * @return {String} cNext
  6301. */
  6302. function nextPreview() {
  6303. return dot.charAt(index + 1);
  6304. }
  6305. /**
  6306. * Test whether given character is alphabetic or numeric
  6307. * @param {String} c
  6308. * @return {Boolean} isAlphaNumeric
  6309. */
  6310. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  6311. function isAlphaNumeric(c) {
  6312. return regexAlphaNumeric.test(c);
  6313. }
  6314. /**
  6315. * Merge all properties of object b into object b
  6316. * @param {Object} a
  6317. * @param {Object} b
  6318. * @return {Object} a
  6319. */
  6320. function merge (a, b) {
  6321. if (!a) {
  6322. a = {};
  6323. }
  6324. if (b) {
  6325. for (var name in b) {
  6326. if (b.hasOwnProperty(name)) {
  6327. a[name] = b[name];
  6328. }
  6329. }
  6330. }
  6331. return a;
  6332. }
  6333. /**
  6334. * Set a value in an object, where the provided parameter name can be a
  6335. * path with nested parameters. For example:
  6336. *
  6337. * var obj = {a: 2};
  6338. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  6339. *
  6340. * @param {Object} obj
  6341. * @param {String} path A parameter name or dot-separated parameter path,
  6342. * like "color.highlight.border".
  6343. * @param {*} value
  6344. */
  6345. function setValue(obj, path, value) {
  6346. var keys = path.split('.');
  6347. var o = obj;
  6348. while (keys.length) {
  6349. var key = keys.shift();
  6350. if (keys.length) {
  6351. // this isn't the end point
  6352. if (!o[key]) {
  6353. o[key] = {};
  6354. }
  6355. o = o[key];
  6356. }
  6357. else {
  6358. // this is the end point
  6359. o[key] = value;
  6360. }
  6361. }
  6362. }
  6363. /**
  6364. * Add a node to a graph object. If there is already a node with
  6365. * the same id, their attributes will be merged.
  6366. * @param {Object} graph
  6367. * @param {Object} node
  6368. */
  6369. function addNode(graph, node) {
  6370. var i, len;
  6371. var current = null;
  6372. // find root graph (in case of subgraph)
  6373. var graphs = [graph]; // list with all graphs from current graph to root graph
  6374. var root = graph;
  6375. while (root.parent) {
  6376. graphs.push(root.parent);
  6377. root = root.parent;
  6378. }
  6379. // find existing node (at root level) by its id
  6380. if (root.nodes) {
  6381. for (i = 0, len = root.nodes.length; i < len; i++) {
  6382. if (node.id === root.nodes[i].id) {
  6383. current = root.nodes[i];
  6384. break;
  6385. }
  6386. }
  6387. }
  6388. if (!current) {
  6389. // this is a new node
  6390. current = {
  6391. id: node.id
  6392. };
  6393. if (graph.node) {
  6394. // clone default attributes
  6395. current.attr = merge(current.attr, graph.node);
  6396. }
  6397. }
  6398. // add node to this (sub)graph and all its parent graphs
  6399. for (i = graphs.length - 1; i >= 0; i--) {
  6400. var g = graphs[i];
  6401. if (!g.nodes) {
  6402. g.nodes = [];
  6403. }
  6404. if (g.nodes.indexOf(current) == -1) {
  6405. g.nodes.push(current);
  6406. }
  6407. }
  6408. // merge attributes
  6409. if (node.attr) {
  6410. current.attr = merge(current.attr, node.attr);
  6411. }
  6412. }
  6413. /**
  6414. * Add an edge to a graph object
  6415. * @param {Object} graph
  6416. * @param {Object} edge
  6417. */
  6418. function addEdge(graph, edge) {
  6419. if (!graph.edges) {
  6420. graph.edges = [];
  6421. }
  6422. graph.edges.push(edge);
  6423. if (graph.edge) {
  6424. var attr = merge({}, graph.edge); // clone default attributes
  6425. edge.attr = merge(attr, edge.attr); // merge attributes
  6426. }
  6427. }
  6428. /**
  6429. * Create an edge to a graph object
  6430. * @param {Object} graph
  6431. * @param {String | Number | Object} from
  6432. * @param {String | Number | Object} to
  6433. * @param {String} type
  6434. * @param {Object | null} attr
  6435. * @return {Object} edge
  6436. */
  6437. function createEdge(graph, from, to, type, attr) {
  6438. var edge = {
  6439. from: from,
  6440. to: to,
  6441. type: type
  6442. };
  6443. if (graph.edge) {
  6444. edge.attr = merge({}, graph.edge); // clone default attributes
  6445. }
  6446. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  6447. return edge;
  6448. }
  6449. /**
  6450. * Get next token in the current dot file.
  6451. * The token and token type are available as token and tokenType
  6452. */
  6453. function getToken() {
  6454. tokenType = TOKENTYPE.NULL;
  6455. token = '';
  6456. // skip over whitespaces
  6457. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  6458. next();
  6459. }
  6460. do {
  6461. var isComment = false;
  6462. // skip comment
  6463. if (c == '#') {
  6464. // find the previous non-space character
  6465. var i = index - 1;
  6466. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  6467. i--;
  6468. }
  6469. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  6470. // the # is at the start of a line, this is indeed a line comment
  6471. while (c != '' && c != '\n') {
  6472. next();
  6473. }
  6474. isComment = true;
  6475. }
  6476. }
  6477. if (c == '/' && nextPreview() == '/') {
  6478. // skip line comment
  6479. while (c != '' && c != '\n') {
  6480. next();
  6481. }
  6482. isComment = true;
  6483. }
  6484. if (c == '/' && nextPreview() == '*') {
  6485. // skip block comment
  6486. while (c != '') {
  6487. if (c == '*' && nextPreview() == '/') {
  6488. // end of block comment found. skip these last two characters
  6489. next();
  6490. next();
  6491. break;
  6492. }
  6493. else {
  6494. next();
  6495. }
  6496. }
  6497. isComment = true;
  6498. }
  6499. // skip over whitespaces
  6500. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  6501. next();
  6502. }
  6503. }
  6504. while (isComment);
  6505. // check for end of dot file
  6506. if (c == '') {
  6507. // token is still empty
  6508. tokenType = TOKENTYPE.DELIMITER;
  6509. return;
  6510. }
  6511. // check for delimiters consisting of 2 characters
  6512. var c2 = c + nextPreview();
  6513. if (DELIMITERS[c2]) {
  6514. tokenType = TOKENTYPE.DELIMITER;
  6515. token = c2;
  6516. next();
  6517. next();
  6518. return;
  6519. }
  6520. // check for delimiters consisting of 1 character
  6521. if (DELIMITERS[c]) {
  6522. tokenType = TOKENTYPE.DELIMITER;
  6523. token = c;
  6524. next();
  6525. return;
  6526. }
  6527. // check for an identifier (number or string)
  6528. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  6529. if (isAlphaNumeric(c) || c == '-') {
  6530. token += c;
  6531. next();
  6532. while (isAlphaNumeric(c)) {
  6533. token += c;
  6534. next();
  6535. }
  6536. if (token == 'false') {
  6537. token = false; // convert to boolean
  6538. }
  6539. else if (token == 'true') {
  6540. token = true; // convert to boolean
  6541. }
  6542. else if (!isNaN(Number(token))) {
  6543. token = Number(token); // convert to number
  6544. }
  6545. tokenType = TOKENTYPE.IDENTIFIER;
  6546. return;
  6547. }
  6548. // check for a string enclosed by double quotes
  6549. if (c == '"') {
  6550. next();
  6551. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  6552. token += c;
  6553. if (c == '"') { // skip the escape character
  6554. next();
  6555. }
  6556. next();
  6557. }
  6558. if (c != '"') {
  6559. throw newSyntaxError('End of string " expected');
  6560. }
  6561. next();
  6562. tokenType = TOKENTYPE.IDENTIFIER;
  6563. return;
  6564. }
  6565. // something unknown is found, wrong characters, a syntax error
  6566. tokenType = TOKENTYPE.UNKNOWN;
  6567. while (c != '') {
  6568. token += c;
  6569. next();
  6570. }
  6571. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  6572. }
  6573. /**
  6574. * Parse a graph.
  6575. * @returns {Object} graph
  6576. */
  6577. function parseGraph() {
  6578. var graph = {};
  6579. first();
  6580. getToken();
  6581. // optional strict keyword
  6582. if (token == 'strict') {
  6583. graph.strict = true;
  6584. getToken();
  6585. }
  6586. // graph or digraph keyword
  6587. if (token == 'graph' || token == 'digraph') {
  6588. graph.type = token;
  6589. getToken();
  6590. }
  6591. // optional graph id
  6592. if (tokenType == TOKENTYPE.IDENTIFIER) {
  6593. graph.id = token;
  6594. getToken();
  6595. }
  6596. // open angle bracket
  6597. if (token != '{') {
  6598. throw newSyntaxError('Angle bracket { expected');
  6599. }
  6600. getToken();
  6601. // statements
  6602. parseStatements(graph);
  6603. // close angle bracket
  6604. if (token != '}') {
  6605. throw newSyntaxError('Angle bracket } expected');
  6606. }
  6607. getToken();
  6608. // end of file
  6609. if (token !== '') {
  6610. throw newSyntaxError('End of file expected');
  6611. }
  6612. getToken();
  6613. // remove temporary default properties
  6614. delete graph.node;
  6615. delete graph.edge;
  6616. delete graph.graph;
  6617. return graph;
  6618. }
  6619. /**
  6620. * Parse a list with statements.
  6621. * @param {Object} graph
  6622. */
  6623. function parseStatements (graph) {
  6624. while (token !== '' && token != '}') {
  6625. parseStatement(graph);
  6626. if (token == ';') {
  6627. getToken();
  6628. }
  6629. }
  6630. }
  6631. /**
  6632. * Parse a single statement. Can be a an attribute statement, node
  6633. * statement, a series of node statements and edge statements, or a
  6634. * parameter.
  6635. * @param {Object} graph
  6636. */
  6637. function parseStatement(graph) {
  6638. // parse subgraph
  6639. var subgraph = parseSubgraph(graph);
  6640. if (subgraph) {
  6641. // edge statements
  6642. parseEdge(graph, subgraph);
  6643. return;
  6644. }
  6645. // parse an attribute statement
  6646. var attr = parseAttributeStatement(graph);
  6647. if (attr) {
  6648. return;
  6649. }
  6650. // parse node
  6651. if (tokenType != TOKENTYPE.IDENTIFIER) {
  6652. throw newSyntaxError('Identifier expected');
  6653. }
  6654. var id = token; // id can be a string or a number
  6655. getToken();
  6656. if (token == '=') {
  6657. // id statement
  6658. getToken();
  6659. if (tokenType != TOKENTYPE.IDENTIFIER) {
  6660. throw newSyntaxError('Identifier expected');
  6661. }
  6662. graph[id] = token;
  6663. getToken();
  6664. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  6665. }
  6666. else {
  6667. parseNodeStatement(graph, id);
  6668. }
  6669. }
  6670. /**
  6671. * Parse a subgraph
  6672. * @param {Object} graph parent graph object
  6673. * @return {Object | null} subgraph
  6674. */
  6675. function parseSubgraph (graph) {
  6676. var subgraph = null;
  6677. // optional subgraph keyword
  6678. if (token == 'subgraph') {
  6679. subgraph = {};
  6680. subgraph.type = 'subgraph';
  6681. getToken();
  6682. // optional graph id
  6683. if (tokenType == TOKENTYPE.IDENTIFIER) {
  6684. subgraph.id = token;
  6685. getToken();
  6686. }
  6687. }
  6688. // open angle bracket
  6689. if (token == '{') {
  6690. getToken();
  6691. if (!subgraph) {
  6692. subgraph = {};
  6693. }
  6694. subgraph.parent = graph;
  6695. subgraph.node = graph.node;
  6696. subgraph.edge = graph.edge;
  6697. subgraph.graph = graph.graph;
  6698. // statements
  6699. parseStatements(subgraph);
  6700. // close angle bracket
  6701. if (token != '}') {
  6702. throw newSyntaxError('Angle bracket } expected');
  6703. }
  6704. getToken();
  6705. // remove temporary default properties
  6706. delete subgraph.node;
  6707. delete subgraph.edge;
  6708. delete subgraph.graph;
  6709. delete subgraph.parent;
  6710. // register at the parent graph
  6711. if (!graph.subgraphs) {
  6712. graph.subgraphs = [];
  6713. }
  6714. graph.subgraphs.push(subgraph);
  6715. }
  6716. return subgraph;
  6717. }
  6718. /**
  6719. * parse an attribute statement like "node [shape=circle fontSize=16]".
  6720. * Available keywords are 'node', 'edge', 'graph'.
  6721. * The previous list with default attributes will be replaced
  6722. * @param {Object} graph
  6723. * @returns {String | null} keyword Returns the name of the parsed attribute
  6724. * (node, edge, graph), or null if nothing
  6725. * is parsed.
  6726. */
  6727. function parseAttributeStatement (graph) {
  6728. // attribute statements
  6729. if (token == 'node') {
  6730. getToken();
  6731. // node attributes
  6732. graph.node = parseAttributeList();
  6733. return 'node';
  6734. }
  6735. else if (token == 'edge') {
  6736. getToken();
  6737. // edge attributes
  6738. graph.edge = parseAttributeList();
  6739. return 'edge';
  6740. }
  6741. else if (token == 'graph') {
  6742. getToken();
  6743. // graph attributes
  6744. graph.graph = parseAttributeList();
  6745. return 'graph';
  6746. }
  6747. return null;
  6748. }
  6749. /**
  6750. * parse a node statement
  6751. * @param {Object} graph
  6752. * @param {String | Number} id
  6753. */
  6754. function parseNodeStatement(graph, id) {
  6755. // node statement
  6756. var node = {
  6757. id: id
  6758. };
  6759. var attr = parseAttributeList();
  6760. if (attr) {
  6761. node.attr = attr;
  6762. }
  6763. addNode(graph, node);
  6764. // edge statements
  6765. parseEdge(graph, id);
  6766. }
  6767. /**
  6768. * Parse an edge or a series of edges
  6769. * @param {Object} graph
  6770. * @param {String | Number} from Id of the from node
  6771. */
  6772. function parseEdge(graph, from) {
  6773. while (token == '->' || token == '--') {
  6774. var to;
  6775. var type = token;
  6776. getToken();
  6777. var subgraph = parseSubgraph(graph);
  6778. if (subgraph) {
  6779. to = subgraph;
  6780. }
  6781. else {
  6782. if (tokenType != TOKENTYPE.IDENTIFIER) {
  6783. throw newSyntaxError('Identifier or subgraph expected');
  6784. }
  6785. to = token;
  6786. addNode(graph, {
  6787. id: to
  6788. });
  6789. getToken();
  6790. }
  6791. // parse edge attributes
  6792. var attr = parseAttributeList();
  6793. // create edge
  6794. var edge = createEdge(graph, from, to, type, attr);
  6795. addEdge(graph, edge);
  6796. from = to;
  6797. }
  6798. }
  6799. /**
  6800. * Parse a set with attributes,
  6801. * for example [label="1.000", shape=solid]
  6802. * @return {Object | null} attr
  6803. */
  6804. function parseAttributeList() {
  6805. var attr = null;
  6806. while (token == '[') {
  6807. getToken();
  6808. attr = {};
  6809. while (token !== '' && token != ']') {
  6810. if (tokenType != TOKENTYPE.IDENTIFIER) {
  6811. throw newSyntaxError('Attribute name expected');
  6812. }
  6813. var name = token;
  6814. getToken();
  6815. if (token != '=') {
  6816. throw newSyntaxError('Equal sign = expected');
  6817. }
  6818. getToken();
  6819. if (tokenType != TOKENTYPE.IDENTIFIER) {
  6820. throw newSyntaxError('Attribute value expected');
  6821. }
  6822. var value = token;
  6823. setValue(attr, name, value); // name can be a path
  6824. getToken();
  6825. if (token ==',') {
  6826. getToken();
  6827. }
  6828. }
  6829. if (token != ']') {
  6830. throw newSyntaxError('Bracket ] expected');
  6831. }
  6832. getToken();
  6833. }
  6834. return attr;
  6835. }
  6836. /**
  6837. * Create a syntax error with extra information on current token and index.
  6838. * @param {String} message
  6839. * @returns {SyntaxError} err
  6840. */
  6841. function newSyntaxError(message) {
  6842. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  6843. }
  6844. /**
  6845. * Chop off text after a maximum length
  6846. * @param {String} text
  6847. * @param {Number} maxLength
  6848. * @returns {String}
  6849. */
  6850. function chop (text, maxLength) {
  6851. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  6852. }
  6853. /**
  6854. * Execute a function fn for each pair of elements in two arrays
  6855. * @param {Array | *} array1
  6856. * @param {Array | *} array2
  6857. * @param {function} fn
  6858. */
  6859. function forEach2(array1, array2, fn) {
  6860. if (array1 instanceof Array) {
  6861. array1.forEach(function (elem1) {
  6862. if (array2 instanceof Array) {
  6863. array2.forEach(function (elem2) {
  6864. fn(elem1, elem2);
  6865. });
  6866. }
  6867. else {
  6868. fn(elem1, array2);
  6869. }
  6870. });
  6871. }
  6872. else {
  6873. if (array2 instanceof Array) {
  6874. array2.forEach(function (elem2) {
  6875. fn(array1, elem2);
  6876. });
  6877. }
  6878. else {
  6879. fn(array1, array2);
  6880. }
  6881. }
  6882. }
  6883. /**
  6884. * Convert a string containing a graph in DOT language into a map containing
  6885. * with nodes and edges in the format of graph.
  6886. * @param {String} data Text containing a graph in DOT-notation
  6887. * @return {Object} graphData
  6888. */
  6889. function DOTToGraph (data) {
  6890. // parse the DOT file
  6891. var dotData = parseDOT(data);
  6892. var graphData = {
  6893. nodes: [],
  6894. edges: [],
  6895. options: {}
  6896. };
  6897. // copy the nodes
  6898. if (dotData.nodes) {
  6899. dotData.nodes.forEach(function (dotNode) {
  6900. var graphNode = {
  6901. id: dotNode.id,
  6902. label: String(dotNode.label || dotNode.id)
  6903. };
  6904. merge(graphNode, dotNode.attr);
  6905. if (graphNode.image) {
  6906. graphNode.shape = 'image';
  6907. }
  6908. graphData.nodes.push(graphNode);
  6909. });
  6910. }
  6911. // copy the edges
  6912. if (dotData.edges) {
  6913. /**
  6914. * Convert an edge in DOT format to an edge with VisGraph format
  6915. * @param {Object} dotEdge
  6916. * @returns {Object} graphEdge
  6917. */
  6918. function convertEdge(dotEdge) {
  6919. var graphEdge = {
  6920. from: dotEdge.from,
  6921. to: dotEdge.to
  6922. };
  6923. merge(graphEdge, dotEdge.attr);
  6924. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  6925. return graphEdge;
  6926. }
  6927. dotData.edges.forEach(function (dotEdge) {
  6928. var from, to;
  6929. if (dotEdge.from instanceof Object) {
  6930. from = dotEdge.from.nodes;
  6931. }
  6932. else {
  6933. from = {
  6934. id: dotEdge.from
  6935. }
  6936. }
  6937. if (dotEdge.to instanceof Object) {
  6938. to = dotEdge.to.nodes;
  6939. }
  6940. else {
  6941. to = {
  6942. id: dotEdge.to
  6943. }
  6944. }
  6945. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  6946. dotEdge.from.edges.forEach(function (subEdge) {
  6947. var graphEdge = convertEdge(subEdge);
  6948. graphData.edges.push(graphEdge);
  6949. });
  6950. }
  6951. forEach2(from, to, function (from, to) {
  6952. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  6953. var graphEdge = convertEdge(subEdge);
  6954. graphData.edges.push(graphEdge);
  6955. });
  6956. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  6957. dotEdge.to.edges.forEach(function (subEdge) {
  6958. var graphEdge = convertEdge(subEdge);
  6959. graphData.edges.push(graphEdge);
  6960. });
  6961. }
  6962. });
  6963. }
  6964. // copy the options
  6965. if (dotData.attr) {
  6966. graphData.options = dotData.attr;
  6967. }
  6968. return graphData;
  6969. }
  6970. // exports
  6971. exports.parseDOT = parseDOT;
  6972. exports.DOTToGraph = DOTToGraph;
  6973. })(typeof util !== 'undefined' ? util : exports);
  6974. /**
  6975. * Canvas shapes used by the Graph
  6976. */
  6977. if (typeof CanvasRenderingContext2D !== 'undefined') {
  6978. /**
  6979. * Draw a circle shape
  6980. */
  6981. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  6982. this.beginPath();
  6983. this.arc(x, y, r, 0, 2*Math.PI, false);
  6984. };
  6985. /**
  6986. * Draw a square shape
  6987. * @param {Number} x horizontal center
  6988. * @param {Number} y vertical center
  6989. * @param {Number} r size, width and height of the square
  6990. */
  6991. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  6992. this.beginPath();
  6993. this.rect(x - r, y - r, r * 2, r * 2);
  6994. };
  6995. /**
  6996. * Draw a triangle shape
  6997. * @param {Number} x horizontal center
  6998. * @param {Number} y vertical center
  6999. * @param {Number} r radius, half the length of the sides of the triangle
  7000. */
  7001. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  7002. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7003. this.beginPath();
  7004. var s = r * 2;
  7005. var s2 = s / 2;
  7006. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7007. var h = Math.sqrt(s * s - s2 * s2); // height
  7008. this.moveTo(x, y - (h - ir));
  7009. this.lineTo(x + s2, y + ir);
  7010. this.lineTo(x - s2, y + ir);
  7011. this.lineTo(x, y - (h - ir));
  7012. this.closePath();
  7013. };
  7014. /**
  7015. * Draw a triangle shape in downward orientation
  7016. * @param {Number} x horizontal center
  7017. * @param {Number} y vertical center
  7018. * @param {Number} r radius
  7019. */
  7020. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  7021. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7022. this.beginPath();
  7023. var s = r * 2;
  7024. var s2 = s / 2;
  7025. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7026. var h = Math.sqrt(s * s - s2 * s2); // height
  7027. this.moveTo(x, y + (h - ir));
  7028. this.lineTo(x + s2, y - ir);
  7029. this.lineTo(x - s2, y - ir);
  7030. this.lineTo(x, y + (h - ir));
  7031. this.closePath();
  7032. };
  7033. /**
  7034. * Draw a star shape, a star with 5 points
  7035. * @param {Number} x horizontal center
  7036. * @param {Number} y vertical center
  7037. * @param {Number} r radius, half the length of the sides of the triangle
  7038. */
  7039. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  7040. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  7041. this.beginPath();
  7042. for (var n = 0; n < 10; n++) {
  7043. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  7044. this.lineTo(
  7045. x + radius * Math.sin(n * 2 * Math.PI / 10),
  7046. y - radius * Math.cos(n * 2 * Math.PI / 10)
  7047. );
  7048. }
  7049. this.closePath();
  7050. };
  7051. /**
  7052. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  7053. */
  7054. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  7055. var r2d = Math.PI/180;
  7056. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  7057. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  7058. this.beginPath();
  7059. this.moveTo(x+r,y);
  7060. this.lineTo(x+w-r,y);
  7061. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  7062. this.lineTo(x+w,y+h-r);
  7063. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  7064. this.lineTo(x+r,y+h);
  7065. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  7066. this.lineTo(x,y+r);
  7067. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  7068. };
  7069. /**
  7070. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7071. */
  7072. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  7073. var kappa = .5522848,
  7074. ox = (w / 2) * kappa, // control point offset horizontal
  7075. oy = (h / 2) * kappa, // control point offset vertical
  7076. xe = x + w, // x-end
  7077. ye = y + h, // y-end
  7078. xm = x + w / 2, // x-middle
  7079. ym = y + h / 2; // y-middle
  7080. this.beginPath();
  7081. this.moveTo(x, ym);
  7082. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7083. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7084. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7085. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7086. };
  7087. /**
  7088. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7089. */
  7090. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  7091. var f = 1/3;
  7092. var wEllipse = w;
  7093. var hEllipse = h * f;
  7094. var kappa = .5522848,
  7095. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  7096. oy = (hEllipse / 2) * kappa, // control point offset vertical
  7097. xe = x + wEllipse, // x-end
  7098. ye = y + hEllipse, // y-end
  7099. xm = x + wEllipse / 2, // x-middle
  7100. ym = y + hEllipse / 2, // y-middle
  7101. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  7102. yeb = y + h; // y-end, bottom ellipse
  7103. this.beginPath();
  7104. this.moveTo(xe, ym);
  7105. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7106. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7107. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7108. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7109. this.lineTo(xe, ymb);
  7110. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  7111. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  7112. this.lineTo(x, ym);
  7113. };
  7114. /**
  7115. * Draw an arrow point (no line)
  7116. */
  7117. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  7118. // tail
  7119. var xt = x - length * Math.cos(angle);
  7120. var yt = y - length * Math.sin(angle);
  7121. // inner tail
  7122. // TODO: allow to customize different shapes
  7123. var xi = x - length * 0.9 * Math.cos(angle);
  7124. var yi = y - length * 0.9 * Math.sin(angle);
  7125. // left
  7126. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  7127. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  7128. // right
  7129. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  7130. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  7131. this.beginPath();
  7132. this.moveTo(x, y);
  7133. this.lineTo(xl, yl);
  7134. this.lineTo(xi, yi);
  7135. this.lineTo(xr, yr);
  7136. this.closePath();
  7137. };
  7138. /**
  7139. * Sets up the dashedLine functionality for drawing
  7140. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  7141. * @author David Jordan
  7142. * @date 2012-08-08
  7143. */
  7144. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  7145. if (!dashArray) dashArray=[10,5];
  7146. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  7147. var dashCount = dashArray.length;
  7148. this.moveTo(x, y);
  7149. var dx = (x2-x), dy = (y2-y);
  7150. var slope = dy/dx;
  7151. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  7152. var dashIndex=0, draw=true;
  7153. while (distRemaining>=0.1){
  7154. var dashLength = dashArray[dashIndex++%dashCount];
  7155. if (dashLength > distRemaining) dashLength = distRemaining;
  7156. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  7157. if (dx<0) xStep = -xStep;
  7158. x += xStep;
  7159. y += slope*xStep;
  7160. this[draw ? 'lineTo' : 'moveTo'](x,y);
  7161. distRemaining -= dashLength;
  7162. draw = !draw;
  7163. }
  7164. };
  7165. // TODO: add diamond shape
  7166. }
  7167. /**
  7168. * @class Node
  7169. * A node. A node can be connected to other nodes via one or multiple edges.
  7170. * @param {object} properties An object containing properties for the node. All
  7171. * properties are optional, except for the id.
  7172. * {number} id Id of the node. Required
  7173. * {string} label Text label for the node
  7174. * {number} x Horizontal position of the node
  7175. * {number} y Vertical position of the node
  7176. * {string} shape Node shape, available:
  7177. * "database", "circle", "ellipse",
  7178. * "box", "image", "text", "dot",
  7179. * "star", "triangle", "triangleDown",
  7180. * "square"
  7181. * {string} image An image url
  7182. * {string} title An title text, can be HTML
  7183. * {anytype} group A group name or number
  7184. * @param {Graph.Images} imagelist A list with images. Only needed
  7185. * when the node has an image
  7186. * @param {Graph.Groups} grouplist A list with groups. Needed for
  7187. * retrieving group properties
  7188. * @param {Object} constants An object with default values for
  7189. * example for the color
  7190. */
  7191. function Node(properties, imagelist, grouplist, constants) {
  7192. this.selected = false;
  7193. this.edges = []; // all edges connected to this node
  7194. this.group = constants.nodes.group;
  7195. this.fontSize = constants.nodes.fontSize;
  7196. this.fontFace = constants.nodes.fontFace;
  7197. this.fontColor = constants.nodes.fontColor;
  7198. this.color = constants.nodes.color;
  7199. // set defaults for the properties
  7200. this.id = undefined;
  7201. this.shape = constants.nodes.shape;
  7202. this.image = constants.nodes.image;
  7203. this.x = 0;
  7204. this.y = 0;
  7205. this.xFixed = false;
  7206. this.yFixed = false;
  7207. this.radius = constants.nodes.radius;
  7208. this.radiusFixed = false;
  7209. this.radiusMin = constants.nodes.radiusMin;
  7210. this.radiusMax = constants.nodes.radiusMax;
  7211. this.imagelist = imagelist;
  7212. this.grouplist = grouplist;
  7213. this.setProperties(properties, constants);
  7214. // mass, force, velocity
  7215. this.mass = 50; // kg (mass is adjusted for the number of connected edges)
  7216. this.fx = 0.0; // external force x
  7217. this.fy = 0.0; // external force y
  7218. this.vx = 0.0; // velocity x
  7219. this.vy = 0.0; // velocity y
  7220. this.minForce = constants.minForce;
  7221. this.damping = 0.9; // damping factor
  7222. };
  7223. /**
  7224. * Attach a edge to the node
  7225. * @param {Edge} edge
  7226. */
  7227. Node.prototype.attachEdge = function(edge) {
  7228. if (this.edges.indexOf(edge) == -1) {
  7229. this.edges.push(edge);
  7230. }
  7231. this._updateMass();
  7232. };
  7233. /**
  7234. * Detach a edge from the node
  7235. * @param {Edge} edge
  7236. */
  7237. Node.prototype.detachEdge = function(edge) {
  7238. var index = this.edges.indexOf(edge);
  7239. if (index != -1) {
  7240. this.edges.splice(index, 1);
  7241. }
  7242. this._updateMass();
  7243. };
  7244. /**
  7245. * Update the nodes mass, which is determined by the number of edges connecting
  7246. * to it (more edges -> heavier node).
  7247. * @private
  7248. */
  7249. Node.prototype._updateMass = function() {
  7250. this.mass = 50 + 20 * this.edges.length; // kg
  7251. };
  7252. /**
  7253. * Set or overwrite properties for the node
  7254. * @param {Object} properties an object with properties
  7255. * @param {Object} constants and object with default, global properties
  7256. */
  7257. Node.prototype.setProperties = function(properties, constants) {
  7258. if (!properties) {
  7259. return;
  7260. }
  7261. // basic properties
  7262. if (properties.id != undefined) {this.id = properties.id;}
  7263. if (properties.label != undefined) {this.label = properties.label;}
  7264. if (properties.title != undefined) {this.title = properties.title;}
  7265. if (properties.group != undefined) {this.group = properties.group;}
  7266. if (properties.x != undefined) {this.x = properties.x;}
  7267. if (properties.y != undefined) {this.y = properties.y;}
  7268. if (properties.value != undefined) {this.value = properties.value;}
  7269. if (this.id === undefined) {
  7270. throw "Node must have an id";
  7271. }
  7272. // copy group properties
  7273. if (this.group) {
  7274. var groupObj = this.grouplist.get(this.group);
  7275. for (var prop in groupObj) {
  7276. if (groupObj.hasOwnProperty(prop)) {
  7277. this[prop] = groupObj[prop];
  7278. }
  7279. }
  7280. }
  7281. // individual shape properties
  7282. if (properties.shape != undefined) {this.shape = properties.shape;}
  7283. if (properties.image != undefined) {this.image = properties.image;}
  7284. if (properties.radius != undefined) {this.radius = properties.radius;}
  7285. if (properties.color != undefined) {this.color = Node.parseColor(properties.color);}
  7286. if (properties.fontColor != undefined) {this.fontColor = properties.fontColor;}
  7287. if (properties.fontSize != undefined) {this.fontSize = properties.fontSize;}
  7288. if (properties.fontFace != undefined) {this.fontFace = properties.fontFace;}
  7289. if (this.image != undefined) {
  7290. if (this.imagelist) {
  7291. this.imageObj = this.imagelist.load(this.image);
  7292. }
  7293. else {
  7294. throw "No imagelist provided";
  7295. }
  7296. }
  7297. this.xFixed = this.xFixed || (properties.x != undefined);
  7298. this.yFixed = this.yFixed || (properties.y != undefined);
  7299. this.radiusFixed = this.radiusFixed || (properties.radius != undefined);
  7300. if (this.shape == 'image') {
  7301. this.radiusMin = constants.nodes.widthMin;
  7302. this.radiusMax = constants.nodes.widthMax;
  7303. }
  7304. // choose draw method depending on the shape
  7305. switch (this.shape) {
  7306. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  7307. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  7308. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  7309. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  7310. // TODO: add diamond shape
  7311. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  7312. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  7313. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  7314. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  7315. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  7316. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  7317. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  7318. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  7319. }
  7320. // reset the size of the node, this can be changed
  7321. this._reset();
  7322. };
  7323. /**
  7324. * Parse a color property into an object with border, background, and
  7325. * hightlight colors
  7326. * @param {Object | String} color
  7327. * @return {Object} colorObject
  7328. */
  7329. Node.parseColor = function(color) {
  7330. var c;
  7331. if (util.isString(color)) {
  7332. c = {
  7333. border: color,
  7334. background: color,
  7335. highlight: {
  7336. border: color,
  7337. background: color
  7338. }
  7339. };
  7340. // TODO: automatically generate a nice highlight color
  7341. }
  7342. else {
  7343. c = {};
  7344. c.background = color.background || 'white';
  7345. c.border = color.border || c.background;
  7346. if (util.isString(color.highlight)) {
  7347. c.highlight = {
  7348. border: color.highlight,
  7349. background: color.highlight
  7350. }
  7351. }
  7352. else {
  7353. c.highlight = {};
  7354. c.highlight.background = color.highlight && color.highlight.background || c.background;
  7355. c.highlight.border = color.highlight && color.highlight.border || c.border;
  7356. }
  7357. }
  7358. return c;
  7359. };
  7360. /**
  7361. * select this node
  7362. */
  7363. Node.prototype.select = function() {
  7364. this.selected = true;
  7365. this._reset();
  7366. };
  7367. /**
  7368. * unselect this node
  7369. */
  7370. Node.prototype.unselect = function() {
  7371. this.selected = false;
  7372. this._reset();
  7373. };
  7374. /**
  7375. * Reset the calculated size of the node, forces it to recalculate its size
  7376. * @private
  7377. */
  7378. Node.prototype._reset = function() {
  7379. this.width = undefined;
  7380. this.height = undefined;
  7381. };
  7382. /**
  7383. * get the title of this node.
  7384. * @return {string} title The title of the node, or undefined when no title
  7385. * has been set.
  7386. */
  7387. Node.prototype.getTitle = function() {
  7388. return this.title;
  7389. };
  7390. /**
  7391. * Calculate the distance to the border of the Node
  7392. * @param {CanvasRenderingContext2D} ctx
  7393. * @param {Number} angle Angle in radians
  7394. * @returns {number} distance Distance to the border in pixels
  7395. */
  7396. Node.prototype.distanceToBorder = function (ctx, angle) {
  7397. var borderWidth = 1;
  7398. if (!this.width) {
  7399. this.resize(ctx);
  7400. }
  7401. //noinspection FallthroughInSwitchStatementJS
  7402. switch (this.shape) {
  7403. case 'circle':
  7404. case 'dot':
  7405. return this.radius + borderWidth;
  7406. case 'ellipse':
  7407. var a = this.width / 2;
  7408. var b = this.height / 2;
  7409. var w = (Math.sin(angle) * a);
  7410. var h = (Math.cos(angle) * b);
  7411. return a * b / Math.sqrt(w * w + h * h);
  7412. // TODO: implement distanceToBorder for database
  7413. // TODO: implement distanceToBorder for triangle
  7414. // TODO: implement distanceToBorder for triangleDown
  7415. case 'box':
  7416. case 'image':
  7417. case 'text':
  7418. default:
  7419. if (this.width) {
  7420. return Math.min(
  7421. Math.abs(this.width / 2 / Math.cos(angle)),
  7422. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  7423. // TODO: reckon with border radius too in case of box
  7424. }
  7425. else {
  7426. return 0;
  7427. }
  7428. }
  7429. // TODO: implement calculation of distance to border for all shapes
  7430. };
  7431. /**
  7432. * Set forces acting on the node
  7433. * @param {number} fx Force in horizontal direction
  7434. * @param {number} fy Force in vertical direction
  7435. */
  7436. Node.prototype._setForce = function(fx, fy) {
  7437. this.fx = fx;
  7438. this.fy = fy;
  7439. };
  7440. /**
  7441. * Add forces acting on the node
  7442. * @param {number} fx Force in horizontal direction
  7443. * @param {number} fy Force in vertical direction
  7444. * @private
  7445. */
  7446. Node.prototype._addForce = function(fx, fy) {
  7447. this.fx += fx;
  7448. this.fy += fy;
  7449. };
  7450. /**
  7451. * Perform one discrete step for the node
  7452. * @param {number} interval Time interval in seconds
  7453. */
  7454. Node.prototype.discreteStep = function(interval) {
  7455. if (!this.xFixed) {
  7456. var dx = -this.damping * this.vx; // damping force
  7457. var ax = (this.fx + dx) / this.mass; // acceleration
  7458. this.vx += ax / interval; // velocity
  7459. this.x += this.vx / interval; // position
  7460. }
  7461. if (!this.yFixed) {
  7462. var dy = -this.damping * this.vy; // damping force
  7463. var ay = (this.fy + dy) / this.mass; // acceleration
  7464. this.vy += ay / interval; // velocity
  7465. this.y += this.vy / interval; // position
  7466. }
  7467. };
  7468. /**
  7469. * Check if this node has a fixed x and y position
  7470. * @return {boolean} true if fixed, false if not
  7471. */
  7472. Node.prototype.isFixed = function() {
  7473. return (this.xFixed && this.yFixed);
  7474. };
  7475. /**
  7476. * Check if this node is moving
  7477. * @param {number} vmin the minimum velocity considered as "moving"
  7478. * @return {boolean} true if moving, false if it has no velocity
  7479. */
  7480. // TODO: replace this method with calculating the kinetic energy
  7481. Node.prototype.isMoving = function(vmin) {
  7482. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin ||
  7483. (!this.xFixed && Math.abs(this.fx) > this.minForce) ||
  7484. (!this.yFixed && Math.abs(this.fy) > this.minForce));
  7485. };
  7486. /**
  7487. * check if this node is selecte
  7488. * @return {boolean} selected True if node is selected, else false
  7489. */
  7490. Node.prototype.isSelected = function() {
  7491. return this.selected;
  7492. };
  7493. /**
  7494. * Retrieve the value of the node. Can be undefined
  7495. * @return {Number} value
  7496. */
  7497. Node.prototype.getValue = function() {
  7498. return this.value;
  7499. };
  7500. /**
  7501. * Calculate the distance from the nodes location to the given location (x,y)
  7502. * @param {Number} x
  7503. * @param {Number} y
  7504. * @return {Number} value
  7505. */
  7506. Node.prototype.getDistance = function(x, y) {
  7507. var dx = this.x - x,
  7508. dy = this.y - y;
  7509. return Math.sqrt(dx * dx + dy * dy);
  7510. };
  7511. /**
  7512. * Adjust the value range of the node. The node will adjust it's radius
  7513. * based on its value.
  7514. * @param {Number} min
  7515. * @param {Number} max
  7516. */
  7517. Node.prototype.setValueRange = function(min, max) {
  7518. if (!this.radiusFixed && this.value !== undefined) {
  7519. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  7520. this.radius = (this.value - min) * scale + this.radiusMin;
  7521. }
  7522. };
  7523. /**
  7524. * Draw this node in the given canvas
  7525. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  7526. * @param {CanvasRenderingContext2D} ctx
  7527. */
  7528. Node.prototype.draw = function(ctx) {
  7529. throw "Draw method not initialized for node";
  7530. };
  7531. /**
  7532. * Recalculate the size of this node in the given canvas
  7533. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  7534. * @param {CanvasRenderingContext2D} ctx
  7535. */
  7536. Node.prototype.resize = function(ctx) {
  7537. throw "Resize method not initialized for node";
  7538. };
  7539. /**
  7540. * Check if this object is overlapping with the provided object
  7541. * @param {Object} obj an object with parameters left, top, right, bottom
  7542. * @return {boolean} True if location is located on node
  7543. */
  7544. Node.prototype.isOverlappingWith = function(obj) {
  7545. return (this.left < obj.right &&
  7546. this.left + this.width > obj.left &&
  7547. this.top < obj.bottom &&
  7548. this.top + this.height > obj.top);
  7549. };
  7550. Node.prototype._resizeImage = function (ctx) {
  7551. // TODO: pre calculate the image size
  7552. if (!this.width) { // undefined or 0
  7553. var width, height;
  7554. if (this.value) {
  7555. var scale = this.imageObj.height / this.imageObj.width;
  7556. width = this.radius || this.imageObj.width;
  7557. height = this.radius * scale || this.imageObj.height;
  7558. }
  7559. else {
  7560. width = this.imageObj.width;
  7561. height = this.imageObj.height;
  7562. }
  7563. this.width = width;
  7564. this.height = height;
  7565. }
  7566. };
  7567. Node.prototype._drawImage = function (ctx) {
  7568. this._resizeImage(ctx);
  7569. this.left = this.x - this.width / 2;
  7570. this.top = this.y - this.height / 2;
  7571. var yLabel;
  7572. if (this.imageObj) {
  7573. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  7574. yLabel = this.y + this.height / 2;
  7575. }
  7576. else {
  7577. // image still loading... just draw the label for now
  7578. yLabel = this.y;
  7579. }
  7580. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  7581. };
  7582. Node.prototype._resizeBox = function (ctx) {
  7583. if (!this.width) {
  7584. var margin = 5;
  7585. var textSize = this.getTextSize(ctx);
  7586. this.width = textSize.width + 2 * margin;
  7587. this.height = textSize.height + 2 * margin;
  7588. }
  7589. };
  7590. Node.prototype._drawBox = function (ctx) {
  7591. this._resizeBox(ctx);
  7592. this.left = this.x - this.width / 2;
  7593. this.top = this.y - this.height / 2;
  7594. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  7595. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  7596. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  7597. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  7598. ctx.fill();
  7599. ctx.stroke();
  7600. this._label(ctx, this.label, this.x, this.y);
  7601. };
  7602. Node.prototype._resizeDatabase = function (ctx) {
  7603. if (!this.width) {
  7604. var margin = 5;
  7605. var textSize = this.getTextSize(ctx);
  7606. var size = textSize.width + 2 * margin;
  7607. this.width = size;
  7608. this.height = size;
  7609. }
  7610. };
  7611. Node.prototype._drawDatabase = function (ctx) {
  7612. this._resizeDatabase(ctx);
  7613. this.left = this.x - this.width / 2;
  7614. this.top = this.y - this.height / 2;
  7615. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  7616. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  7617. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  7618. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  7619. ctx.fill();
  7620. ctx.stroke();
  7621. this._label(ctx, this.label, this.x, this.y);
  7622. };
  7623. Node.prototype._resizeCircle = function (ctx) {
  7624. if (!this.width) {
  7625. var margin = 5;
  7626. var textSize = this.getTextSize(ctx);
  7627. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  7628. this.radius = diameter / 2;
  7629. this.width = diameter;
  7630. this.height = diameter;
  7631. }
  7632. };
  7633. Node.prototype._drawCircle = function (ctx) {
  7634. this._resizeCircle(ctx);
  7635. this.left = this.x - this.width / 2;
  7636. this.top = this.y - this.height / 2;
  7637. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  7638. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  7639. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  7640. ctx.circle(this.x, this.y, this.radius);
  7641. ctx.fill();
  7642. ctx.stroke();
  7643. this._label(ctx, this.label, this.x, this.y);
  7644. };
  7645. Node.prototype._resizeEllipse = function (ctx) {
  7646. if (!this.width) {
  7647. var textSize = this.getTextSize(ctx);
  7648. this.width = textSize.width * 1.5;
  7649. this.height = textSize.height * 2;
  7650. if (this.width < this.height) {
  7651. this.width = this.height;
  7652. }
  7653. }
  7654. };
  7655. Node.prototype._drawEllipse = function (ctx) {
  7656. this._resizeEllipse(ctx);
  7657. this.left = this.x - this.width / 2;
  7658. this.top = this.y - this.height / 2;
  7659. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  7660. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  7661. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  7662. ctx.ellipse(this.left, this.top, this.width, this.height);
  7663. ctx.fill();
  7664. ctx.stroke();
  7665. this._label(ctx, this.label, this.x, this.y);
  7666. };
  7667. Node.prototype._drawDot = function (ctx) {
  7668. this._drawShape(ctx, 'circle');
  7669. };
  7670. Node.prototype._drawTriangle = function (ctx) {
  7671. this._drawShape(ctx, 'triangle');
  7672. };
  7673. Node.prototype._drawTriangleDown = function (ctx) {
  7674. this._drawShape(ctx, 'triangleDown');
  7675. };
  7676. Node.prototype._drawSquare = function (ctx) {
  7677. this._drawShape(ctx, 'square');
  7678. };
  7679. Node.prototype._drawStar = function (ctx) {
  7680. this._drawShape(ctx, 'star');
  7681. };
  7682. Node.prototype._resizeShape = function (ctx) {
  7683. if (!this.width) {
  7684. var size = 2 * this.radius;
  7685. this.width = size;
  7686. this.height = size;
  7687. }
  7688. };
  7689. Node.prototype._drawShape = function (ctx, shape) {
  7690. this._resizeShape(ctx);
  7691. this.left = this.x - this.width / 2;
  7692. this.top = this.y - this.height / 2;
  7693. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  7694. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  7695. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  7696. ctx[shape](this.x, this.y, this.radius);
  7697. ctx.fill();
  7698. ctx.stroke();
  7699. if (this.label) {
  7700. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  7701. }
  7702. };
  7703. Node.prototype._resizeText = function (ctx) {
  7704. if (!this.width) {
  7705. var margin = 5;
  7706. var textSize = this.getTextSize(ctx);
  7707. this.width = textSize.width + 2 * margin;
  7708. this.height = textSize.height + 2 * margin;
  7709. }
  7710. };
  7711. Node.prototype._drawText = function (ctx) {
  7712. this._resizeText(ctx);
  7713. this.left = this.x - this.width / 2;
  7714. this.top = this.y - this.height / 2;
  7715. this._label(ctx, this.label, this.x, this.y);
  7716. };
  7717. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  7718. if (text) {
  7719. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  7720. ctx.fillStyle = this.fontColor || "black";
  7721. ctx.textAlign = align || "center";
  7722. ctx.textBaseline = baseline || "middle";
  7723. var lines = text.split('\n'),
  7724. lineCount = lines.length,
  7725. fontSize = (this.fontSize + 4),
  7726. yLine = y + (1 - lineCount) / 2 * fontSize;
  7727. for (var i = 0; i < lineCount; i++) {
  7728. ctx.fillText(lines[i], x, yLine);
  7729. yLine += fontSize;
  7730. }
  7731. }
  7732. };
  7733. Node.prototype.getTextSize = function(ctx) {
  7734. if (this.label != undefined) {
  7735. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  7736. var lines = this.label.split('\n'),
  7737. height = (this.fontSize + 4) * lines.length,
  7738. width = 0;
  7739. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  7740. width = Math.max(width, ctx.measureText(lines[i]).width);
  7741. }
  7742. return {"width": width, "height": height};
  7743. }
  7744. else {
  7745. return {"width": 0, "height": 0};
  7746. }
  7747. };
  7748. /**
  7749. * @class Edge
  7750. *
  7751. * A edge connects two nodes
  7752. * @param {Object} properties Object with properties. Must contain
  7753. * At least properties from and to.
  7754. * Available properties: from (number),
  7755. * to (number), label (string, color (string),
  7756. * width (number), style (string),
  7757. * length (number), title (string)
  7758. * @param {Graph} graph A graph object, used to find and edge to
  7759. * nodes.
  7760. * @param {Object} constants An object with default values for
  7761. * example for the color
  7762. */
  7763. function Edge (properties, graph, constants) {
  7764. if (!graph) {
  7765. throw "No graph provided";
  7766. }
  7767. this.graph = graph;
  7768. // initialize constants
  7769. this.widthMin = constants.edges.widthMin;
  7770. this.widthMax = constants.edges.widthMax;
  7771. // initialize variables
  7772. this.id = undefined;
  7773. this.fromId = undefined;
  7774. this.toId = undefined;
  7775. this.style = constants.edges.style;
  7776. this.title = undefined;
  7777. this.width = constants.edges.width;
  7778. this.value = undefined;
  7779. this.length = constants.edges.length;
  7780. this.from = null; // a node
  7781. this.to = null; // a node
  7782. this.connected = false;
  7783. // Added to support dashed lines
  7784. // David Jordan
  7785. // 2012-08-08
  7786. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  7787. this.stiffness = undefined; // depends on the length of the edge
  7788. this.color = constants.edges.color;
  7789. this.widthFixed = false;
  7790. this.lengthFixed = false;
  7791. this.setProperties(properties, constants);
  7792. }
  7793. /**
  7794. * Set or overwrite properties for the edge
  7795. * @param {Object} properties an object with properties
  7796. * @param {Object} constants and object with default, global properties
  7797. */
  7798. Edge.prototype.setProperties = function(properties, constants) {
  7799. if (!properties) {
  7800. return;
  7801. }
  7802. if (properties.from != undefined) {this.fromId = properties.from;}
  7803. if (properties.to != undefined) {this.toId = properties.to;}
  7804. if (properties.id != undefined) {this.id = properties.id;}
  7805. if (properties.style != undefined) {this.style = properties.style;}
  7806. if (properties.label != undefined) {this.label = properties.label;}
  7807. if (this.label) {
  7808. this.fontSize = constants.edges.fontSize;
  7809. this.fontFace = constants.edges.fontFace;
  7810. this.fontColor = constants.edges.fontColor;
  7811. if (properties.fontColor != undefined) {this.fontColor = properties.fontColor;}
  7812. if (properties.fontSize != undefined) {this.fontSize = properties.fontSize;}
  7813. if (properties.fontFace != undefined) {this.fontFace = properties.fontFace;}
  7814. }
  7815. if (properties.title != undefined) {this.title = properties.title;}
  7816. if (properties.width != undefined) {this.width = properties.width;}
  7817. if (properties.value != undefined) {this.value = properties.value;}
  7818. if (properties.length != undefined) {this.length = properties.length;}
  7819. // Added to support dashed lines
  7820. // David Jordan
  7821. // 2012-08-08
  7822. if (properties.dash) {
  7823. if (properties.dash.length != undefined) {this.dash.length = properties.dash.length;}
  7824. if (properties.dash.gap != undefined) {this.dash.gap = properties.dash.gap;}
  7825. if (properties.dash.altLength != undefined) {this.dash.altLength = properties.dash.altLength;}
  7826. }
  7827. if (properties.color != undefined) {this.color = properties.color;}
  7828. // A node is connected when it has a from and to node.
  7829. this.connect();
  7830. this.widthFixed = this.widthFixed || (properties.width != undefined);
  7831. this.lengthFixed = this.lengthFixed || (properties.length != undefined);
  7832. this.stiffness = 1 / this.length;
  7833. // set draw method based on style
  7834. switch (this.style) {
  7835. case 'line': this.draw = this._drawLine; break;
  7836. case 'arrow': this.draw = this._drawArrow; break;
  7837. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  7838. case 'dash-line': this.draw = this._drawDashLine; break;
  7839. default: this.draw = this._drawLine; break;
  7840. }
  7841. };
  7842. /**
  7843. * Connect an edge to its nodes
  7844. */
  7845. Edge.prototype.connect = function () {
  7846. this.disconnect();
  7847. this.from = this.graph.nodes[this.fromId] || null;
  7848. this.to = this.graph.nodes[this.toId] || null;
  7849. this.connected = (this.from && this.to);
  7850. if (this.connected) {
  7851. this.from.attachEdge(this);
  7852. this.to.attachEdge(this);
  7853. }
  7854. else {
  7855. if (this.from) {
  7856. this.from.detachEdge(this);
  7857. }
  7858. if (this.to) {
  7859. this.to.detachEdge(this);
  7860. }
  7861. }
  7862. };
  7863. /**
  7864. * Disconnect an edge from its nodes
  7865. */
  7866. Edge.prototype.disconnect = function () {
  7867. if (this.from) {
  7868. this.from.detachEdge(this);
  7869. this.from = null;
  7870. }
  7871. if (this.to) {
  7872. this.to.detachEdge(this);
  7873. this.to = null;
  7874. }
  7875. this.connected = false;
  7876. };
  7877. /**
  7878. * get the title of this edge.
  7879. * @return {string} title The title of the edge, or undefined when no title
  7880. * has been set.
  7881. */
  7882. Edge.prototype.getTitle = function() {
  7883. return this.title;
  7884. };
  7885. /**
  7886. * Retrieve the value of the edge. Can be undefined
  7887. * @return {Number} value
  7888. */
  7889. Edge.prototype.getValue = function() {
  7890. return this.value;
  7891. };
  7892. /**
  7893. * Adjust the value range of the edge. The edge will adjust it's width
  7894. * based on its value.
  7895. * @param {Number} min
  7896. * @param {Number} max
  7897. */
  7898. Edge.prototype.setValueRange = function(min, max) {
  7899. if (!this.widthFixed && this.value !== undefined) {
  7900. var factor = (this.widthMax - this.widthMin) / (max - min);
  7901. this.width = (this.value - min) * factor + this.widthMin;
  7902. }
  7903. };
  7904. /**
  7905. * Redraw a edge
  7906. * Draw this edge in the given canvas
  7907. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  7908. * @param {CanvasRenderingContext2D} ctx
  7909. */
  7910. Edge.prototype.draw = function(ctx) {
  7911. throw "Method draw not initialized in edge";
  7912. };
  7913. /**
  7914. * Check if this object is overlapping with the provided object
  7915. * @param {Object} obj an object with parameters left, top
  7916. * @return {boolean} True if location is located on the edge
  7917. */
  7918. Edge.prototype.isOverlappingWith = function(obj) {
  7919. var distMax = 10;
  7920. var xFrom = this.from.x;
  7921. var yFrom = this.from.y;
  7922. var xTo = this.to.x;
  7923. var yTo = this.to.y;
  7924. var xObj = obj.left;
  7925. var yObj = obj.top;
  7926. var dist = Edge._dist(xFrom, yFrom, xTo, yTo, xObj, yObj);
  7927. return (dist < distMax);
  7928. };
  7929. /**
  7930. * Redraw a edge as a line
  7931. * Draw this edge in the given canvas
  7932. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  7933. * @param {CanvasRenderingContext2D} ctx
  7934. * @private
  7935. */
  7936. Edge.prototype._drawLine = function(ctx) {
  7937. // set style
  7938. ctx.strokeStyle = this.color;
  7939. ctx.lineWidth = this._getLineWidth();
  7940. var point;
  7941. if (this.from != this.to) {
  7942. // draw line
  7943. this._line(ctx);
  7944. // draw label
  7945. if (this.label) {
  7946. point = this._pointOnLine(0.5);
  7947. this._label(ctx, this.label, point.x, point.y);
  7948. }
  7949. }
  7950. else {
  7951. var x, y;
  7952. var radius = this.length / 4;
  7953. var node = this.from;
  7954. if (!node.width) {
  7955. node.resize(ctx);
  7956. }
  7957. if (node.width > node.height) {
  7958. x = node.x + node.width / 2;
  7959. y = node.y - radius;
  7960. }
  7961. else {
  7962. x = node.x + radius;
  7963. y = node.y - node.height / 2;
  7964. }
  7965. this._circle(ctx, x, y, radius);
  7966. point = this._pointOnCircle(x, y, radius, 0.5);
  7967. this._label(ctx, this.label, point.x, point.y);
  7968. }
  7969. };
  7970. /**
  7971. * Get the line width of the edge. Depends on width and whether one of the
  7972. * connected nodes is selected.
  7973. * @return {Number} width
  7974. * @private
  7975. */
  7976. Edge.prototype._getLineWidth = function() {
  7977. if (this.from.selected || this.to.selected) {
  7978. return Math.min(this.width * 2, this.widthMax);
  7979. }
  7980. else {
  7981. return this.width;
  7982. }
  7983. };
  7984. /**
  7985. * Draw a line between two nodes
  7986. * @param {CanvasRenderingContext2D} ctx
  7987. * @private
  7988. */
  7989. Edge.prototype._line = function (ctx) {
  7990. // draw a straight line
  7991. ctx.beginPath();
  7992. ctx.moveTo(this.from.x, this.from.y);
  7993. ctx.lineTo(this.to.x, this.to.y);
  7994. ctx.stroke();
  7995. };
  7996. /**
  7997. * Draw a line from a node to itself, a circle
  7998. * @param {CanvasRenderingContext2D} ctx
  7999. * @param {Number} x
  8000. * @param {Number} y
  8001. * @param {Number} radius
  8002. * @private
  8003. */
  8004. Edge.prototype._circle = function (ctx, x, y, radius) {
  8005. // draw a circle
  8006. ctx.beginPath();
  8007. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  8008. ctx.stroke();
  8009. };
  8010. /**
  8011. * Draw label with white background and with the middle at (x, y)
  8012. * @param {CanvasRenderingContext2D} ctx
  8013. * @param {String} text
  8014. * @param {Number} x
  8015. * @param {Number} y
  8016. * @private
  8017. */
  8018. Edge.prototype._label = function (ctx, text, x, y) {
  8019. if (text) {
  8020. // TODO: cache the calculated size
  8021. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  8022. this.fontSize + "px " + this.fontFace;
  8023. ctx.fillStyle = 'white';
  8024. var width = ctx.measureText(text).width;
  8025. var height = this.fontSize;
  8026. var left = x - width / 2;
  8027. var top = y - height / 2;
  8028. ctx.fillRect(left, top, width, height);
  8029. // draw text
  8030. ctx.fillStyle = this.fontColor || "black";
  8031. ctx.textAlign = "left";
  8032. ctx.textBaseline = "top";
  8033. ctx.fillText(text, left, top);
  8034. }
  8035. };
  8036. /**
  8037. * Redraw a edge as a dashed line
  8038. * Draw this edge in the given canvas
  8039. * @author David Jordan
  8040. * @date 2012-08-08
  8041. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8042. * @param {CanvasRenderingContext2D} ctx
  8043. * @private
  8044. */
  8045. Edge.prototype._drawDashLine = function(ctx) {
  8046. // set style
  8047. ctx.strokeStyle = this.color;
  8048. ctx.lineWidth = this._getLineWidth();
  8049. // draw dashed line
  8050. ctx.beginPath();
  8051. ctx.lineCap = 'round';
  8052. if (this.dash.altLength != undefined) //If an alt dash value has been set add to the array this value
  8053. {
  8054. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  8055. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  8056. }
  8057. 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
  8058. {
  8059. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  8060. [this.dash.length,this.dash.gap]);
  8061. }
  8062. else //If all else fails draw a line
  8063. {
  8064. ctx.moveTo(this.from.x, this.from.y);
  8065. ctx.lineTo(this.to.x, this.to.y);
  8066. }
  8067. ctx.stroke();
  8068. // draw label
  8069. if (this.label) {
  8070. var point = this._pointOnLine(0.5);
  8071. this._label(ctx, this.label, point.x, point.y);
  8072. }
  8073. };
  8074. /**
  8075. * Get a point on a line
  8076. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  8077. * @return {Object} point
  8078. * @private
  8079. */
  8080. Edge.prototype._pointOnLine = function (percentage) {
  8081. return {
  8082. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  8083. y: (1 - percentage) * this.from.y + percentage * this.to.y
  8084. }
  8085. };
  8086. /**
  8087. * Get a point on a circle
  8088. * @param {Number} x
  8089. * @param {Number} y
  8090. * @param {Number} radius
  8091. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  8092. * @return {Object} point
  8093. * @private
  8094. */
  8095. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  8096. var angle = (percentage - 3/8) * 2 * Math.PI;
  8097. return {
  8098. x: x + radius * Math.cos(angle),
  8099. y: y - radius * Math.sin(angle)
  8100. }
  8101. };
  8102. /**
  8103. * Redraw a edge as a line with an arrow halfway the line
  8104. * Draw this edge in the given canvas
  8105. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8106. * @param {CanvasRenderingContext2D} ctx
  8107. * @private
  8108. */
  8109. Edge.prototype._drawArrowCenter = function(ctx) {
  8110. var point;
  8111. // set style
  8112. ctx.strokeStyle = this.color;
  8113. ctx.fillStyle = this.color;
  8114. ctx.lineWidth = this._getLineWidth();
  8115. if (this.from != this.to) {
  8116. // draw line
  8117. this._line(ctx);
  8118. // draw an arrow halfway the line
  8119. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  8120. var length = 10 + 5 * this.width; // TODO: make customizable?
  8121. point = this._pointOnLine(0.5);
  8122. ctx.arrow(point.x, point.y, angle, length);
  8123. ctx.fill();
  8124. ctx.stroke();
  8125. // draw label
  8126. if (this.label) {
  8127. point = this._pointOnLine(0.5);
  8128. this._label(ctx, this.label, point.x, point.y);
  8129. }
  8130. }
  8131. else {
  8132. // draw circle
  8133. var x, y;
  8134. var radius = this.length / 4;
  8135. var node = this.from;
  8136. if (!node.width) {
  8137. node.resize(ctx);
  8138. }
  8139. if (node.width > node.height) {
  8140. x = node.x + node.width / 2;
  8141. y = node.y - radius;
  8142. }
  8143. else {
  8144. x = node.x + radius;
  8145. y = node.y - node.height / 2;
  8146. }
  8147. this._circle(ctx, x, y, radius);
  8148. // draw all arrows
  8149. var angle = 0.2 * Math.PI;
  8150. var length = 10 + 5 * this.width; // TODO: make customizable?
  8151. point = this._pointOnCircle(x, y, radius, 0.5);
  8152. ctx.arrow(point.x, point.y, angle, length);
  8153. ctx.fill();
  8154. ctx.stroke();
  8155. // draw label
  8156. if (this.label) {
  8157. point = this._pointOnCircle(x, y, radius, 0.5);
  8158. this._label(ctx, this.label, point.x, point.y);
  8159. }
  8160. }
  8161. };
  8162. /**
  8163. * Redraw a edge as a line with an arrow
  8164. * Draw this edge in the given canvas
  8165. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8166. * @param {CanvasRenderingContext2D} ctx
  8167. * @private
  8168. */
  8169. Edge.prototype._drawArrow = function(ctx) {
  8170. // set style
  8171. ctx.strokeStyle = this.color;
  8172. ctx.fillStyle = this.color;
  8173. ctx.lineWidth = this._getLineWidth();
  8174. // draw line
  8175. var angle, length;
  8176. if (this.from != this.to) {
  8177. // calculate length and angle of the line
  8178. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  8179. var dx = (this.to.x - this.from.x);
  8180. var dy = (this.to.y - this.from.y);
  8181. var lEdge = Math.sqrt(dx * dx + dy * dy);
  8182. var lFrom = this.from.distanceToBorder(ctx, angle + Math.PI);
  8183. var pFrom = (lEdge - lFrom) / lEdge;
  8184. var xFrom = (pFrom) * this.from.x + (1 - pFrom) * this.to.x;
  8185. var yFrom = (pFrom) * this.from.y + (1 - pFrom) * this.to.y;
  8186. var lTo = this.to.distanceToBorder(ctx, angle);
  8187. var pTo = (lEdge - lTo) / lEdge;
  8188. var xTo = (1 - pTo) * this.from.x + pTo * this.to.x;
  8189. var yTo = (1 - pTo) * this.from.y + pTo * this.to.y;
  8190. ctx.beginPath();
  8191. ctx.moveTo(xFrom, yFrom);
  8192. ctx.lineTo(xTo, yTo);
  8193. ctx.stroke();
  8194. // draw arrow at the end of the line
  8195. length = 10 + 5 * this.width; // TODO: make customizable?
  8196. ctx.arrow(xTo, yTo, angle, length);
  8197. ctx.fill();
  8198. ctx.stroke();
  8199. // draw label
  8200. if (this.label) {
  8201. var point = this._pointOnLine(0.5);
  8202. this._label(ctx, this.label, point.x, point.y);
  8203. }
  8204. }
  8205. else {
  8206. // draw circle
  8207. var node = this.from;
  8208. var x, y, arrow;
  8209. var radius = this.length / 4;
  8210. if (!node.width) {
  8211. node.resize(ctx);
  8212. }
  8213. if (node.width > node.height) {
  8214. x = node.x + node.width / 2;
  8215. y = node.y - radius;
  8216. arrow = {
  8217. x: x,
  8218. y: node.y,
  8219. angle: 0.9 * Math.PI
  8220. };
  8221. }
  8222. else {
  8223. x = node.x + radius;
  8224. y = node.y - node.height / 2;
  8225. arrow = {
  8226. x: node.x,
  8227. y: y,
  8228. angle: 0.6 * Math.PI
  8229. };
  8230. }
  8231. ctx.beginPath();
  8232. // TODO: do not draw a circle, but an arc
  8233. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  8234. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  8235. ctx.stroke();
  8236. // draw all arrows
  8237. length = 10 + 5 * this.width; // TODO: make customizable?
  8238. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  8239. ctx.fill();
  8240. ctx.stroke();
  8241. // draw label
  8242. if (this.label) {
  8243. point = this._pointOnCircle(x, y, radius, 0.5);
  8244. this._label(ctx, this.label, point.x, point.y);
  8245. }
  8246. }
  8247. };
  8248. /**
  8249. * Calculate the distance between a point (x3,y3) and a line segment from
  8250. * (x1,y1) to (x2,y2).
  8251. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  8252. * @param {number} x1
  8253. * @param {number} y1
  8254. * @param {number} x2
  8255. * @param {number} y2
  8256. * @param {number} x3
  8257. * @param {number} y3
  8258. * @private
  8259. */
  8260. Edge._dist = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  8261. var px = x2-x1,
  8262. py = y2-y1,
  8263. something = px*px + py*py,
  8264. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  8265. if (u > 1) {
  8266. u = 1;
  8267. }
  8268. else if (u < 0) {
  8269. u = 0;
  8270. }
  8271. var x = x1 + u * px,
  8272. y = y1 + u * py,
  8273. dx = x - x3,
  8274. dy = y - y3;
  8275. //# Note: If the actual distance does not matter,
  8276. //# if you only want to compare what this function
  8277. //# returns to other results of this function, you
  8278. //# can just return the squared distance instead
  8279. //# (i.e. remove the sqrt) to gain a little performance
  8280. return Math.sqrt(dx*dx + dy*dy);
  8281. };
  8282. /**
  8283. * Popup is a class to create a popup window with some text
  8284. * @param {Element} container The container object.
  8285. * @param {Number} [x]
  8286. * @param {Number} [y]
  8287. * @param {String} [text]
  8288. */
  8289. function Popup(container, x, y, text) {
  8290. if (container) {
  8291. this.container = container;
  8292. }
  8293. else {
  8294. this.container = document.body;
  8295. }
  8296. this.x = 0;
  8297. this.y = 0;
  8298. this.padding = 5;
  8299. if (x !== undefined && y !== undefined ) {
  8300. this.setPosition(x, y);
  8301. }
  8302. if (text !== undefined) {
  8303. this.setText(text);
  8304. }
  8305. // create the frame
  8306. this.frame = document.createElement("div");
  8307. var style = this.frame.style;
  8308. style.position = "absolute";
  8309. style.visibility = "hidden";
  8310. style.border = "1px solid #666";
  8311. style.color = "black";
  8312. style.padding = this.padding + "px";
  8313. style.backgroundColor = "#FFFFC6";
  8314. style.borderRadius = "3px";
  8315. style.MozBorderRadius = "3px";
  8316. style.WebkitBorderRadius = "3px";
  8317. style.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  8318. style.whiteSpace = "nowrap";
  8319. this.container.appendChild(this.frame);
  8320. };
  8321. /**
  8322. * @param {number} x Horizontal position of the popup window
  8323. * @param {number} y Vertical position of the popup window
  8324. */
  8325. Popup.prototype.setPosition = function(x, y) {
  8326. this.x = parseInt(x);
  8327. this.y = parseInt(y);
  8328. };
  8329. /**
  8330. * Set the text for the popup window. This can be HTML code
  8331. * @param {string} text
  8332. */
  8333. Popup.prototype.setText = function(text) {
  8334. this.frame.innerHTML = text;
  8335. };
  8336. /**
  8337. * Show the popup window
  8338. * @param {boolean} show Optional. Show or hide the window
  8339. */
  8340. Popup.prototype.show = function (show) {
  8341. if (show === undefined) {
  8342. show = true;
  8343. }
  8344. if (show) {
  8345. var height = this.frame.clientHeight;
  8346. var width = this.frame.clientWidth;
  8347. var maxHeight = this.frame.parentNode.clientHeight;
  8348. var maxWidth = this.frame.parentNode.clientWidth;
  8349. var top = (this.y - height);
  8350. if (top + height + this.padding > maxHeight) {
  8351. top = maxHeight - height - this.padding;
  8352. }
  8353. if (top < this.padding) {
  8354. top = this.padding;
  8355. }
  8356. var left = this.x;
  8357. if (left + width + this.padding > maxWidth) {
  8358. left = maxWidth - width - this.padding;
  8359. }
  8360. if (left < this.padding) {
  8361. left = this.padding;
  8362. }
  8363. this.frame.style.left = left + "px";
  8364. this.frame.style.top = top + "px";
  8365. this.frame.style.visibility = "visible";
  8366. }
  8367. else {
  8368. this.hide();
  8369. }
  8370. };
  8371. /**
  8372. * Hide the popup window
  8373. */
  8374. Popup.prototype.hide = function () {
  8375. this.frame.style.visibility = "hidden";
  8376. };
  8377. /**
  8378. * @class Groups
  8379. * This class can store groups and properties specific for groups.
  8380. */
  8381. Groups = function () {
  8382. this.clear();
  8383. this.defaultIndex = 0;
  8384. };
  8385. /**
  8386. * default constants for group colors
  8387. */
  8388. Groups.DEFAULT = [
  8389. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  8390. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  8391. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  8392. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  8393. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  8394. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  8395. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  8396. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  8397. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  8398. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  8399. ];
  8400. /**
  8401. * Clear all groups
  8402. */
  8403. Groups.prototype.clear = function () {
  8404. this.groups = {};
  8405. this.groups.length = function()
  8406. {
  8407. var i = 0;
  8408. for ( var p in this ) {
  8409. if (this.hasOwnProperty(p)) {
  8410. i++;
  8411. }
  8412. }
  8413. return i;
  8414. }
  8415. };
  8416. /**
  8417. * get group properties of a groupname. If groupname is not found, a new group
  8418. * is added.
  8419. * @param {*} groupname Can be a number, string, Date, etc.
  8420. * @return {Object} group The created group, containing all group properties
  8421. */
  8422. Groups.prototype.get = function (groupname) {
  8423. var group = this.groups[groupname];
  8424. if (group == undefined) {
  8425. // create new group
  8426. var index = this.defaultIndex % Groups.DEFAULT.length;
  8427. this.defaultIndex++;
  8428. group = {};
  8429. group.color = Groups.DEFAULT[index];
  8430. this.groups[groupname] = group;
  8431. }
  8432. return group;
  8433. };
  8434. /**
  8435. * Add a custom group style
  8436. * @param {String} groupname
  8437. * @param {Object} style An object containing borderColor,
  8438. * backgroundColor, etc.
  8439. * @return {Object} group The created group object
  8440. */
  8441. Groups.prototype.add = function (groupname, style) {
  8442. this.groups[groupname] = style;
  8443. if (style.color) {
  8444. style.color = Node.parseColor(style.color);
  8445. }
  8446. return style;
  8447. };
  8448. /**
  8449. * @class Images
  8450. * This class loads images and keeps them stored.
  8451. */
  8452. Images = function () {
  8453. this.images = {};
  8454. this.callback = undefined;
  8455. };
  8456. /**
  8457. * Set an onload callback function. This will be called each time an image
  8458. * is loaded
  8459. * @param {function} callback
  8460. */
  8461. Images.prototype.setOnloadCallback = function(callback) {
  8462. this.callback = callback;
  8463. };
  8464. /**
  8465. *
  8466. * @param {string} url Url of the image
  8467. * @return {Image} img The image object
  8468. */
  8469. Images.prototype.load = function(url) {
  8470. var img = this.images[url];
  8471. if (img == undefined) {
  8472. // create the image
  8473. var images = this;
  8474. img = new Image();
  8475. this.images[url] = img;
  8476. img.onload = function() {
  8477. if (images.callback) {
  8478. images.callback(this);
  8479. }
  8480. };
  8481. img.src = url;
  8482. }
  8483. return img;
  8484. };
  8485. /**
  8486. * @constructor Graph
  8487. * Create a graph visualization, displaying nodes and edges.
  8488. *
  8489. * @param {Element} container The DOM element in which the Graph will
  8490. * be created. Normally a div element.
  8491. * @param {Object} data An object containing parameters
  8492. * {Array} nodes
  8493. * {Array} edges
  8494. * @param {Object} options Options
  8495. */
  8496. function Graph (container, data, options) {
  8497. // create variables and set default values
  8498. this.containerElement = container;
  8499. this.width = '100%';
  8500. this.height = '100%';
  8501. this.refreshRate = 50; // milliseconds
  8502. this.stabilize = true; // stabilize before displaying the graph
  8503. this.selectable = true;
  8504. // set constant values
  8505. this.constants = {
  8506. nodes: {
  8507. radiusMin: 5,
  8508. radiusMax: 20,
  8509. radius: 5,
  8510. distance: 100, // px
  8511. shape: 'ellipse',
  8512. image: undefined,
  8513. widthMin: 16, // px
  8514. widthMax: 64, // px
  8515. fontColor: 'black',
  8516. fontSize: 14, // px
  8517. //fontFace: verdana,
  8518. fontFace: 'arial',
  8519. color: {
  8520. border: '#2B7CE9',
  8521. background: '#97C2FC',
  8522. highlight: {
  8523. border: '#2B7CE9',
  8524. background: '#D2E5FF'
  8525. }
  8526. },
  8527. borderColor: '#2B7CE9',
  8528. backgroundColor: '#97C2FC',
  8529. highlightColor: '#D2E5FF',
  8530. group: undefined
  8531. },
  8532. edges: {
  8533. widthMin: 1,
  8534. widthMax: 15,
  8535. width: 1,
  8536. style: 'line',
  8537. color: '#343434',
  8538. fontColor: '#343434',
  8539. fontSize: 14, // px
  8540. fontFace: 'arial',
  8541. //distance: 100, //px
  8542. length: 100, // px
  8543. dash: {
  8544. length: 10,
  8545. gap: 5,
  8546. altLength: undefined
  8547. }
  8548. },
  8549. minForce: 0.05,
  8550. minVelocity: 0.02, // px/s
  8551. maxIterations: 1000 // maximum number of iteration to stabilize
  8552. };
  8553. var graph = this;
  8554. this.nodes = {}; // object with Node objects
  8555. this.edges = {}; // object with Edge objects
  8556. // TODO: create a counter to keep track on the number of nodes having values
  8557. // TODO: create a counter to keep track on the number of nodes currently moving
  8558. // TODO: create a counter to keep track on the number of edges having values
  8559. this.nodesData = null; // A DataSet or DataView
  8560. this.edgesData = null; // A DataSet or DataView
  8561. // create event listeners used to subscribe on the DataSets of the nodes and edges
  8562. var me = this;
  8563. this.nodesListeners = {
  8564. 'add': function (event, params) {
  8565. me._addNodes(params.items);
  8566. me.start();
  8567. },
  8568. 'update': function (event, params) {
  8569. me._updateNodes(params.items);
  8570. me.start();
  8571. },
  8572. 'remove': function (event, params) {
  8573. me._removeNodes(params.items);
  8574. me.start();
  8575. }
  8576. };
  8577. this.edgesListeners = {
  8578. 'add': function (event, params) {
  8579. me._addEdges(params.items);
  8580. me.start();
  8581. },
  8582. 'update': function (event, params) {
  8583. me._updateEdges(params.items);
  8584. me.start();
  8585. },
  8586. 'remove': function (event, params) {
  8587. me._removeEdges(params.items);
  8588. me.start();
  8589. }
  8590. };
  8591. this.groups = new Groups(); // object with groups
  8592. this.images = new Images(); // object with images
  8593. this.images.setOnloadCallback(function () {
  8594. graph._redraw();
  8595. });
  8596. // properties of the data
  8597. this.moving = false; // True if any of the nodes have an undefined position
  8598. this.selection = [];
  8599. this.timer = undefined;
  8600. // create a frame and canvas
  8601. this._create();
  8602. // apply options
  8603. this.setOptions(options);
  8604. // draw data
  8605. this.setData(data);
  8606. }
  8607. /**
  8608. * Set nodes and edges, and optionally options as well.
  8609. *
  8610. * @param {Object} data Object containing parameters:
  8611. * {Array | DataSet | DataView} [nodes] Array with nodes
  8612. * {Array | DataSet | DataView} [edges] Array with edges
  8613. * {String} [dot] String containing data in DOT format
  8614. * {Options} [options] Object with options
  8615. */
  8616. Graph.prototype.setData = function(data) {
  8617. if (data && data.dot && (data.nodes || data.edges)) {
  8618. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  8619. ' parameter pair "nodes" and "edges", but not both.');
  8620. }
  8621. // set options
  8622. this.setOptions(data && data.options);
  8623. // set all data
  8624. if (data && data.dot) {
  8625. // parse DOT file
  8626. if(data && data.dot) {
  8627. var dotData = vis.util.DOTToGraph(data.dot);
  8628. this.setData(dotData);
  8629. return;
  8630. }
  8631. }
  8632. else {
  8633. this._setNodes(data && data.nodes);
  8634. this._setEdges(data && data.edges);
  8635. }
  8636. // find a stable position or start animating to a stable position
  8637. if (this.stabilize) {
  8638. this._doStabilize();
  8639. }
  8640. this.start();
  8641. };
  8642. /**
  8643. * Set options
  8644. * @param {Object} options
  8645. */
  8646. Graph.prototype.setOptions = function (options) {
  8647. if (options) {
  8648. // retrieve parameter values
  8649. if (options.width != undefined) {this.width = options.width;}
  8650. if (options.height != undefined) {this.height = options.height;}
  8651. if (options.stabilize != undefined) {this.stabilize = options.stabilize;}
  8652. if (options.selectable != undefined) {this.selectable = options.selectable;}
  8653. // TODO: work out these options and document them
  8654. if (options.edges) {
  8655. for (var prop in options.edges) {
  8656. if (options.edges.hasOwnProperty(prop)) {
  8657. this.constants.edges[prop] = options.edges[prop];
  8658. }
  8659. }
  8660. if (options.edges.length != undefined &&
  8661. options.nodes && options.nodes.distance == undefined) {
  8662. this.constants.edges.length = options.edges.length;
  8663. this.constants.nodes.distance = options.edges.length * 1.25;
  8664. }
  8665. if (!options.edges.fontColor) {
  8666. this.constants.edges.fontColor = options.edges.color;
  8667. }
  8668. // Added to support dashed lines
  8669. // David Jordan
  8670. // 2012-08-08
  8671. if (options.edges.dash) {
  8672. if (options.edges.dash.length != undefined) {
  8673. this.constants.edges.dash.length = options.edges.dash.length;
  8674. }
  8675. if (options.edges.dash.gap != undefined) {
  8676. this.constants.edges.dash.gap = options.edges.dash.gap;
  8677. }
  8678. if (options.edges.dash.altLength != undefined) {
  8679. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  8680. }
  8681. }
  8682. }
  8683. if (options.nodes) {
  8684. for (prop in options.nodes) {
  8685. if (options.nodes.hasOwnProperty(prop)) {
  8686. this.constants.nodes[prop] = options.nodes[prop];
  8687. }
  8688. }
  8689. if (options.nodes.color) {
  8690. this.constants.nodes.color = Node.parseColor(options.nodes.color);
  8691. }
  8692. /*
  8693. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  8694. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  8695. */
  8696. }
  8697. if (options.groups) {
  8698. for (var groupname in options.groups) {
  8699. if (options.groups.hasOwnProperty(groupname)) {
  8700. var group = options.groups[groupname];
  8701. this.groups.add(groupname, group);
  8702. }
  8703. }
  8704. }
  8705. }
  8706. this.setSize(this.width, this.height);
  8707. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  8708. this._setScale(1);
  8709. };
  8710. /**
  8711. * fire an event
  8712. * @param {String} event The name of an event, for example "select"
  8713. * @param {Object} params Optional object with event parameters
  8714. * @private
  8715. */
  8716. Graph.prototype._trigger = function (event, params) {
  8717. events.trigger(this, event, params);
  8718. };
  8719. /**
  8720. * Create the main frame for the Graph.
  8721. * This function is executed once when a Graph object is created. The frame
  8722. * contains a canvas, and this canvas contains all objects like the axis and
  8723. * nodes.
  8724. * @private
  8725. */
  8726. Graph.prototype._create = function () {
  8727. // remove all elements from the container element.
  8728. while (this.containerElement.hasChildNodes()) {
  8729. this.containerElement.removeChild(this.containerElement.firstChild);
  8730. }
  8731. this.frame = document.createElement("div");
  8732. this.frame.className = "graph-frame";
  8733. this.frame.style.position = "relative";
  8734. this.frame.style.overflow = "hidden";
  8735. // create the graph canvas (HTML canvas element)
  8736. this.frame.canvas = document.createElement( "canvas" );
  8737. this.frame.canvas.style.position = "relative";
  8738. this.frame.appendChild(this.frame.canvas);
  8739. if (!this.frame.canvas.getContext) {
  8740. var noCanvas = document.createElement( "DIV" );
  8741. noCanvas.style.color = "red";
  8742. noCanvas.style.fontWeight = "bold" ;
  8743. noCanvas.style.padding = "10px";
  8744. noCanvas.innerHTML = "Error: your browser does not support HTML canvas";
  8745. this.frame.canvas.appendChild(noCanvas);
  8746. }
  8747. // create event listeners
  8748. var me = this;
  8749. var onmousedown = function (event) {me._onMouseDown(event);};
  8750. var onmousemove = function (event) {me._onMouseMoveTitle(event);};
  8751. var onmousewheel = function (event) {me._onMouseWheel(event);};
  8752. var ontouchstart = function (event) {me._onTouchStart(event);};
  8753. vis.util.addEventListener(this.frame.canvas, "mousedown", onmousedown);
  8754. vis.util.addEventListener(this.frame.canvas, "mousemove", onmousemove);
  8755. vis.util.addEventListener(this.frame.canvas, "mousewheel", onmousewheel);
  8756. vis.util.addEventListener(this.frame.canvas, "touchstart", ontouchstart);
  8757. // add the frame to the container element
  8758. this.containerElement.appendChild(this.frame);
  8759. };
  8760. /**
  8761. * handle on mouse down event
  8762. * @private
  8763. */
  8764. Graph.prototype._onMouseDown = function (event) {
  8765. event = event || window.event;
  8766. if (!this.selectable) {
  8767. return;
  8768. }
  8769. // check if mouse is still down (may be up when focus is lost for example
  8770. // in an iframe)
  8771. if (this.leftButtonDown) {
  8772. this._onMouseUp(event);
  8773. }
  8774. // only react on left mouse button down
  8775. this.leftButtonDown = event.which ? (event.which == 1) : (event.button == 1);
  8776. if (!this.leftButtonDown && !this.touchDown) {
  8777. return;
  8778. }
  8779. // add event listeners to handle moving the contents
  8780. // we store the function onmousemove and onmouseup in the timeline, so we can
  8781. // remove the eventlisteners lateron in the function mouseUp()
  8782. var me = this;
  8783. if (!this.onmousemove) {
  8784. this.onmousemove = function (event) {me._onMouseMove(event);};
  8785. vis.util.addEventListener(document, "mousemove", me.onmousemove);
  8786. }
  8787. if (!this.onmouseup) {
  8788. this.onmouseup = function (event) {me._onMouseUp(event);};
  8789. vis.util.addEventListener(document, "mouseup", me.onmouseup);
  8790. }
  8791. vis.util.preventDefault(event);
  8792. // store the start x and y position of the mouse
  8793. this.startMouseX = util.getPageX(event);
  8794. this.startMouseY = util.getPageY(event);
  8795. this.startFrameLeft = vis.util.getAbsoluteLeft(this.frame.canvas);
  8796. this.startFrameTop = vis.util.getAbsoluteTop(this.frame.canvas);
  8797. this.startTranslation = this._getTranslation();
  8798. this.ctrlKeyDown = event.ctrlKey;
  8799. this.shiftKeyDown = event.shiftKey;
  8800. var obj = {
  8801. left: this._xToCanvas(this.startMouseX - this.startFrameLeft),
  8802. top: this._yToCanvas(this.startMouseY - this.startFrameTop),
  8803. right: this._xToCanvas(this.startMouseX - this.startFrameLeft),
  8804. bottom: this._yToCanvas(this.startMouseY - this.startFrameTop)
  8805. };
  8806. var overlappingNodes = this._getNodesOverlappingWith(obj);
  8807. // if there are overlapping nodes, select the last one, this is the
  8808. // one which is drawn on top of the others
  8809. this.startClickedObj = (overlappingNodes.length > 0) ?
  8810. overlappingNodes[overlappingNodes.length - 1] : undefined;
  8811. if (this.startClickedObj) {
  8812. // move clicked node with the mouse
  8813. // make the clicked node temporarily fixed, and store their original state
  8814. var node = this.nodes[this.startClickedObj];
  8815. this.startClickedObj.xFixed = node.xFixed;
  8816. this.startClickedObj.yFixed = node.yFixed;
  8817. node.xFixed = true;
  8818. node.yFixed = true;
  8819. if (!this.ctrlKeyDown || !node.isSelected()) {
  8820. // select this node
  8821. this._selectNodes([this.startClickedObj], this.ctrlKeyDown);
  8822. }
  8823. else {
  8824. // unselect this node
  8825. this._unselectNodes([this.startClickedObj]);
  8826. }
  8827. if (!this.moving) {
  8828. this._redraw();
  8829. }
  8830. }
  8831. else if (this.shiftKeyDown) {
  8832. // start selection of multiple nodes
  8833. }
  8834. else {
  8835. // start moving the graph
  8836. this.moved = false;
  8837. }
  8838. };
  8839. /**
  8840. * handle on mouse move event
  8841. * @param {Event} event
  8842. * @private
  8843. */
  8844. Graph.prototype._onMouseMove = function (event) {
  8845. event = event || window.event;
  8846. if (!this.selectable) {
  8847. return;
  8848. }
  8849. var mouseX = util.getPageX(event);
  8850. var mouseY = util.getPageY(event);
  8851. this.mouseX = mouseX;
  8852. this.mouseY = mouseY;
  8853. if (this.startClickedObj) {
  8854. var node = this.nodes[this.startClickedObj];
  8855. if (!this.startClickedObj.xFixed)
  8856. node.x = this._xToCanvas(mouseX - this.startFrameLeft);
  8857. if (!this.startClickedObj.yFixed)
  8858. node.y = this._yToCanvas(mouseY - this.startFrameTop);
  8859. // start animation if not yet running
  8860. if (!this.moving) {
  8861. this.moving = true;
  8862. this.start();
  8863. }
  8864. }
  8865. else if (this.shiftKeyDown) {
  8866. // draw a rect from start mouse location to current mouse location
  8867. if (this.frame.selRect == undefined) {
  8868. this.frame.selRect = document.createElement("DIV");
  8869. this.frame.appendChild(this.frame.selRect);
  8870. this.frame.selRect.style.position = "absolute";
  8871. this.frame.selRect.style.border = "1px dashed red";
  8872. }
  8873. var left = Math.min(this.startMouseX, mouseX) - this.startFrameLeft;
  8874. var top = Math.min(this.startMouseY, mouseY) - this.startFrameTop;
  8875. var right = Math.max(this.startMouseX, mouseX) - this.startFrameLeft;
  8876. var bottom = Math.max(this.startMouseY, mouseY) - this.startFrameTop;
  8877. this.frame.selRect.style.left = left + "px";
  8878. this.frame.selRect.style.top = top + "px";
  8879. this.frame.selRect.style.width = (right - left) + "px";
  8880. this.frame.selRect.style.height = (bottom - top) + "px";
  8881. }
  8882. else {
  8883. // move the graph
  8884. var diffX = mouseX - this.startMouseX;
  8885. var diffY = mouseY - this.startMouseY;
  8886. this._setTranslation(
  8887. this.startTranslation.x + diffX,
  8888. this.startTranslation.y + diffY);
  8889. this._redraw();
  8890. this.moved = true;
  8891. }
  8892. vis.util.preventDefault(event);
  8893. };
  8894. /**
  8895. * handle on mouse up event
  8896. * @param {Event} event
  8897. * @private
  8898. */
  8899. Graph.prototype._onMouseUp = function (event) {
  8900. event = event || window.event;
  8901. if (!this.selectable) {
  8902. return;
  8903. }
  8904. // remove event listeners here, important for Safari
  8905. if (this.onmousemove) {
  8906. vis.util.removeEventListener(document, "mousemove", this.onmousemove);
  8907. this.onmousemove = undefined;
  8908. }
  8909. if (this.onmouseup) {
  8910. vis.util.removeEventListener(document, "mouseup", this.onmouseup);
  8911. this.onmouseup = undefined;
  8912. }
  8913. vis.util.preventDefault(event);
  8914. // check selected nodes
  8915. var endMouseX = util.getPageX(event) || this.mouseX || 0;
  8916. var endMouseY = util.getPageY(event) || this.mouseY || 0;
  8917. var ctrlKey = event ? event.ctrlKey : window.event.ctrlKey;
  8918. if (this.startClickedObj) {
  8919. // restore the original fixed state
  8920. var node = this.nodes[this.startClickedObj];
  8921. node.xFixed = this.startClickedObj.xFixed;
  8922. node.yFixed = this.startClickedObj.yFixed;
  8923. }
  8924. else if (this.shiftKeyDown) {
  8925. // select nodes inside selection area
  8926. var obj = {
  8927. "left": this._xToCanvas(Math.min(this.startMouseX, endMouseX) - this.startFrameLeft),
  8928. "top": this._yToCanvas(Math.min(this.startMouseY, endMouseY) - this.startFrameTop),
  8929. "right": this._xToCanvas(Math.max(this.startMouseX, endMouseX) - this.startFrameLeft),
  8930. "bottom": this._yToCanvas(Math.max(this.startMouseY, endMouseY) - this.startFrameTop)
  8931. };
  8932. var overlappingNodes = this._getNodesOverlappingWith(obj);
  8933. this._selectNodes(overlappingNodes, ctrlKey);
  8934. this.redraw();
  8935. // remove the selection rectangle
  8936. if (this.frame.selRect) {
  8937. this.frame.removeChild(this.frame.selRect);
  8938. this.frame.selRect = undefined;
  8939. }
  8940. }
  8941. else {
  8942. if (!this.ctrlKeyDown && !this.moved) {
  8943. // remove selection
  8944. this._unselectNodes();
  8945. this._redraw();
  8946. }
  8947. }
  8948. this.leftButtonDown = false;
  8949. this.ctrlKeyDown = false;
  8950. };
  8951. /**
  8952. * Event handler for mouse wheel event, used to zoom the timeline
  8953. * Code from http://adomas.org/javascript-mouse-wheel/
  8954. * @param {Event} event
  8955. * @private
  8956. */
  8957. Graph.prototype._onMouseWheel = function(event) {
  8958. event = event || window.event;
  8959. var mouseX = util.getPageX(event);
  8960. var mouseY = util.getPageY(event);
  8961. // retrieve delta
  8962. var delta = 0;
  8963. if (event.wheelDelta) { /* IE/Opera. */
  8964. delta = event.wheelDelta/120;
  8965. } else if (event.detail) { /* Mozilla case. */
  8966. // In Mozilla, sign of delta is different than in IE.
  8967. // Also, delta is multiple of 3.
  8968. delta = -event.detail/3;
  8969. }
  8970. // If delta is nonzero, handle it.
  8971. // Basically, delta is now positive if wheel was scrolled up,
  8972. // and negative, if wheel was scrolled down.
  8973. if (delta) {
  8974. // determine zoom factor, and adjust the zoom factor such that zooming in
  8975. // and zooming out correspond wich each other
  8976. var zoom = delta / 10;
  8977. if (delta < 0) {
  8978. zoom = zoom / (1 - zoom);
  8979. }
  8980. var scaleOld = this._getScale();
  8981. var scaleNew = scaleOld * (1 + zoom);
  8982. if (scaleNew < 0.01) {
  8983. scaleNew = 0.01;
  8984. }
  8985. if (scaleNew > 10) {
  8986. scaleNew = 10;
  8987. }
  8988. var frameLeft = vis.util.getAbsoluteLeft(this.frame.canvas);
  8989. var frameTop = vis.util.getAbsoluteTop(this.frame.canvas);
  8990. var x = mouseX - frameLeft;
  8991. var y = mouseY - frameTop;
  8992. var translation = this._getTranslation();
  8993. var scaleFrac = scaleNew / scaleOld;
  8994. var tx = (1 - scaleFrac) * x + translation.x * scaleFrac;
  8995. var ty = (1 - scaleFrac) * y + translation.y * scaleFrac;
  8996. this._setScale(scaleNew);
  8997. this._setTranslation(tx, ty);
  8998. this._redraw();
  8999. }
  9000. // Prevent default actions caused by mouse wheel.
  9001. // That might be ugly, but we handle scrolls somehow
  9002. // anyway, so don't bother here...
  9003. vis.util.preventDefault(event);
  9004. };
  9005. /**
  9006. * Mouse move handler for checking whether the title moves over a node with a title.
  9007. * @param {Event} event
  9008. * @private
  9009. */
  9010. Graph.prototype._onMouseMoveTitle = function (event) {
  9011. event = event || window.event;
  9012. var startMouseX = util.getPageX(event);
  9013. var startMouseY = util.getPageY(event);
  9014. this.startFrameLeft = this.startFrameLeft || vis.util.getAbsoluteLeft(this.frame.canvas);
  9015. this.startFrameTop = this.startFrameTop || vis.util.getAbsoluteTop(this.frame.canvas);
  9016. var x = startMouseX - this.startFrameLeft;
  9017. var y = startMouseY - this.startFrameTop;
  9018. // check if the previously selected node is still selected
  9019. if (this.popupNode) {
  9020. this._checkHidePopup(x, y);
  9021. }
  9022. // start a timeout that will check if the mouse is positioned above
  9023. // an element
  9024. var me = this;
  9025. var checkShow = function() {
  9026. me._checkShowPopup(x, y);
  9027. };
  9028. if (this.popupTimer) {
  9029. clearInterval(this.popupTimer); // stop any running timer
  9030. }
  9031. if (!this.leftButtonDown) {
  9032. this.popupTimer = setTimeout(checkShow, 300);
  9033. }
  9034. };
  9035. /**
  9036. * Check if there is an element on the given position in the graph
  9037. * (a node or edge). If so, and if this element has a title,
  9038. * show a popup window with its title.
  9039. *
  9040. * @param {number} x
  9041. * @param {number} y
  9042. * @private
  9043. */
  9044. Graph.prototype._checkShowPopup = function (x, y) {
  9045. var obj = {
  9046. "left" : this._xToCanvas(x),
  9047. "top" : this._yToCanvas(y),
  9048. "right" : this._xToCanvas(x),
  9049. "bottom" : this._yToCanvas(y)
  9050. };
  9051. var id;
  9052. var lastPopupNode = this.popupNode;
  9053. if (this.popupNode == undefined) {
  9054. // search the nodes for overlap, select the top one in case of multiple nodes
  9055. var nodes = this.nodes;
  9056. for (id in nodes) {
  9057. if (nodes.hasOwnProperty(id)) {
  9058. var node = nodes[id];
  9059. if (node.getTitle() != undefined && node.isOverlappingWith(obj)) {
  9060. this.popupNode = node;
  9061. break;
  9062. }
  9063. }
  9064. }
  9065. }
  9066. if (this.popupNode == undefined) {
  9067. // search the edges for overlap
  9068. var edges = this.edges;
  9069. for (id in edges) {
  9070. if (edges.hasOwnProperty(id)) {
  9071. var edge = edges[id];
  9072. if (edge.connected && (edge.getTitle() != undefined) &&
  9073. edge.isOverlappingWith(obj)) {
  9074. this.popupNode = edge;
  9075. break;
  9076. }
  9077. }
  9078. }
  9079. }
  9080. if (this.popupNode) {
  9081. // show popup message window
  9082. if (this.popupNode != lastPopupNode) {
  9083. var me = this;
  9084. if (!me.popup) {
  9085. me.popup = new Popup(me.frame);
  9086. }
  9087. // adjust a small offset such that the mouse cursor is located in the
  9088. // bottom left location of the popup, and you can easily move over the
  9089. // popup area
  9090. me.popup.setPosition(x - 3, y - 3);
  9091. me.popup.setText(me.popupNode.getTitle());
  9092. me.popup.show();
  9093. }
  9094. }
  9095. else {
  9096. if (this.popup) {
  9097. this.popup.hide();
  9098. }
  9099. }
  9100. };
  9101. /**
  9102. * Check if the popup must be hided, which is the case when the mouse is no
  9103. * longer hovering on the object
  9104. * @param {number} x
  9105. * @param {number} y
  9106. * @private
  9107. */
  9108. Graph.prototype._checkHidePopup = function (x, y) {
  9109. var obj = {
  9110. "left" : x,
  9111. "top" : y,
  9112. "right" : x,
  9113. "bottom" : y
  9114. };
  9115. if (!this.popupNode || !this.popupNode.isOverlappingWith(obj) ) {
  9116. this.popupNode = undefined;
  9117. if (this.popup) {
  9118. this.popup.hide();
  9119. }
  9120. }
  9121. };
  9122. /**
  9123. * Event handler for touchstart event on mobile devices
  9124. * @param {Event} event
  9125. * @private
  9126. */
  9127. Graph.prototype._onTouchStart = function(event) {
  9128. vis.util.preventDefault(event);
  9129. if (this.touchDown) {
  9130. // if already moving, return
  9131. return;
  9132. }
  9133. this.touchDown = true;
  9134. var me = this;
  9135. if (!this.ontouchmove) {
  9136. this.ontouchmove = function (event) {me._onTouchMove(event);};
  9137. vis.util.addEventListener(document, "touchmove", this.ontouchmove);
  9138. }
  9139. if (!this.ontouchend) {
  9140. this.ontouchend = function (event) {me._onTouchEnd(event);};
  9141. vis.util.addEventListener(document, "touchend", this.ontouchend);
  9142. }
  9143. this._onMouseDown(event);
  9144. };
  9145. /**
  9146. * Event handler for touchmove event on mobile devices
  9147. * @param {Event} event
  9148. * @private
  9149. */
  9150. Graph.prototype._onTouchMove = function(event) {
  9151. vis.util.preventDefault(event);
  9152. this._onMouseMove(event);
  9153. };
  9154. /**
  9155. * Event handler for touchend event on mobile devices
  9156. * @param {Event} event
  9157. * @private
  9158. */
  9159. Graph.prototype._onTouchEnd = function(event) {
  9160. vis.util.preventDefault(event);
  9161. this.touchDown = false;
  9162. if (this.ontouchmove) {
  9163. vis.util.removeEventListener(document, "touchmove", this.ontouchmove);
  9164. this.ontouchmove = undefined;
  9165. }
  9166. if (this.ontouchend) {
  9167. vis.util.removeEventListener(document, "touchend", this.ontouchend);
  9168. this.ontouchend = undefined;
  9169. }
  9170. this._onMouseUp(event);
  9171. };
  9172. /**
  9173. * Unselect selected nodes. If no selection array is provided, all nodes
  9174. * are unselected
  9175. * @param {Object[]} selection Array with selection objects, each selection
  9176. * object has a parameter row. Optional
  9177. * @param {Boolean} triggerSelect If true (default), the select event
  9178. * is triggered when nodes are unselected
  9179. * @return {Boolean} changed True if the selection is changed
  9180. * @private
  9181. */
  9182. Graph.prototype._unselectNodes = function(selection, triggerSelect) {
  9183. var changed = false;
  9184. var i, iMax, id;
  9185. if (selection) {
  9186. // remove provided selections
  9187. for (i = 0, iMax = selection.length; i < iMax; i++) {
  9188. id = selection[i];
  9189. this.nodes[id].unselect();
  9190. var j = 0;
  9191. while (j < this.selection.length) {
  9192. if (this.selection[j] == id) {
  9193. this.selection.splice(j, 1);
  9194. changed = true;
  9195. }
  9196. else {
  9197. j++;
  9198. }
  9199. }
  9200. }
  9201. }
  9202. else if (this.selection && this.selection.length) {
  9203. // remove all selections
  9204. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  9205. id = this.selection[i];
  9206. this.nodes[id].unselect();
  9207. changed = true;
  9208. }
  9209. this.selection = [];
  9210. }
  9211. if (changed && (triggerSelect == true || triggerSelect == undefined)) {
  9212. // fire the select event
  9213. this._trigger('select');
  9214. }
  9215. return changed;
  9216. };
  9217. /**
  9218. * select all nodes on given location x, y
  9219. * @param {Array} selection an array with node ids
  9220. * @param {boolean} append If true, the new selection will be appended to the
  9221. * current selection (except for duplicate entries)
  9222. * @return {Boolean} changed True if the selection is changed
  9223. * @private
  9224. */
  9225. Graph.prototype._selectNodes = function(selection, append) {
  9226. var changed = false;
  9227. var i, iMax;
  9228. // TODO: the selectNodes method is a little messy, rework this
  9229. // check if the current selection equals the desired selection
  9230. var selectionAlreadyThere = true;
  9231. if (selection.length != this.selection.length) {
  9232. selectionAlreadyThere = false;
  9233. }
  9234. else {
  9235. for (i = 0, iMax = Math.min(selection.length, this.selection.length); i < iMax; i++) {
  9236. if (selection[i] != this.selection[i]) {
  9237. selectionAlreadyThere = false;
  9238. break;
  9239. }
  9240. }
  9241. }
  9242. if (selectionAlreadyThere) {
  9243. return changed;
  9244. }
  9245. if (append == undefined || append == false) {
  9246. // first deselect any selected node
  9247. var triggerSelect = false;
  9248. changed = this._unselectNodes(undefined, triggerSelect);
  9249. }
  9250. for (i = 0, iMax = selection.length; i < iMax; i++) {
  9251. // add each of the new selections, but only when they are not duplicate
  9252. var id = selection[i];
  9253. var isDuplicate = (this.selection.indexOf(id) != -1);
  9254. if (!isDuplicate) {
  9255. this.nodes[id].select();
  9256. this.selection.push(id);
  9257. changed = true;
  9258. }
  9259. }
  9260. if (changed) {
  9261. // fire the select event
  9262. this._trigger('select');
  9263. }
  9264. return changed;
  9265. };
  9266. /**
  9267. * retrieve all nodes overlapping with given object
  9268. * @param {Object} obj An object with parameters left, top, right, bottom
  9269. * @return {Object[]} An array with selection objects containing
  9270. * the parameter row.
  9271. * @private
  9272. */
  9273. Graph.prototype._getNodesOverlappingWith = function (obj) {
  9274. var nodes = this.nodes,
  9275. overlappingNodes = [];
  9276. for (var id in nodes) {
  9277. if (nodes.hasOwnProperty(id)) {
  9278. if (nodes[id].isOverlappingWith(obj)) {
  9279. overlappingNodes.push(id);
  9280. }
  9281. }
  9282. }
  9283. return overlappingNodes;
  9284. };
  9285. /**
  9286. * retrieve the currently selected nodes
  9287. * @return {Number[] | String[]} selection An array with the ids of the
  9288. * selected nodes.
  9289. */
  9290. Graph.prototype.getSelection = function() {
  9291. return this.selection.concat([]);
  9292. };
  9293. /**
  9294. * select zero or more nodes
  9295. * @param {Number[] | String[]} selection An array with the ids of the
  9296. * selected nodes.
  9297. */
  9298. Graph.prototype.setSelection = function(selection) {
  9299. var i, iMax, id;
  9300. if (selection.length == undefined)
  9301. throw "Selection must be an array with ids";
  9302. // first unselect any selected node
  9303. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  9304. id = this.selection[i];
  9305. this.nodes[id].unselect();
  9306. }
  9307. this.selection = [];
  9308. for (i = 0, iMax = selection.length; i < iMax; i++) {
  9309. id = selection[i];
  9310. var node = this.nodes[id];
  9311. if (!node) {
  9312. throw new RangeError('Node with id "' + id + '" not found');
  9313. }
  9314. node.select();
  9315. this.selection.push(id);
  9316. }
  9317. this.redraw();
  9318. };
  9319. /**
  9320. * Validate the selection: remove ids of nodes which no longer exist
  9321. * @private
  9322. */
  9323. Graph.prototype._updateSelection = function () {
  9324. var i = 0;
  9325. while (i < this.selection.length) {
  9326. var id = this.selection[i];
  9327. if (!this.nodes[id]) {
  9328. this.selection.splice(i, 1);
  9329. }
  9330. else {
  9331. i++;
  9332. }
  9333. }
  9334. };
  9335. /**
  9336. * Temporary method to test calculating a hub value for the nodes
  9337. * @param {number} level Maximum number edges between two nodes in order
  9338. * to call them connected. Optional, 1 by default
  9339. * @return {Number[]} connectioncount array with the connection count
  9340. * for each node
  9341. * @private
  9342. */
  9343. Graph.prototype._getConnectionCount = function(level) {
  9344. if (level == undefined) {
  9345. level = 1;
  9346. }
  9347. // get the nodes connected to given nodes
  9348. function getConnectedNodes(nodes) {
  9349. var connectedNodes = [];
  9350. for (var j = 0, jMax = nodes.length; j < jMax; j++) {
  9351. var node = nodes[j];
  9352. // find all nodes connected to this node
  9353. var edges = node.edges;
  9354. for (var i = 0, iMax = edges.length; i < iMax; i++) {
  9355. var edge = edges[i];
  9356. var other = null;
  9357. // check if connected
  9358. if (edge.from == node)
  9359. other = edge.to;
  9360. else if (edge.to == node)
  9361. other = edge.from;
  9362. // check if the other node is not already in the list with nodes
  9363. var k, kMax;
  9364. if (other) {
  9365. for (k = 0, kMax = nodes.length; k < kMax; k++) {
  9366. if (nodes[k] == other) {
  9367. other = null;
  9368. break;
  9369. }
  9370. }
  9371. }
  9372. if (other) {
  9373. for (k = 0, kMax = connectedNodes.length; k < kMax; k++) {
  9374. if (connectedNodes[k] == other) {
  9375. other = null;
  9376. break;
  9377. }
  9378. }
  9379. }
  9380. if (other)
  9381. connectedNodes.push(other);
  9382. }
  9383. }
  9384. return connectedNodes;
  9385. }
  9386. var connections = [];
  9387. var nodes = this.nodes;
  9388. for (var id in nodes) {
  9389. if (nodes.hasOwnProperty(id)) {
  9390. var c = [nodes[id]];
  9391. for (var l = 0; l < level; l++) {
  9392. c = c.concat(getConnectedNodes(c));
  9393. }
  9394. connections.push(c);
  9395. }
  9396. }
  9397. var hubs = [];
  9398. for (var i = 0, len = connections.length; i < len; i++) {
  9399. hubs.push(connections[i].length);
  9400. }
  9401. return hubs;
  9402. };
  9403. /**
  9404. * Set a new size for the graph
  9405. * @param {string} width Width in pixels or percentage (for example "800px"
  9406. * or "50%")
  9407. * @param {string} height Height in pixels or percentage (for example "400px"
  9408. * or "30%")
  9409. */
  9410. Graph.prototype.setSize = function(width, height) {
  9411. this.frame.style.width = width;
  9412. this.frame.style.height = height;
  9413. this.frame.canvas.style.width = "100%";
  9414. this.frame.canvas.style.height = "100%";
  9415. this.frame.canvas.width = this.frame.canvas.clientWidth;
  9416. this.frame.canvas.height = this.frame.canvas.clientHeight;
  9417. };
  9418. /**
  9419. * Set a data set with nodes for the graph
  9420. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  9421. * @private
  9422. */
  9423. Graph.prototype._setNodes = function(nodes) {
  9424. var oldNodesData = this.nodesData;
  9425. if (nodes instanceof DataSet || nodes instanceof DataView) {
  9426. this.nodesData = nodes;
  9427. }
  9428. else if (nodes instanceof Array) {
  9429. this.nodesData = new DataSet();
  9430. this.nodesData.add(nodes);
  9431. }
  9432. else if (!nodes) {
  9433. this.nodesData = new DataSet();
  9434. }
  9435. else {
  9436. throw new TypeError('Array or DataSet expected');
  9437. }
  9438. if (oldNodesData) {
  9439. // unsubscribe from old dataset
  9440. util.forEach(this.nodesListeners, function (callback, event) {
  9441. oldNodesData.unsubscribe(event, callback);
  9442. });
  9443. }
  9444. // remove drawn nodes
  9445. this.nodes = {};
  9446. if (this.nodesData) {
  9447. // subscribe to new dataset
  9448. var me = this;
  9449. util.forEach(this.nodesListeners, function (callback, event) {
  9450. me.nodesData.subscribe(event, callback);
  9451. });
  9452. // draw all new nodes
  9453. var ids = this.nodesData.getIds();
  9454. this._addNodes(ids);
  9455. }
  9456. this._updateSelection();
  9457. };
  9458. /**
  9459. * Add nodes
  9460. * @param {Number[] | String[]} ids
  9461. * @private
  9462. */
  9463. Graph.prototype._addNodes = function(ids) {
  9464. var id;
  9465. for (var i = 0, len = ids.length; i < len; i++) {
  9466. id = ids[i];
  9467. var data = this.nodesData.get(id);
  9468. var node = new Node(data, this.images, this.groups, this.constants);
  9469. this.nodes[id] = node; // note: this may replace an existing node
  9470. if (!node.isFixed()) {
  9471. // TODO: position new nodes in a smarter way!
  9472. var radius = this.constants.edges.length * 2;
  9473. var count = ids.length;
  9474. var angle = 2 * Math.PI * (i / count);
  9475. node.x = radius * Math.cos(angle);
  9476. node.y = radius * Math.sin(angle);
  9477. // note: no not use node.isMoving() here, as that gives the current
  9478. // velocity of the node, which is zero after creation of the node.
  9479. this.moving = true;
  9480. }
  9481. }
  9482. this._reconnectEdges();
  9483. this._updateValueRange(this.nodes);
  9484. };
  9485. /**
  9486. * Update existing nodes, or create them when not yet existing
  9487. * @param {Number[] | String[]} ids
  9488. * @private
  9489. */
  9490. Graph.prototype._updateNodes = function(ids) {
  9491. var nodes = this.nodes,
  9492. nodesData = this.nodesData;
  9493. for (var i = 0, len = ids.length; i < len; i++) {
  9494. var id = ids[i];
  9495. var node = nodes[id];
  9496. var data = nodesData.get(id);
  9497. if (node) {
  9498. // update node
  9499. node.setProperties(data, this.constants);
  9500. }
  9501. else {
  9502. // create node
  9503. node = new Node(properties, this.images, this.groups, this.constants);
  9504. nodes[id] = node;
  9505. if (!node.isFixed()) {
  9506. this.moving = true;
  9507. }
  9508. }
  9509. }
  9510. this._reconnectEdges();
  9511. this._updateValueRange(nodes);
  9512. };
  9513. /**
  9514. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  9515. * @param {Number[] | String[]} ids
  9516. * @private
  9517. */
  9518. Graph.prototype._removeNodes = function(ids) {
  9519. var nodes = this.nodes;
  9520. for (var i = 0, len = ids.length; i < len; i++) {
  9521. var id = ids[i];
  9522. delete nodes[id];
  9523. }
  9524. this._reconnectEdges();
  9525. this._updateSelection();
  9526. this._updateValueRange(nodes);
  9527. };
  9528. /**
  9529. * Load edges by reading the data table
  9530. * @param {Array | DataSet | DataView} edges The data containing the edges.
  9531. * @private
  9532. * @private
  9533. */
  9534. Graph.prototype._setEdges = function(edges) {
  9535. var oldEdgesData = this.edgesData;
  9536. if (edges instanceof DataSet || edges instanceof DataView) {
  9537. this.edgesData = edges;
  9538. }
  9539. else if (edges instanceof Array) {
  9540. this.edgesData = new DataSet();
  9541. this.edgesData.add(edges);
  9542. }
  9543. else if (!edges) {
  9544. this.edgesData = new DataSet();
  9545. }
  9546. else {
  9547. throw new TypeError('Array or DataSet expected');
  9548. }
  9549. if (oldEdgesData) {
  9550. // unsubscribe from old dataset
  9551. util.forEach(this.edgesListeners, function (callback, event) {
  9552. oldEdgesData.unsubscribe(event, callback);
  9553. });
  9554. }
  9555. // remove drawn edges
  9556. this.edges = {};
  9557. if (this.edgesData) {
  9558. // subscribe to new dataset
  9559. var me = this;
  9560. util.forEach(this.edgesListeners, function (callback, event) {
  9561. me.edgesData.subscribe(event, callback);
  9562. });
  9563. // draw all new nodes
  9564. var ids = this.edgesData.getIds();
  9565. this._addEdges(ids);
  9566. }
  9567. this._reconnectEdges();
  9568. };
  9569. /**
  9570. * Add edges
  9571. * @param {Number[] | String[]} ids
  9572. * @private
  9573. */
  9574. Graph.prototype._addEdges = function (ids) {
  9575. var edges = this.edges,
  9576. edgesData = this.edgesData;
  9577. for (var i = 0, len = ids.length; i < len; i++) {
  9578. var id = ids[i];
  9579. var oldEdge = edges[id];
  9580. if (oldEdge) {
  9581. oldEdge.disconnect();
  9582. }
  9583. var data = edgesData.get(id);
  9584. edges[id] = new Edge(data, this, this.constants);
  9585. }
  9586. this.moving = true;
  9587. this._updateValueRange(edges);
  9588. };
  9589. /**
  9590. * Update existing edges, or create them when not yet existing
  9591. * @param {Number[] | String[]} ids
  9592. * @private
  9593. */
  9594. Graph.prototype._updateEdges = function (ids) {
  9595. var edges = this.edges,
  9596. edgesData = this.edgesData;
  9597. for (var i = 0, len = ids.length; i < len; i++) {
  9598. var id = ids[i];
  9599. var data = edgesData.get(id);
  9600. var edge = edges[id];
  9601. if (edge) {
  9602. // update edge
  9603. edge.disconnect();
  9604. edge.setProperties(data, this.constants);
  9605. edge.connect();
  9606. }
  9607. else {
  9608. // create edge
  9609. edge = new Edge(data, this, this.constants);
  9610. this.edges[id] = edge;
  9611. }
  9612. }
  9613. this.moving = true;
  9614. this._updateValueRange(edges);
  9615. };
  9616. /**
  9617. * Remove existing edges. Non existing ids will be ignored
  9618. * @param {Number[] | String[]} ids
  9619. * @private
  9620. */
  9621. Graph.prototype._removeEdges = function (ids) {
  9622. var edges = this.edges;
  9623. for (var i = 0, len = ids.length; i < len; i++) {
  9624. var id = ids[i];
  9625. var edge = edges[id];
  9626. if (edge) {
  9627. edge.disconnect();
  9628. delete edges[id];
  9629. }
  9630. }
  9631. this.moving = true;
  9632. this._updateValueRange(edges);
  9633. };
  9634. /**
  9635. * Reconnect all edges
  9636. * @private
  9637. */
  9638. Graph.prototype._reconnectEdges = function() {
  9639. var id,
  9640. nodes = this.nodes,
  9641. edges = this.edges;
  9642. for (id in nodes) {
  9643. if (nodes.hasOwnProperty(id)) {
  9644. nodes[id].edges = [];
  9645. }
  9646. }
  9647. for (id in edges) {
  9648. if (edges.hasOwnProperty(id)) {
  9649. var edge = edges[id];
  9650. edge.from = null;
  9651. edge.to = null;
  9652. edge.connect();
  9653. }
  9654. }
  9655. };
  9656. /**
  9657. * Update the values of all object in the given array according to the current
  9658. * value range of the objects in the array.
  9659. * @param {Object} obj An object containing a set of Edges or Nodes
  9660. * The objects must have a method getValue() and
  9661. * setValueRange(min, max).
  9662. * @private
  9663. */
  9664. Graph.prototype._updateValueRange = function(obj) {
  9665. var id;
  9666. // determine the range of the objects
  9667. var valueMin = undefined;
  9668. var valueMax = undefined;
  9669. for (id in obj) {
  9670. if (obj.hasOwnProperty(id)) {
  9671. var value = obj[id].getValue();
  9672. if (value !== undefined) {
  9673. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  9674. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  9675. }
  9676. }
  9677. }
  9678. // adjust the range of all objects
  9679. if (valueMin !== undefined && valueMax !== undefined) {
  9680. for (id in obj) {
  9681. if (obj.hasOwnProperty(id)) {
  9682. obj[id].setValueRange(valueMin, valueMax);
  9683. }
  9684. }
  9685. }
  9686. };
  9687. /**
  9688. * Redraw the graph with the current data
  9689. * chart will be resized too.
  9690. */
  9691. Graph.prototype.redraw = function() {
  9692. this.setSize(this.width, this.height);
  9693. this._redraw();
  9694. };
  9695. /**
  9696. * Redraw the graph with the current data
  9697. * @private
  9698. */
  9699. Graph.prototype._redraw = function() {
  9700. var ctx = this.frame.canvas.getContext("2d");
  9701. // clear the canvas
  9702. var w = this.frame.canvas.width;
  9703. var h = this.frame.canvas.height;
  9704. ctx.clearRect(0, 0, w, h);
  9705. // set scaling and translation
  9706. ctx.save();
  9707. ctx.translate(this.translation.x, this.translation.y);
  9708. ctx.scale(this.scale, this.scale);
  9709. this._drawEdges(ctx);
  9710. this._drawNodes(ctx);
  9711. // restore original scaling and translation
  9712. ctx.restore();
  9713. };
  9714. /**
  9715. * Set the translation of the graph
  9716. * @param {Number} offsetX Horizontal offset
  9717. * @param {Number} offsetY Vertical offset
  9718. * @private
  9719. */
  9720. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  9721. if (this.translation === undefined) {
  9722. this.translation = {
  9723. "x": 0,
  9724. "y": 0
  9725. };
  9726. }
  9727. if (offsetX !== undefined) {
  9728. this.translation.x = offsetX;
  9729. }
  9730. if (offsetY !== undefined) {
  9731. this.translation.y = offsetY;
  9732. }
  9733. };
  9734. /**
  9735. * Get the translation of the graph
  9736. * @return {Object} translation An object with parameters x and y, both a number
  9737. * @private
  9738. */
  9739. Graph.prototype._getTranslation = function() {
  9740. return {
  9741. "x": this.translation.x,
  9742. "y": this.translation.y
  9743. };
  9744. };
  9745. /**
  9746. * Scale the graph
  9747. * @param {Number} scale Scaling factor 1.0 is unscaled
  9748. * @private
  9749. */
  9750. Graph.prototype._setScale = function(scale) {
  9751. this.scale = scale;
  9752. };
  9753. /**
  9754. * Get the current scale of the graph
  9755. * @return {Number} scale Scaling factor 1.0 is unscaled
  9756. * @private
  9757. */
  9758. Graph.prototype._getScale = function() {
  9759. return this.scale;
  9760. };
  9761. Graph.prototype._xToCanvas = function(x) {
  9762. return (x - this.translation.x) / this.scale;
  9763. };
  9764. Graph.prototype._canvasToX = function(x) {
  9765. return x * this.scale + this.translation.x;
  9766. };
  9767. Graph.prototype._yToCanvas = function(y) {
  9768. return (y - this.translation.y) / this.scale;
  9769. };
  9770. Graph.prototype._canvasToY = function(y) {
  9771. return y * this.scale + this.translation.y ;
  9772. };
  9773. /**
  9774. * Redraw all nodes
  9775. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9776. * @param {CanvasRenderingContext2D} ctx
  9777. * @private
  9778. */
  9779. Graph.prototype._drawNodes = function(ctx) {
  9780. // first draw the unselected nodes
  9781. var nodes = this.nodes;
  9782. var selected = [];
  9783. for (var id in nodes) {
  9784. if (nodes.hasOwnProperty(id)) {
  9785. if (nodes[id].isSelected()) {
  9786. selected.push(id);
  9787. }
  9788. else {
  9789. nodes[id].draw(ctx);
  9790. }
  9791. }
  9792. }
  9793. // draw the selected nodes on top
  9794. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  9795. nodes[selected[s]].draw(ctx);
  9796. }
  9797. };
  9798. /**
  9799. * Redraw all edges
  9800. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9801. * @param {CanvasRenderingContext2D} ctx
  9802. * @private
  9803. */
  9804. Graph.prototype._drawEdges = function(ctx) {
  9805. var edges = this.edges;
  9806. for (var id in edges) {
  9807. if (edges.hasOwnProperty(id)) {
  9808. var edge = edges[id];
  9809. if (edge.connected) {
  9810. edges[id].draw(ctx);
  9811. }
  9812. }
  9813. }
  9814. };
  9815. /**
  9816. * Find a stable position for all nodes
  9817. * @private
  9818. */
  9819. Graph.prototype._doStabilize = function() {
  9820. var start = new Date();
  9821. // find stable position
  9822. var count = 0;
  9823. var vmin = this.constants.minVelocity;
  9824. var stable = false;
  9825. while (!stable && count < this.constants.maxIterations) {
  9826. this._calculateForces();
  9827. this._discreteStepNodes();
  9828. stable = !this._isMoving(vmin);
  9829. count++;
  9830. }
  9831. var end = new Date();
  9832. // console.log("Stabilized in " + (end-start) + " ms, " + count + " iterations" ); // TODO: cleanup
  9833. };
  9834. /**
  9835. * Calculate the external forces acting on the nodes
  9836. * Forces are caused by: edges, repulsing forces between nodes, gravity
  9837. * @private
  9838. */
  9839. Graph.prototype._calculateForces = function() {
  9840. // create a local edge to the nodes and edges, that is faster
  9841. var id, dx, dy, angle, distance, fx, fy,
  9842. repulsingForce, springForce, length, edgeLength,
  9843. nodes = this.nodes,
  9844. edges = this.edges;
  9845. // gravity, add a small constant force to pull the nodes towards the center of
  9846. // the graph
  9847. // Also, the forces are reset to zero in this loop by using _setForce instead
  9848. // of _addForce
  9849. var gravity = 0.01,
  9850. gx = this.frame.canvas.clientWidth / 2,
  9851. gy = this.frame.canvas.clientHeight / 2;
  9852. for (id in nodes) {
  9853. if (nodes.hasOwnProperty(id)) {
  9854. var node = nodes[id];
  9855. dx = gx - node.x;
  9856. dy = gy - node.y;
  9857. angle = Math.atan2(dy, dx);
  9858. fx = Math.cos(angle) * gravity;
  9859. fy = Math.sin(angle) * gravity;
  9860. node._setForce(fx, fy);
  9861. }
  9862. }
  9863. // repulsing forces between nodes
  9864. var minimumDistance = this.constants.nodes.distance,
  9865. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  9866. for (var id1 in nodes) {
  9867. if (nodes.hasOwnProperty(id1)) {
  9868. var node1 = nodes[id1];
  9869. for (var id2 in nodes) {
  9870. if (nodes.hasOwnProperty(id2)) {
  9871. var node2 = nodes[id2];
  9872. // calculate normally distributed force
  9873. dx = node2.x - node1.x;
  9874. dy = node2.y - node1.y;
  9875. distance = Math.sqrt(dx * dx + dy * dy);
  9876. angle = Math.atan2(dy, dx);
  9877. // TODO: correct factor for repulsing force
  9878. //repulsingForce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  9879. //repulsingForce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  9880. repulsingForce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)); // TODO: customize the repulsing force
  9881. fx = Math.cos(angle) * repulsingForce;
  9882. fy = Math.sin(angle) * repulsingForce;
  9883. node1._addForce(-fx, -fy);
  9884. node2._addForce(fx, fy);
  9885. }
  9886. }
  9887. }
  9888. }
  9889. /* TODO: re-implement repulsion of edges
  9890. for (var n = 0; n < nodes.length; n++) {
  9891. for (var l = 0; l < edges.length; l++) {
  9892. var lx = edges[l].from.x+(edges[l].to.x - edges[l].from.x)/2,
  9893. ly = edges[l].from.y+(edges[l].to.y - edges[l].from.y)/2,
  9894. // calculate normally distributed force
  9895. dx = nodes[n].x - lx,
  9896. dy = nodes[n].y - ly,
  9897. distance = Math.sqrt(dx * dx + dy * dy),
  9898. angle = Math.atan2(dy, dx),
  9899. // TODO: correct factor for repulsing force
  9900. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  9901. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  9902. repulsingforce = 1 / (1 + Math.exp((distance / (minimumDistance / 2) - 1) * steepness)), // TODO: customize the repulsing force
  9903. fx = Math.cos(angle) * repulsingforce,
  9904. fy = Math.sin(angle) * repulsingforce;
  9905. nodes[n]._addForce(fx, fy);
  9906. edges[l].from._addForce(-fx/2,-fy/2);
  9907. edges[l].to._addForce(-fx/2,-fy/2);
  9908. }
  9909. }
  9910. */
  9911. // forces caused by the edges, modelled as springs
  9912. for (id in edges) {
  9913. if (edges.hasOwnProperty(id)) {
  9914. var edge = edges[id];
  9915. if (edge.connected) {
  9916. dx = (edge.to.x - edge.from.x);
  9917. dy = (edge.to.y - edge.from.y);
  9918. //edgeLength = (edge.from.width + edge.from.height + edge.to.width + edge.to.height)/2 || edge.length; // TODO: dmin
  9919. //edgeLength = (edge.from.width + edge.to.width)/2 || edge.length; // TODO: dmin
  9920. //edgeLength = 20 + ((edge.from.width + edge.to.width) || 0) / 2;
  9921. edgeLength = edge.length;
  9922. length = Math.sqrt(dx * dx + dy * dy);
  9923. angle = Math.atan2(dy, dx);
  9924. springForce = edge.stiffness * (edgeLength - length);
  9925. fx = Math.cos(angle) * springForce;
  9926. fy = Math.sin(angle) * springForce;
  9927. edge.from._addForce(-fx, -fy);
  9928. edge.to._addForce(fx, fy);
  9929. }
  9930. }
  9931. }
  9932. /* TODO: re-implement repulsion of edges
  9933. // repulsing forces between edges
  9934. var minimumDistance = this.constants.edges.distance,
  9935. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  9936. for (var l = 0; l < edges.length; l++) {
  9937. //Keep distance from other edge centers
  9938. for (var l2 = l + 1; l2 < this.edges.length; l2++) {
  9939. //var dmin = (nodes[n].width + nodes[n].height + nodes[n2].width + nodes[n2].height) / 1 || minimumDistance, // TODO: dmin
  9940. //var dmin = (nodes[n].width + nodes[n2].width)/2 || minimumDistance, // TODO: dmin
  9941. //dmin = 40 + ((nodes[n].width/2 + nodes[n2].width/2) || 0),
  9942. var lx = edges[l].from.x+(edges[l].to.x - edges[l].from.x)/2,
  9943. ly = edges[l].from.y+(edges[l].to.y - edges[l].from.y)/2,
  9944. l2x = edges[l2].from.x+(edges[l2].to.x - edges[l2].from.x)/2,
  9945. l2y = edges[l2].from.y+(edges[l2].to.y - edges[l2].from.y)/2,
  9946. // calculate normally distributed force
  9947. dx = l2x - lx,
  9948. dy = l2y - ly,
  9949. distance = Math.sqrt(dx * dx + dy * dy),
  9950. angle = Math.atan2(dy, dx),
  9951. // TODO: correct factor for repulsing force
  9952. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  9953. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  9954. repulsingforce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)), // TODO: customize the repulsing force
  9955. fx = Math.cos(angle) * repulsingforce,
  9956. fy = Math.sin(angle) * repulsingforce;
  9957. edges[l].from._addForce(-fx, -fy);
  9958. edges[l].to._addForce(-fx, -fy);
  9959. edges[l2].from._addForce(fx, fy);
  9960. edges[l2].to._addForce(fx, fy);
  9961. }
  9962. }
  9963. */
  9964. };
  9965. /**
  9966. * Check if any of the nodes is still moving
  9967. * @param {number} vmin the minimum velocity considered as "moving"
  9968. * @return {boolean} true if moving, false if non of the nodes is moving
  9969. * @private
  9970. */
  9971. Graph.prototype._isMoving = function(vmin) {
  9972. // TODO: ismoving does not work well: should check the kinetic energy, not its velocity
  9973. var nodes = this.nodes;
  9974. for (var id in nodes) {
  9975. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  9976. return true;
  9977. }
  9978. }
  9979. return false;
  9980. };
  9981. /**
  9982. * Perform one discrete step for all nodes
  9983. * @private
  9984. */
  9985. Graph.prototype._discreteStepNodes = function() {
  9986. var interval = this.refreshRate / 1000.0; // in seconds
  9987. var nodes = this.nodes;
  9988. for (var id in nodes) {
  9989. if (nodes.hasOwnProperty(id)) {
  9990. nodes[id].discreteStep(interval);
  9991. }
  9992. }
  9993. };
  9994. /**
  9995. * Start animating nodes and edges
  9996. */
  9997. Graph.prototype.start = function() {
  9998. if (this.moving) {
  9999. this._calculateForces();
  10000. this._discreteStepNodes();
  10001. var vmin = this.constants.minVelocity;
  10002. this.moving = this._isMoving(vmin);
  10003. }
  10004. if (this.moving) {
  10005. // start animation. only start timer if it is not already running
  10006. if (!this.timer) {
  10007. var graph = this;
  10008. this.timer = window.setTimeout(function () {
  10009. graph.timer = undefined;
  10010. graph.start();
  10011. graph._redraw();
  10012. }, this.refreshRate);
  10013. }
  10014. }
  10015. else {
  10016. this._redraw();
  10017. }
  10018. };
  10019. /**
  10020. * Stop animating nodes and edges.
  10021. */
  10022. Graph.prototype.stop = function () {
  10023. if (this.timer) {
  10024. window.clearInterval(this.timer);
  10025. this.timer = undefined;
  10026. }
  10027. };
  10028. /**
  10029. * vis.js module exports
  10030. */
  10031. var vis = {
  10032. util: util,
  10033. events: events,
  10034. Controller: Controller,
  10035. DataSet: DataSet,
  10036. DataView: DataView,
  10037. Range: Range,
  10038. Stack: Stack,
  10039. TimeStep: TimeStep,
  10040. EventBus: EventBus,
  10041. components: {
  10042. items: {
  10043. Item: Item,
  10044. ItemBox: ItemBox,
  10045. ItemPoint: ItemPoint,
  10046. ItemRange: ItemRange
  10047. },
  10048. Component: Component,
  10049. Panel: Panel,
  10050. RootPanel: RootPanel,
  10051. ItemSet: ItemSet,
  10052. TimeAxis: TimeAxis
  10053. },
  10054. graph: {
  10055. Node: Node,
  10056. Edge: Edge,
  10057. Popup: Popup,
  10058. Groups: Groups,
  10059. Images: Images
  10060. },
  10061. Timeline: Timeline,
  10062. Graph: Graph
  10063. };
  10064. /**
  10065. * CommonJS module exports
  10066. */
  10067. if (typeof exports !== 'undefined') {
  10068. exports = vis;
  10069. }
  10070. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  10071. module.exports = vis;
  10072. }
  10073. /**
  10074. * AMD module exports
  10075. */
  10076. if (typeof(define) === 'function') {
  10077. define(function () {
  10078. return vis;
  10079. });
  10080. }
  10081. /**
  10082. * Window exports
  10083. */
  10084. if (typeof window !== 'undefined') {
  10085. // attach the module to the window, load as a regular javascript file
  10086. window['vis'] = vis;
  10087. }
  10088. // inject css
  10089. util.loadCss("/* vis.js stylesheet */\n.vis.timeline {\n}\n\n\n.vis.timeline.rootpanel {\n position: relative;\n overflow: hidden;\n\n border: 1px solid #bfbfbf;\n -moz-box-sizing: border-box;\n box-sizing: border-box;\n}\n\n.vis.timeline .panel {\n position: absolute;\n overflow: hidden;\n}\n\n\n.vis.timeline .groupset {\n position: absolute;\n padding: 0;\n margin: 0;\n}\n\n.vis.timeline .labels {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n\n padding: 0;\n margin: 0;\n\n border-right: 1px solid #bfbfbf;\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n}\n\n.vis.timeline .labels .label {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n border-bottom: 1px solid #bfbfbf;\n color: #4d4d4d;\n}\n\n.vis.timeline .labels .label .inner {\n display: inline-block;\n padding: 5px;\n}\n\n\n.vis.timeline .itemset {\n position: absolute;\n padding: 0;\n margin: 0;\n overflow: hidden;\n}\n\n.vis.timeline .background {\n}\n\n.vis.timeline .foreground {\n}\n\n.vis.timeline .itemset-axis {\n position: absolute;\n}\n\n.vis.timeline .groupset .itemset-axis {\n border-top: 1px solid #bfbfbf;\n}\n\n/* TODO: with orientation=='bottom', this will more or less overlap with timeline axis\n.vis.timeline .groupset .itemset-axis:last-child {\n border-top: none;\n}\n*/\n\n\n.vis.timeline .item {\n position: absolute;\n color: #1A1A1A;\n border-color: #97B0F8;\n background-color: #D5DDF6;\n display: inline-block;\n}\n\n.vis.timeline .item.selected {\n border-color: #FFC200;\n background-color: #FFF785;\n z-index: 999;\n}\n\n.vis.timeline .item.cluster {\n /* TODO: use another color or pattern? */\n background: #97B0F8 url('img/cluster_bg.png');\n color: white;\n}\n.vis.timeline .item.cluster.point {\n border-color: #D5DDF6;\n}\n\n.vis.timeline .item.box {\n text-align: center;\n border-style: solid;\n border-width: 1px;\n border-radius: 5px;\n -moz-border-radius: 5px; /* For Firefox 3.6 and older */\n}\n\n.vis.timeline .item.point {\n background: none;\n}\n\n.vis.timeline .dot {\n border: 5px solid #97B0F8;\n position: absolute;\n border-radius: 5px;\n -moz-border-radius: 5px; /* For Firefox 3.6 and older */\n}\n\n.vis.timeline .item.range {\n border-style: solid;\n border-width: 1px;\n border-radius: 2px;\n -moz-border-radius: 2px; /* For Firefox 3.6 and older */\n}\n\n.vis.timeline .item.range .drag-left {\n cursor: w-resize;\n z-index: 1000;\n}\n\n.vis.timeline .item.range .drag-right {\n cursor: e-resize;\n z-index: 1000;\n}\n\n.vis.timeline .item.range .content {\n position: relative;\n display: inline-block;\n}\n\n.vis.timeline .item.line {\n position: absolute;\n width: 0;\n border-left-width: 1px;\n border-left-style: solid;\n}\n\n.vis.timeline .item .content {\n margin: 5px;\n white-space: nowrap;\n overflow: hidden;\n}\n\n.vis.timeline .axis {\n position: relative;\n}\n\n.vis.timeline .axis .text {\n position: absolute;\n color: #4d4d4d;\n padding: 3px;\n white-space: nowrap;\n}\n\n.vis.timeline .axis .text.measure {\n position: absolute;\n padding-left: 0;\n padding-right: 0;\n margin-left: 0;\n margin-right: 0;\n visibility: hidden;\n}\n\n.vis.timeline .axis .grid.vertical {\n position: absolute;\n width: 0;\n border-right: 1px solid;\n}\n\n.vis.timeline .axis .grid.horizontal {\n position: absolute;\n left: 0;\n width: 100%;\n height: 0;\n border-bottom: 1px solid;\n}\n\n.vis.timeline .axis .grid.minor {\n border-color: #e5e5e5;\n}\n\n.vis.timeline .axis .grid.major {\n border-color: #bfbfbf;\n}\n\n");
  10090. })()
  10091. },{"moment":2}],2:[function(require,module,exports){
  10092. (function(){// moment.js
  10093. // version : 2.0.0
  10094. // author : Tim Wood
  10095. // license : MIT
  10096. // momentjs.com
  10097. (function (undefined) {
  10098. /************************************
  10099. Constants
  10100. ************************************/
  10101. var moment,
  10102. VERSION = "2.0.0",
  10103. round = Math.round, i,
  10104. // internal storage for language config files
  10105. languages = {},
  10106. // check for nodeJS
  10107. hasModule = (typeof module !== 'undefined' && module.exports),
  10108. // ASP.NET json date format regex
  10109. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  10110. // format tokens
  10111. 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,
  10112. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  10113. // parsing tokens
  10114. parseMultipleFormatChunker = /([0-9a-zA-Z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)/gi,
  10115. // parsing token regexes
  10116. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  10117. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  10118. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  10119. parseTokenFourDigits = /\d{1,4}/, // 0 - 9999
  10120. parseTokenSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  10121. 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.
  10122. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/i, // +00:00 -00:00 +0000 -0000 or Z
  10123. parseTokenT = /T/i, // T (ISO seperator)
  10124. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  10125. // preliminary iso regex
  10126. // 0000-00-00 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000
  10127. isoRegex = /^\s*\d{4}-\d\d-\d\d((T| )(\d\d(:\d\d(:\d\d(\.\d\d?\d?)?)?)?)?([\+\-]\d\d:?\d\d)?)?/,
  10128. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  10129. // iso time formats and regexes
  10130. isoTimes = [
  10131. ['HH:mm:ss.S', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/],
  10132. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  10133. ['HH:mm', /(T| )\d\d:\d\d/],
  10134. ['HH', /(T| )\d\d/]
  10135. ],
  10136. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  10137. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  10138. // getter and setter names
  10139. proxyGettersAndSetters = 'Month|Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  10140. unitMillisecondFactors = {
  10141. 'Milliseconds' : 1,
  10142. 'Seconds' : 1e3,
  10143. 'Minutes' : 6e4,
  10144. 'Hours' : 36e5,
  10145. 'Days' : 864e5,
  10146. 'Months' : 2592e6,
  10147. 'Years' : 31536e6
  10148. },
  10149. // format function strings
  10150. formatFunctions = {},
  10151. // tokens to ordinalize and pad
  10152. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  10153. paddedTokens = 'M D H h m s w W'.split(' '),
  10154. formatTokenFunctions = {
  10155. M : function () {
  10156. return this.month() + 1;
  10157. },
  10158. MMM : function (format) {
  10159. return this.lang().monthsShort(this, format);
  10160. },
  10161. MMMM : function (format) {
  10162. return this.lang().months(this, format);
  10163. },
  10164. D : function () {
  10165. return this.date();
  10166. },
  10167. DDD : function () {
  10168. return this.dayOfYear();
  10169. },
  10170. d : function () {
  10171. return this.day();
  10172. },
  10173. dd : function (format) {
  10174. return this.lang().weekdaysMin(this, format);
  10175. },
  10176. ddd : function (format) {
  10177. return this.lang().weekdaysShort(this, format);
  10178. },
  10179. dddd : function (format) {
  10180. return this.lang().weekdays(this, format);
  10181. },
  10182. w : function () {
  10183. return this.week();
  10184. },
  10185. W : function () {
  10186. return this.isoWeek();
  10187. },
  10188. YY : function () {
  10189. return leftZeroFill(this.year() % 100, 2);
  10190. },
  10191. YYYY : function () {
  10192. return leftZeroFill(this.year(), 4);
  10193. },
  10194. YYYYY : function () {
  10195. return leftZeroFill(this.year(), 5);
  10196. },
  10197. a : function () {
  10198. return this.lang().meridiem(this.hours(), this.minutes(), true);
  10199. },
  10200. A : function () {
  10201. return this.lang().meridiem(this.hours(), this.minutes(), false);
  10202. },
  10203. H : function () {
  10204. return this.hours();
  10205. },
  10206. h : function () {
  10207. return this.hours() % 12 || 12;
  10208. },
  10209. m : function () {
  10210. return this.minutes();
  10211. },
  10212. s : function () {
  10213. return this.seconds();
  10214. },
  10215. S : function () {
  10216. return ~~(this.milliseconds() / 100);
  10217. },
  10218. SS : function () {
  10219. return leftZeroFill(~~(this.milliseconds() / 10), 2);
  10220. },
  10221. SSS : function () {
  10222. return leftZeroFill(this.milliseconds(), 3);
  10223. },
  10224. Z : function () {
  10225. var a = -this.zone(),
  10226. b = "+";
  10227. if (a < 0) {
  10228. a = -a;
  10229. b = "-";
  10230. }
  10231. return b + leftZeroFill(~~(a / 60), 2) + ":" + leftZeroFill(~~a % 60, 2);
  10232. },
  10233. ZZ : function () {
  10234. var a = -this.zone(),
  10235. b = "+";
  10236. if (a < 0) {
  10237. a = -a;
  10238. b = "-";
  10239. }
  10240. return b + leftZeroFill(~~(10 * a / 6), 4);
  10241. },
  10242. X : function () {
  10243. return this.unix();
  10244. }
  10245. };
  10246. function padToken(func, count) {
  10247. return function (a) {
  10248. return leftZeroFill(func.call(this, a), count);
  10249. };
  10250. }
  10251. function ordinalizeToken(func) {
  10252. return function (a) {
  10253. return this.lang().ordinal(func.call(this, a));
  10254. };
  10255. }
  10256. while (ordinalizeTokens.length) {
  10257. i = ordinalizeTokens.pop();
  10258. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i]);
  10259. }
  10260. while (paddedTokens.length) {
  10261. i = paddedTokens.pop();
  10262. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  10263. }
  10264. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  10265. /************************************
  10266. Constructors
  10267. ************************************/
  10268. function Language() {
  10269. }
  10270. // Moment prototype object
  10271. function Moment(config) {
  10272. extend(this, config);
  10273. }
  10274. // Duration Constructor
  10275. function Duration(duration) {
  10276. var data = this._data = {},
  10277. years = duration.years || duration.year || duration.y || 0,
  10278. months = duration.months || duration.month || duration.M || 0,
  10279. weeks = duration.weeks || duration.week || duration.w || 0,
  10280. days = duration.days || duration.day || duration.d || 0,
  10281. hours = duration.hours || duration.hour || duration.h || 0,
  10282. minutes = duration.minutes || duration.minute || duration.m || 0,
  10283. seconds = duration.seconds || duration.second || duration.s || 0,
  10284. milliseconds = duration.milliseconds || duration.millisecond || duration.ms || 0;
  10285. // representation for dateAddRemove
  10286. this._milliseconds = milliseconds +
  10287. seconds * 1e3 + // 1000
  10288. minutes * 6e4 + // 1000 * 60
  10289. hours * 36e5; // 1000 * 60 * 60
  10290. // Because of dateAddRemove treats 24 hours as different from a
  10291. // day when working around DST, we need to store them separately
  10292. this._days = days +
  10293. weeks * 7;
  10294. // It is impossible translate months into days without knowing
  10295. // which months you are are talking about, so we have to store
  10296. // it separately.
  10297. this._months = months +
  10298. years * 12;
  10299. // The following code bubbles up values, see the tests for
  10300. // examples of what that means.
  10301. data.milliseconds = milliseconds % 1000;
  10302. seconds += absRound(milliseconds / 1000);
  10303. data.seconds = seconds % 60;
  10304. minutes += absRound(seconds / 60);
  10305. data.minutes = minutes % 60;
  10306. hours += absRound(minutes / 60);
  10307. data.hours = hours % 24;
  10308. days += absRound(hours / 24);
  10309. days += weeks * 7;
  10310. data.days = days % 30;
  10311. months += absRound(days / 30);
  10312. data.months = months % 12;
  10313. years += absRound(months / 12);
  10314. data.years = years;
  10315. }
  10316. /************************************
  10317. Helpers
  10318. ************************************/
  10319. function extend(a, b) {
  10320. for (var i in b) {
  10321. if (b.hasOwnProperty(i)) {
  10322. a[i] = b[i];
  10323. }
  10324. }
  10325. return a;
  10326. }
  10327. function absRound(number) {
  10328. if (number < 0) {
  10329. return Math.ceil(number);
  10330. } else {
  10331. return Math.floor(number);
  10332. }
  10333. }
  10334. // left zero fill a number
  10335. // see http://jsperf.com/left-zero-filling for performance comparison
  10336. function leftZeroFill(number, targetLength) {
  10337. var output = number + '';
  10338. while (output.length < targetLength) {
  10339. output = '0' + output;
  10340. }
  10341. return output;
  10342. }
  10343. // helper function for _.addTime and _.subtractTime
  10344. function addOrSubtractDurationFromMoment(mom, duration, isAdding) {
  10345. var ms = duration._milliseconds,
  10346. d = duration._days,
  10347. M = duration._months,
  10348. currentDate;
  10349. if (ms) {
  10350. mom._d.setTime(+mom + ms * isAdding);
  10351. }
  10352. if (d) {
  10353. mom.date(mom.date() + d * isAdding);
  10354. }
  10355. if (M) {
  10356. currentDate = mom.date();
  10357. mom.date(1)
  10358. .month(mom.month() + M * isAdding)
  10359. .date(Math.min(currentDate, mom.daysInMonth()));
  10360. }
  10361. }
  10362. // check if is an array
  10363. function isArray(input) {
  10364. return Object.prototype.toString.call(input) === '[object Array]';
  10365. }
  10366. // compare two arrays, return the number of differences
  10367. function compareArrays(array1, array2) {
  10368. var len = Math.min(array1.length, array2.length),
  10369. lengthDiff = Math.abs(array1.length - array2.length),
  10370. diffs = 0,
  10371. i;
  10372. for (i = 0; i < len; i++) {
  10373. if (~~array1[i] !== ~~array2[i]) {
  10374. diffs++;
  10375. }
  10376. }
  10377. return diffs + lengthDiff;
  10378. }
  10379. /************************************
  10380. Languages
  10381. ************************************/
  10382. Language.prototype = {
  10383. set : function (config) {
  10384. var prop, i;
  10385. for (i in config) {
  10386. prop = config[i];
  10387. if (typeof prop === 'function') {
  10388. this[i] = prop;
  10389. } else {
  10390. this['_' + i] = prop;
  10391. }
  10392. }
  10393. },
  10394. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  10395. months : function (m) {
  10396. return this._months[m.month()];
  10397. },
  10398. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  10399. monthsShort : function (m) {
  10400. return this._monthsShort[m.month()];
  10401. },
  10402. monthsParse : function (monthName) {
  10403. var i, mom, regex, output;
  10404. if (!this._monthsParse) {
  10405. this._monthsParse = [];
  10406. }
  10407. for (i = 0; i < 12; i++) {
  10408. // make the regex if we don't have it already
  10409. if (!this._monthsParse[i]) {
  10410. mom = moment([2000, i]);
  10411. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  10412. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  10413. }
  10414. // test the regex
  10415. if (this._monthsParse[i].test(monthName)) {
  10416. return i;
  10417. }
  10418. }
  10419. },
  10420. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  10421. weekdays : function (m) {
  10422. return this._weekdays[m.day()];
  10423. },
  10424. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  10425. weekdaysShort : function (m) {
  10426. return this._weekdaysShort[m.day()];
  10427. },
  10428. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  10429. weekdaysMin : function (m) {
  10430. return this._weekdaysMin[m.day()];
  10431. },
  10432. _longDateFormat : {
  10433. LT : "h:mm A",
  10434. L : "MM/DD/YYYY",
  10435. LL : "MMMM D YYYY",
  10436. LLL : "MMMM D YYYY LT",
  10437. LLLL : "dddd, MMMM D YYYY LT"
  10438. },
  10439. longDateFormat : function (key) {
  10440. var output = this._longDateFormat[key];
  10441. if (!output && this._longDateFormat[key.toUpperCase()]) {
  10442. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  10443. return val.slice(1);
  10444. });
  10445. this._longDateFormat[key] = output;
  10446. }
  10447. return output;
  10448. },
  10449. meridiem : function (hours, minutes, isLower) {
  10450. if (hours > 11) {
  10451. return isLower ? 'pm' : 'PM';
  10452. } else {
  10453. return isLower ? 'am' : 'AM';
  10454. }
  10455. },
  10456. _calendar : {
  10457. sameDay : '[Today at] LT',
  10458. nextDay : '[Tomorrow at] LT',
  10459. nextWeek : 'dddd [at] LT',
  10460. lastDay : '[Yesterday at] LT',
  10461. lastWeek : '[last] dddd [at] LT',
  10462. sameElse : 'L'
  10463. },
  10464. calendar : function (key, mom) {
  10465. var output = this._calendar[key];
  10466. return typeof output === 'function' ? output.apply(mom) : output;
  10467. },
  10468. _relativeTime : {
  10469. future : "in %s",
  10470. past : "%s ago",
  10471. s : "a few seconds",
  10472. m : "a minute",
  10473. mm : "%d minutes",
  10474. h : "an hour",
  10475. hh : "%d hours",
  10476. d : "a day",
  10477. dd : "%d days",
  10478. M : "a month",
  10479. MM : "%d months",
  10480. y : "a year",
  10481. yy : "%d years"
  10482. },
  10483. relativeTime : function (number, withoutSuffix, string, isFuture) {
  10484. var output = this._relativeTime[string];
  10485. return (typeof output === 'function') ?
  10486. output(number, withoutSuffix, string, isFuture) :
  10487. output.replace(/%d/i, number);
  10488. },
  10489. pastFuture : function (diff, output) {
  10490. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  10491. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  10492. },
  10493. ordinal : function (number) {
  10494. return this._ordinal.replace("%d", number);
  10495. },
  10496. _ordinal : "%d",
  10497. preparse : function (string) {
  10498. return string;
  10499. },
  10500. postformat : function (string) {
  10501. return string;
  10502. },
  10503. week : function (mom) {
  10504. return weekOfYear(mom, this._week.dow, this._week.doy);
  10505. },
  10506. _week : {
  10507. dow : 0, // Sunday is the first day of the week.
  10508. doy : 6 // The week that contains Jan 1st is the first week of the year.
  10509. }
  10510. };
  10511. // Loads a language definition into the `languages` cache. The function
  10512. // takes a key and optionally values. If not in the browser and no values
  10513. // are provided, it will load the language file module. As a convenience,
  10514. // this function also returns the language values.
  10515. function loadLang(key, values) {
  10516. values.abbr = key;
  10517. if (!languages[key]) {
  10518. languages[key] = new Language();
  10519. }
  10520. languages[key].set(values);
  10521. return languages[key];
  10522. }
  10523. // Determines which language definition to use and returns it.
  10524. //
  10525. // With no parameters, it will return the global language. If you
  10526. // pass in a language key, such as 'en', it will return the
  10527. // definition for 'en', so long as 'en' has already been loaded using
  10528. // moment.lang.
  10529. function getLangDefinition(key) {
  10530. if (!key) {
  10531. return moment.fn._lang;
  10532. }
  10533. if (!languages[key] && hasModule) {
  10534. require('./lang/' + key);
  10535. }
  10536. return languages[key];
  10537. }
  10538. /************************************
  10539. Formatting
  10540. ************************************/
  10541. function removeFormattingTokens(input) {
  10542. if (input.match(/\[.*\]/)) {
  10543. return input.replace(/^\[|\]$/g, "");
  10544. }
  10545. return input.replace(/\\/g, "");
  10546. }
  10547. function makeFormatFunction(format) {
  10548. var array = format.match(formattingTokens), i, length;
  10549. for (i = 0, length = array.length; i < length; i++) {
  10550. if (formatTokenFunctions[array[i]]) {
  10551. array[i] = formatTokenFunctions[array[i]];
  10552. } else {
  10553. array[i] = removeFormattingTokens(array[i]);
  10554. }
  10555. }
  10556. return function (mom) {
  10557. var output = "";
  10558. for (i = 0; i < length; i++) {
  10559. output += typeof array[i].call === 'function' ? array[i].call(mom, format) : array[i];
  10560. }
  10561. return output;
  10562. };
  10563. }
  10564. // format date using native date object
  10565. function formatMoment(m, format) {
  10566. var i = 5;
  10567. function replaceLongDateFormatTokens(input) {
  10568. return m.lang().longDateFormat(input) || input;
  10569. }
  10570. while (i-- && localFormattingTokens.test(format)) {
  10571. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  10572. }
  10573. if (!formatFunctions[format]) {
  10574. formatFunctions[format] = makeFormatFunction(format);
  10575. }
  10576. return formatFunctions[format](m);
  10577. }
  10578. /************************************
  10579. Parsing
  10580. ************************************/
  10581. // get the regex to find the next token
  10582. function getParseRegexForToken(token) {
  10583. switch (token) {
  10584. case 'DDDD':
  10585. return parseTokenThreeDigits;
  10586. case 'YYYY':
  10587. return parseTokenFourDigits;
  10588. case 'YYYYY':
  10589. return parseTokenSixDigits;
  10590. case 'S':
  10591. case 'SS':
  10592. case 'SSS':
  10593. case 'DDD':
  10594. return parseTokenOneToThreeDigits;
  10595. case 'MMM':
  10596. case 'MMMM':
  10597. case 'dd':
  10598. case 'ddd':
  10599. case 'dddd':
  10600. case 'a':
  10601. case 'A':
  10602. return parseTokenWord;
  10603. case 'X':
  10604. return parseTokenTimestampMs;
  10605. case 'Z':
  10606. case 'ZZ':
  10607. return parseTokenTimezone;
  10608. case 'T':
  10609. return parseTokenT;
  10610. case 'MM':
  10611. case 'DD':
  10612. case 'YY':
  10613. case 'HH':
  10614. case 'hh':
  10615. case 'mm':
  10616. case 'ss':
  10617. case 'M':
  10618. case 'D':
  10619. case 'd':
  10620. case 'H':
  10621. case 'h':
  10622. case 'm':
  10623. case 's':
  10624. return parseTokenOneOrTwoDigits;
  10625. default :
  10626. return new RegExp(token.replace('\\', ''));
  10627. }
  10628. }
  10629. // function to convert string input to date
  10630. function addTimeToArrayFromToken(token, input, config) {
  10631. var a, b,
  10632. datePartArray = config._a;
  10633. switch (token) {
  10634. // MONTH
  10635. case 'M' : // fall through to MM
  10636. case 'MM' :
  10637. datePartArray[1] = (input == null) ? 0 : ~~input - 1;
  10638. break;
  10639. case 'MMM' : // fall through to MMMM
  10640. case 'MMMM' :
  10641. a = getLangDefinition(config._l).monthsParse(input);
  10642. // if we didn't find a month name, mark the date as invalid.
  10643. if (a != null) {
  10644. datePartArray[1] = a;
  10645. } else {
  10646. config._isValid = false;
  10647. }
  10648. break;
  10649. // DAY OF MONTH
  10650. case 'D' : // fall through to DDDD
  10651. case 'DD' : // fall through to DDDD
  10652. case 'DDD' : // fall through to DDDD
  10653. case 'DDDD' :
  10654. if (input != null) {
  10655. datePartArray[2] = ~~input;
  10656. }
  10657. break;
  10658. // YEAR
  10659. case 'YY' :
  10660. datePartArray[0] = ~~input + (~~input > 68 ? 1900 : 2000);
  10661. break;
  10662. case 'YYYY' :
  10663. case 'YYYYY' :
  10664. datePartArray[0] = ~~input;
  10665. break;
  10666. // AM / PM
  10667. case 'a' : // fall through to A
  10668. case 'A' :
  10669. config._isPm = ((input + '').toLowerCase() === 'pm');
  10670. break;
  10671. // 24 HOUR
  10672. case 'H' : // fall through to hh
  10673. case 'HH' : // fall through to hh
  10674. case 'h' : // fall through to hh
  10675. case 'hh' :
  10676. datePartArray[3] = ~~input;
  10677. break;
  10678. // MINUTE
  10679. case 'm' : // fall through to mm
  10680. case 'mm' :
  10681. datePartArray[4] = ~~input;
  10682. break;
  10683. // SECOND
  10684. case 's' : // fall through to ss
  10685. case 'ss' :
  10686. datePartArray[5] = ~~input;
  10687. break;
  10688. // MILLISECOND
  10689. case 'S' :
  10690. case 'SS' :
  10691. case 'SSS' :
  10692. datePartArray[6] = ~~ (('0.' + input) * 1000);
  10693. break;
  10694. // UNIX TIMESTAMP WITH MS
  10695. case 'X':
  10696. config._d = new Date(parseFloat(input) * 1000);
  10697. break;
  10698. // TIMEZONE
  10699. case 'Z' : // fall through to ZZ
  10700. case 'ZZ' :
  10701. config._useUTC = true;
  10702. a = (input + '').match(parseTimezoneChunker);
  10703. if (a && a[1]) {
  10704. config._tzh = ~~a[1];
  10705. }
  10706. if (a && a[2]) {
  10707. config._tzm = ~~a[2];
  10708. }
  10709. // reverse offsets
  10710. if (a && a[0] === '+') {
  10711. config._tzh = -config._tzh;
  10712. config._tzm = -config._tzm;
  10713. }
  10714. break;
  10715. }
  10716. // if the input is null, the date is not valid
  10717. if (input == null) {
  10718. config._isValid = false;
  10719. }
  10720. }
  10721. // convert an array to a date.
  10722. // the array should mirror the parameters below
  10723. // note: all values past the year are optional and will default to the lowest possible value.
  10724. // [year, month, day , hour, minute, second, millisecond]
  10725. function dateFromArray(config) {
  10726. var i, date, input = [];
  10727. if (config._d) {
  10728. return;
  10729. }
  10730. for (i = 0; i < 7; i++) {
  10731. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  10732. }
  10733. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  10734. input[3] += config._tzh || 0;
  10735. input[4] += config._tzm || 0;
  10736. date = new Date(0);
  10737. if (config._useUTC) {
  10738. date.setUTCFullYear(input[0], input[1], input[2]);
  10739. date.setUTCHours(input[3], input[4], input[5], input[6]);
  10740. } else {
  10741. date.setFullYear(input[0], input[1], input[2]);
  10742. date.setHours(input[3], input[4], input[5], input[6]);
  10743. }
  10744. config._d = date;
  10745. }
  10746. // date from string and format string
  10747. function makeDateFromStringAndFormat(config) {
  10748. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  10749. var tokens = config._f.match(formattingTokens),
  10750. string = config._i,
  10751. i, parsedInput;
  10752. config._a = [];
  10753. for (i = 0; i < tokens.length; i++) {
  10754. parsedInput = (getParseRegexForToken(tokens[i]).exec(string) || [])[0];
  10755. if (parsedInput) {
  10756. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  10757. }
  10758. // don't parse if its not a known token
  10759. if (formatTokenFunctions[tokens[i]]) {
  10760. addTimeToArrayFromToken(tokens[i], parsedInput, config);
  10761. }
  10762. }
  10763. // handle am pm
  10764. if (config._isPm && config._a[3] < 12) {
  10765. config._a[3] += 12;
  10766. }
  10767. // if is 12 am, change hours to 0
  10768. if (config._isPm === false && config._a[3] === 12) {
  10769. config._a[3] = 0;
  10770. }
  10771. // return
  10772. dateFromArray(config);
  10773. }
  10774. // date from string and array of format strings
  10775. function makeDateFromStringAndArray(config) {
  10776. var tempConfig,
  10777. tempMoment,
  10778. bestMoment,
  10779. scoreToBeat = 99,
  10780. i,
  10781. currentDate,
  10782. currentScore;
  10783. while (config._f.length) {
  10784. tempConfig = extend({}, config);
  10785. tempConfig._f = config._f.pop();
  10786. makeDateFromStringAndFormat(tempConfig);
  10787. tempMoment = new Moment(tempConfig);
  10788. if (tempMoment.isValid()) {
  10789. bestMoment = tempMoment;
  10790. break;
  10791. }
  10792. currentScore = compareArrays(tempConfig._a, tempMoment.toArray());
  10793. if (currentScore < scoreToBeat) {
  10794. scoreToBeat = currentScore;
  10795. bestMoment = tempMoment;
  10796. }
  10797. }
  10798. extend(config, bestMoment);
  10799. }
  10800. // date from iso format
  10801. function makeDateFromString(config) {
  10802. var i,
  10803. string = config._i;
  10804. if (isoRegex.exec(string)) {
  10805. config._f = 'YYYY-MM-DDT';
  10806. for (i = 0; i < 4; i++) {
  10807. if (isoTimes[i][1].exec(string)) {
  10808. config._f += isoTimes[i][0];
  10809. break;
  10810. }
  10811. }
  10812. if (parseTokenTimezone.exec(string)) {
  10813. config._f += " Z";
  10814. }
  10815. makeDateFromStringAndFormat(config);
  10816. } else {
  10817. config._d = new Date(string);
  10818. }
  10819. }
  10820. function makeDateFromInput(config) {
  10821. var input = config._i,
  10822. matched = aspNetJsonRegex.exec(input);
  10823. if (input === undefined) {
  10824. config._d = new Date();
  10825. } else if (matched) {
  10826. config._d = new Date(+matched[1]);
  10827. } else if (typeof input === 'string') {
  10828. makeDateFromString(config);
  10829. } else if (isArray(input)) {
  10830. config._a = input.slice(0);
  10831. dateFromArray(config);
  10832. } else {
  10833. config._d = input instanceof Date ? new Date(+input) : new Date(input);
  10834. }
  10835. }
  10836. /************************************
  10837. Relative Time
  10838. ************************************/
  10839. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  10840. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  10841. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  10842. }
  10843. function relativeTime(milliseconds, withoutSuffix, lang) {
  10844. var seconds = round(Math.abs(milliseconds) / 1000),
  10845. minutes = round(seconds / 60),
  10846. hours = round(minutes / 60),
  10847. days = round(hours / 24),
  10848. years = round(days / 365),
  10849. args = seconds < 45 && ['s', seconds] ||
  10850. minutes === 1 && ['m'] ||
  10851. minutes < 45 && ['mm', minutes] ||
  10852. hours === 1 && ['h'] ||
  10853. hours < 22 && ['hh', hours] ||
  10854. days === 1 && ['d'] ||
  10855. days <= 25 && ['dd', days] ||
  10856. days <= 45 && ['M'] ||
  10857. days < 345 && ['MM', round(days / 30)] ||
  10858. years === 1 && ['y'] || ['yy', years];
  10859. args[2] = withoutSuffix;
  10860. args[3] = milliseconds > 0;
  10861. args[4] = lang;
  10862. return substituteTimeAgo.apply({}, args);
  10863. }
  10864. /************************************
  10865. Week of Year
  10866. ************************************/
  10867. // firstDayOfWeek 0 = sun, 6 = sat
  10868. // the day of the week that starts the week
  10869. // (usually sunday or monday)
  10870. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  10871. // the first week is the week that contains the first
  10872. // of this day of the week
  10873. // (eg. ISO weeks use thursday (4))
  10874. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  10875. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  10876. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day();
  10877. if (daysToDayOfWeek > end) {
  10878. daysToDayOfWeek -= 7;
  10879. }
  10880. if (daysToDayOfWeek < end - 7) {
  10881. daysToDayOfWeek += 7;
  10882. }
  10883. return Math.ceil(moment(mom).add('d', daysToDayOfWeek).dayOfYear() / 7);
  10884. }
  10885. /************************************
  10886. Top Level Functions
  10887. ************************************/
  10888. function makeMoment(config) {
  10889. var input = config._i,
  10890. format = config._f;
  10891. if (input === null || input === '') {
  10892. return null;
  10893. }
  10894. if (typeof input === 'string') {
  10895. config._i = input = getLangDefinition().preparse(input);
  10896. }
  10897. if (moment.isMoment(input)) {
  10898. config = extend({}, input);
  10899. config._d = new Date(+input._d);
  10900. } else if (format) {
  10901. if (isArray(format)) {
  10902. makeDateFromStringAndArray(config);
  10903. } else {
  10904. makeDateFromStringAndFormat(config);
  10905. }
  10906. } else {
  10907. makeDateFromInput(config);
  10908. }
  10909. return new Moment(config);
  10910. }
  10911. moment = function (input, format, lang) {
  10912. return makeMoment({
  10913. _i : input,
  10914. _f : format,
  10915. _l : lang,
  10916. _isUTC : false
  10917. });
  10918. };
  10919. // creating with utc
  10920. moment.utc = function (input, format, lang) {
  10921. return makeMoment({
  10922. _useUTC : true,
  10923. _isUTC : true,
  10924. _l : lang,
  10925. _i : input,
  10926. _f : format
  10927. });
  10928. };
  10929. // creating with unix timestamp (in seconds)
  10930. moment.unix = function (input) {
  10931. return moment(input * 1000);
  10932. };
  10933. // duration
  10934. moment.duration = function (input, key) {
  10935. var isDuration = moment.isDuration(input),
  10936. isNumber = (typeof input === 'number'),
  10937. duration = (isDuration ? input._data : (isNumber ? {} : input)),
  10938. ret;
  10939. if (isNumber) {
  10940. if (key) {
  10941. duration[key] = input;
  10942. } else {
  10943. duration.milliseconds = input;
  10944. }
  10945. }
  10946. ret = new Duration(duration);
  10947. if (isDuration && input.hasOwnProperty('_lang')) {
  10948. ret._lang = input._lang;
  10949. }
  10950. return ret;
  10951. };
  10952. // version number
  10953. moment.version = VERSION;
  10954. // default format
  10955. moment.defaultFormat = isoFormat;
  10956. // This function will load languages and then set the global language. If
  10957. // no arguments are passed in, it will simply return the current global
  10958. // language key.
  10959. moment.lang = function (key, values) {
  10960. var i;
  10961. if (!key) {
  10962. return moment.fn._lang._abbr;
  10963. }
  10964. if (values) {
  10965. loadLang(key, values);
  10966. } else if (!languages[key]) {
  10967. getLangDefinition(key);
  10968. }
  10969. moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  10970. };
  10971. // returns language data
  10972. moment.langData = function (key) {
  10973. if (key && key._lang && key._lang._abbr) {
  10974. key = key._lang._abbr;
  10975. }
  10976. return getLangDefinition(key);
  10977. };
  10978. // compare moment object
  10979. moment.isMoment = function (obj) {
  10980. return obj instanceof Moment;
  10981. };
  10982. // for typechecking Duration objects
  10983. moment.isDuration = function (obj) {
  10984. return obj instanceof Duration;
  10985. };
  10986. /************************************
  10987. Moment Prototype
  10988. ************************************/
  10989. moment.fn = Moment.prototype = {
  10990. clone : function () {
  10991. return moment(this);
  10992. },
  10993. valueOf : function () {
  10994. return +this._d;
  10995. },
  10996. unix : function () {
  10997. return Math.floor(+this._d / 1000);
  10998. },
  10999. toString : function () {
  11000. return this.format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  11001. },
  11002. toDate : function () {
  11003. return this._d;
  11004. },
  11005. toJSON : function () {
  11006. return moment.utc(this).format('YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  11007. },
  11008. toArray : function () {
  11009. var m = this;
  11010. return [
  11011. m.year(),
  11012. m.month(),
  11013. m.date(),
  11014. m.hours(),
  11015. m.minutes(),
  11016. m.seconds(),
  11017. m.milliseconds()
  11018. ];
  11019. },
  11020. isValid : function () {
  11021. if (this._isValid == null) {
  11022. if (this._a) {
  11023. this._isValid = !compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray());
  11024. } else {
  11025. this._isValid = !isNaN(this._d.getTime());
  11026. }
  11027. }
  11028. return !!this._isValid;
  11029. },
  11030. utc : function () {
  11031. this._isUTC = true;
  11032. return this;
  11033. },
  11034. local : function () {
  11035. this._isUTC = false;
  11036. return this;
  11037. },
  11038. format : function (inputString) {
  11039. var output = formatMoment(this, inputString || moment.defaultFormat);
  11040. return this.lang().postformat(output);
  11041. },
  11042. add : function (input, val) {
  11043. var dur;
  11044. // switch args to support add('s', 1) and add(1, 's')
  11045. if (typeof input === 'string') {
  11046. dur = moment.duration(+val, input);
  11047. } else {
  11048. dur = moment.duration(input, val);
  11049. }
  11050. addOrSubtractDurationFromMoment(this, dur, 1);
  11051. return this;
  11052. },
  11053. subtract : function (input, val) {
  11054. var dur;
  11055. // switch args to support subtract('s', 1) and subtract(1, 's')
  11056. if (typeof input === 'string') {
  11057. dur = moment.duration(+val, input);
  11058. } else {
  11059. dur = moment.duration(input, val);
  11060. }
  11061. addOrSubtractDurationFromMoment(this, dur, -1);
  11062. return this;
  11063. },
  11064. diff : function (input, units, asFloat) {
  11065. var that = this._isUTC ? moment(input).utc() : moment(input).local(),
  11066. zoneDiff = (this.zone() - that.zone()) * 6e4,
  11067. diff, output;
  11068. if (units) {
  11069. // standardize on singular form
  11070. units = units.replace(/s$/, '');
  11071. }
  11072. if (units === 'year' || units === 'month') {
  11073. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  11074. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  11075. output += ((this - moment(this).startOf('month')) - (that - moment(that).startOf('month'))) / diff;
  11076. if (units === 'year') {
  11077. output = output / 12;
  11078. }
  11079. } else {
  11080. diff = (this - that) - zoneDiff;
  11081. output = units === 'second' ? diff / 1e3 : // 1000
  11082. units === 'minute' ? diff / 6e4 : // 1000 * 60
  11083. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  11084. units === 'day' ? diff / 864e5 : // 1000 * 60 * 60 * 24
  11085. units === 'week' ? diff / 6048e5 : // 1000 * 60 * 60 * 24 * 7
  11086. diff;
  11087. }
  11088. return asFloat ? output : absRound(output);
  11089. },
  11090. from : function (time, withoutSuffix) {
  11091. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  11092. },
  11093. fromNow : function (withoutSuffix) {
  11094. return this.from(moment(), withoutSuffix);
  11095. },
  11096. calendar : function () {
  11097. var diff = this.diff(moment().startOf('day'), 'days', true),
  11098. format = diff < -6 ? 'sameElse' :
  11099. diff < -1 ? 'lastWeek' :
  11100. diff < 0 ? 'lastDay' :
  11101. diff < 1 ? 'sameDay' :
  11102. diff < 2 ? 'nextDay' :
  11103. diff < 7 ? 'nextWeek' : 'sameElse';
  11104. return this.format(this.lang().calendar(format, this));
  11105. },
  11106. isLeapYear : function () {
  11107. var year = this.year();
  11108. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  11109. },
  11110. isDST : function () {
  11111. return (this.zone() < moment([this.year()]).zone() ||
  11112. this.zone() < moment([this.year(), 5]).zone());
  11113. },
  11114. day : function (input) {
  11115. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  11116. return input == null ? day :
  11117. this.add({ d : input - day });
  11118. },
  11119. startOf: function (units) {
  11120. units = units.replace(/s$/, '');
  11121. // the following switch intentionally omits break keywords
  11122. // to utilize falling through the cases.
  11123. switch (units) {
  11124. case 'year':
  11125. this.month(0);
  11126. /* falls through */
  11127. case 'month':
  11128. this.date(1);
  11129. /* falls through */
  11130. case 'week':
  11131. case 'day':
  11132. this.hours(0);
  11133. /* falls through */
  11134. case 'hour':
  11135. this.minutes(0);
  11136. /* falls through */
  11137. case 'minute':
  11138. this.seconds(0);
  11139. /* falls through */
  11140. case 'second':
  11141. this.milliseconds(0);
  11142. /* falls through */
  11143. }
  11144. // weeks are a special case
  11145. if (units === 'week') {
  11146. this.day(0);
  11147. }
  11148. return this;
  11149. },
  11150. endOf: function (units) {
  11151. return this.startOf(units).add(units.replace(/s?$/, 's'), 1).subtract('ms', 1);
  11152. },
  11153. isAfter: function (input, units) {
  11154. units = typeof units !== 'undefined' ? units : 'millisecond';
  11155. return +this.clone().startOf(units) > +moment(input).startOf(units);
  11156. },
  11157. isBefore: function (input, units) {
  11158. units = typeof units !== 'undefined' ? units : 'millisecond';
  11159. return +this.clone().startOf(units) < +moment(input).startOf(units);
  11160. },
  11161. isSame: function (input, units) {
  11162. units = typeof units !== 'undefined' ? units : 'millisecond';
  11163. return +this.clone().startOf(units) === +moment(input).startOf(units);
  11164. },
  11165. zone : function () {
  11166. return this._isUTC ? 0 : this._d.getTimezoneOffset();
  11167. },
  11168. daysInMonth : function () {
  11169. return moment.utc([this.year(), this.month() + 1, 0]).date();
  11170. },
  11171. dayOfYear : function (input) {
  11172. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  11173. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  11174. },
  11175. isoWeek : function (input) {
  11176. var week = weekOfYear(this, 1, 4);
  11177. return input == null ? week : this.add("d", (input - week) * 7);
  11178. },
  11179. week : function (input) {
  11180. var week = this.lang().week(this);
  11181. return input == null ? week : this.add("d", (input - week) * 7);
  11182. },
  11183. // If passed a language key, it will set the language for this
  11184. // instance. Otherwise, it will return the language configuration
  11185. // variables for this instance.
  11186. lang : function (key) {
  11187. if (key === undefined) {
  11188. return this._lang;
  11189. } else {
  11190. this._lang = getLangDefinition(key);
  11191. return this;
  11192. }
  11193. }
  11194. };
  11195. // helper for adding shortcuts
  11196. function makeGetterAndSetter(name, key) {
  11197. moment.fn[name] = moment.fn[name + 's'] = function (input) {
  11198. var utc = this._isUTC ? 'UTC' : '';
  11199. if (input != null) {
  11200. this._d['set' + utc + key](input);
  11201. return this;
  11202. } else {
  11203. return this._d['get' + utc + key]();
  11204. }
  11205. };
  11206. }
  11207. // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds)
  11208. for (i = 0; i < proxyGettersAndSetters.length; i ++) {
  11209. makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]);
  11210. }
  11211. // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear')
  11212. makeGetterAndSetter('year', 'FullYear');
  11213. // add plural methods
  11214. moment.fn.days = moment.fn.day;
  11215. moment.fn.weeks = moment.fn.week;
  11216. moment.fn.isoWeeks = moment.fn.isoWeek;
  11217. /************************************
  11218. Duration Prototype
  11219. ************************************/
  11220. moment.duration.fn = Duration.prototype = {
  11221. weeks : function () {
  11222. return absRound(this.days() / 7);
  11223. },
  11224. valueOf : function () {
  11225. return this._milliseconds +
  11226. this._days * 864e5 +
  11227. this._months * 2592e6;
  11228. },
  11229. humanize : function (withSuffix) {
  11230. var difference = +this,
  11231. output = relativeTime(difference, !withSuffix, this.lang());
  11232. if (withSuffix) {
  11233. output = this.lang().pastFuture(difference, output);
  11234. }
  11235. return this.lang().postformat(output);
  11236. },
  11237. lang : moment.fn.lang
  11238. };
  11239. function makeDurationGetter(name) {
  11240. moment.duration.fn[name] = function () {
  11241. return this._data[name];
  11242. };
  11243. }
  11244. function makeDurationAsGetter(name, factor) {
  11245. moment.duration.fn['as' + name] = function () {
  11246. return +this / factor;
  11247. };
  11248. }
  11249. for (i in unitMillisecondFactors) {
  11250. if (unitMillisecondFactors.hasOwnProperty(i)) {
  11251. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  11252. makeDurationGetter(i.toLowerCase());
  11253. }
  11254. }
  11255. makeDurationAsGetter('Weeks', 6048e5);
  11256. /************************************
  11257. Default Lang
  11258. ************************************/
  11259. // Set default language, other languages will inherit from English.
  11260. moment.lang('en', {
  11261. ordinal : function (number) {
  11262. var b = number % 10,
  11263. output = (~~ (number % 100 / 10) === 1) ? 'th' :
  11264. (b === 1) ? 'st' :
  11265. (b === 2) ? 'nd' :
  11266. (b === 3) ? 'rd' : 'th';
  11267. return number + output;
  11268. }
  11269. });
  11270. /************************************
  11271. Exposing Moment
  11272. ************************************/
  11273. // CommonJS module is defined
  11274. if (hasModule) {
  11275. module.exports = moment;
  11276. }
  11277. /*global ender:false */
  11278. if (typeof ender === 'undefined') {
  11279. // here, `this` means `window` in the browser, or `global` on the server
  11280. // add `moment` as a global object via a string identifier,
  11281. // for Closure Compiler "advanced" mode
  11282. this['moment'] = moment;
  11283. }
  11284. /*global define:false */
  11285. if (typeof define === "function" && define.amd) {
  11286. define("moment", [], function () {
  11287. return moment;
  11288. });
  11289. }
  11290. }).call(this);
  11291. })()
  11292. },{}]},{},[1])(1)
  11293. });
  11294. ;