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.

12841 lines
384 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
  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version 0.1.0
  8. * @date 2013-06-20
  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. return ((a.left - margin) < (b.left + b.width) &&
  2689. (a.left + a.width + margin) > b.left &&
  2690. (a.top - margin) < (b.top + b.height) &&
  2691. (a.top + a.height + margin) > b.top);
  2692. };
  2693. /**
  2694. * @constructor Range
  2695. * A Range controls a numeric range with a start and end value.
  2696. * The Range adjusts the range based on mouse events or programmatic changes,
  2697. * and triggers events when the range is changing or has been changed.
  2698. * @param {Object} [options] See description at Range.setOptions
  2699. * @extends Controller
  2700. */
  2701. function Range(options) {
  2702. this.id = util.randomUUID();
  2703. this.start = 0; // Number
  2704. this.end = 0; // Number
  2705. this.options = {
  2706. min: null,
  2707. max: null,
  2708. zoomMin: null,
  2709. zoomMax: null
  2710. };
  2711. this.listeners = [];
  2712. this.setOptions(options);
  2713. }
  2714. /**
  2715. * Set options for the range controller
  2716. * @param {Object} options Available options:
  2717. * {Number} start Set start value of the range
  2718. * {Number} end Set end value of the range
  2719. * {Number} min Minimum value for start
  2720. * {Number} max Maximum value for end
  2721. * {Number} zoomMin Set a minimum value for
  2722. * (end - start).
  2723. * {Number} zoomMax Set a maximum value for
  2724. * (end - start).
  2725. */
  2726. Range.prototype.setOptions = function (options) {
  2727. util.extend(this.options, options);
  2728. if (options.start != null || options.end != null) {
  2729. this.setRange(options.start, options.end);
  2730. }
  2731. };
  2732. /**
  2733. * Add listeners for mouse and touch events to the component
  2734. * @param {Component} component
  2735. * @param {String} event Available events: 'move', 'zoom'
  2736. * @param {String} direction Available directions: 'horizontal', 'vertical'
  2737. */
  2738. Range.prototype.subscribe = function (component, event, direction) {
  2739. var me = this;
  2740. var listener;
  2741. if (direction != 'horizontal' && direction != 'vertical') {
  2742. throw new TypeError('Unknown direction "' + direction + '". ' +
  2743. 'Choose "horizontal" or "vertical".');
  2744. }
  2745. //noinspection FallthroughInSwitchStatementJS
  2746. if (event == 'move') {
  2747. listener = {
  2748. component: component,
  2749. event: event,
  2750. direction: direction,
  2751. callback: function (event) {
  2752. me._onMouseDown(event, listener);
  2753. },
  2754. params: {}
  2755. };
  2756. component.on('mousedown', listener.callback);
  2757. me.listeners.push(listener);
  2758. }
  2759. else if (event == 'zoom') {
  2760. listener = {
  2761. component: component,
  2762. event: event,
  2763. direction: direction,
  2764. callback: function (event) {
  2765. me._onMouseWheel(event, listener);
  2766. },
  2767. params: {}
  2768. };
  2769. component.on('mousewheel', listener.callback);
  2770. me.listeners.push(listener);
  2771. }
  2772. else {
  2773. throw new TypeError('Unknown event "' + event + '". ' +
  2774. 'Choose "move" or "zoom".');
  2775. }
  2776. };
  2777. /**
  2778. * Event handler
  2779. * @param {String} event name of the event, for example 'click', 'mousemove'
  2780. * @param {function} callback callback handler, invoked with the raw HTML Event
  2781. * as parameter.
  2782. */
  2783. Range.prototype.on = function (event, callback) {
  2784. events.addListener(this, event, callback);
  2785. };
  2786. /**
  2787. * Trigger an event
  2788. * @param {String} event name of the event, available events: 'rangechange',
  2789. * 'rangechanged'
  2790. * @private
  2791. */
  2792. Range.prototype._trigger = function (event) {
  2793. events.trigger(this, event, {
  2794. start: this.start,
  2795. end: this.end
  2796. });
  2797. };
  2798. /**
  2799. * Set a new start and end range
  2800. * @param {Number} start
  2801. * @param {Number} end
  2802. */
  2803. Range.prototype.setRange = function(start, end) {
  2804. var changed = this._applyRange(start, end);
  2805. if (changed) {
  2806. this._trigger('rangechange');
  2807. this._trigger('rangechanged');
  2808. }
  2809. };
  2810. /**
  2811. * Set a new start and end range. This method is the same as setRange, but
  2812. * does not trigger a range change and range changed event, and it returns
  2813. * true when the range is changed
  2814. * @param {Number} start
  2815. * @param {Number} end
  2816. * @return {Boolean} changed
  2817. * @private
  2818. */
  2819. Range.prototype._applyRange = function(start, end) {
  2820. var newStart = (start != null) ? util.convert(start, 'Number') : this.start;
  2821. var newEnd = (end != null) ? util.convert(end, 'Number') : this.end;
  2822. var diff;
  2823. // check for valid number
  2824. if (isNaN(newStart)) {
  2825. throw new Error('Invalid start "' + start + '"');
  2826. }
  2827. if (isNaN(newEnd)) {
  2828. throw new Error('Invalid end "' + end + '"');
  2829. }
  2830. // prevent start < end
  2831. if (newEnd < newStart) {
  2832. newEnd = newStart;
  2833. }
  2834. // prevent start < min
  2835. if (this.options.min != null) {
  2836. var min = this.options.min.valueOf();
  2837. if (newStart < min) {
  2838. diff = (min - newStart);
  2839. newStart += diff;
  2840. newEnd += diff;
  2841. }
  2842. }
  2843. // prevent end > max
  2844. if (this.options.max != null) {
  2845. var max = this.options.max.valueOf();
  2846. if (newEnd > max) {
  2847. diff = (newEnd - max);
  2848. newStart -= diff;
  2849. newEnd -= diff;
  2850. }
  2851. }
  2852. // prevent (end-start) > zoomMin
  2853. if (this.options.zoomMin != null) {
  2854. var zoomMin = this.options.zoomMin.valueOf();
  2855. if (zoomMin < 0) {
  2856. zoomMin = 0;
  2857. }
  2858. if ((newEnd - newStart) < zoomMin) {
  2859. if ((this.end - this.start) > zoomMin) {
  2860. // zoom to the minimum
  2861. diff = (zoomMin - (newEnd - newStart));
  2862. newStart -= diff / 2;
  2863. newEnd += diff / 2;
  2864. }
  2865. else {
  2866. // ingore this action, we are already zoomed to the minimum
  2867. newStart = this.start;
  2868. newEnd = this.end;
  2869. }
  2870. }
  2871. }
  2872. // prevent (end-start) > zoomMin
  2873. if (this.options.zoomMax != null) {
  2874. var zoomMax = this.options.zoomMax.valueOf();
  2875. if (zoomMax < 0) {
  2876. zoomMax = 0;
  2877. }
  2878. if ((newEnd - newStart) > zoomMax) {
  2879. if ((this.end - this.start) < zoomMax) {
  2880. // zoom to the maximum
  2881. diff = ((newEnd - newStart) - zoomMax);
  2882. newStart += diff / 2;
  2883. newEnd -= diff / 2;
  2884. }
  2885. else {
  2886. // ingore this action, we are already zoomed to the maximum
  2887. newStart = this.start;
  2888. newEnd = this.end;
  2889. }
  2890. }
  2891. }
  2892. var changed = (this.start != newStart || this.end != newEnd);
  2893. this.start = newStart;
  2894. this.end = newEnd;
  2895. return changed;
  2896. };
  2897. /**
  2898. * Retrieve the current range.
  2899. * @return {Object} An object with start and end properties
  2900. */
  2901. Range.prototype.getRange = function() {
  2902. return {
  2903. start: this.start,
  2904. end: this.end
  2905. };
  2906. };
  2907. /**
  2908. * Calculate the conversion offset and factor for current range, based on
  2909. * the provided width
  2910. * @param {Number} width
  2911. * @returns {{offset: number, factor: number}} conversion
  2912. */
  2913. Range.prototype.conversion = function (width) {
  2914. var start = this.start;
  2915. var end = this.end;
  2916. return Range.conversion(this.start, this.end, width);
  2917. };
  2918. /**
  2919. * Static method to calculate the conversion offset and factor for a range,
  2920. * based on the provided start, end, and width
  2921. * @param {Number} start
  2922. * @param {Number} end
  2923. * @param {Number} width
  2924. * @returns {{offset: number, factor: number}} conversion
  2925. */
  2926. Range.conversion = function (start, end, width) {
  2927. if (width != 0 && (end - start != 0)) {
  2928. return {
  2929. offset: start,
  2930. factor: width / (end - start)
  2931. }
  2932. }
  2933. else {
  2934. return {
  2935. offset: 0,
  2936. factor: 1
  2937. };
  2938. }
  2939. };
  2940. /**
  2941. * Start moving horizontally or vertically
  2942. * @param {Event} event
  2943. * @param {Object} listener Listener containing the component and params
  2944. * @private
  2945. */
  2946. Range.prototype._onMouseDown = function(event, listener) {
  2947. event = event || window.event;
  2948. var params = listener.params;
  2949. // only react on left mouse button down
  2950. var leftButtonDown = event.which ? (event.which == 1) : (event.button == 1);
  2951. if (!leftButtonDown) {
  2952. return;
  2953. }
  2954. // get mouse position
  2955. params.mouseX = util.getPageX(event);
  2956. params.mouseY = util.getPageY(event);
  2957. params.previousLeft = 0;
  2958. params.previousOffset = 0;
  2959. params.moved = false;
  2960. params.start = this.start;
  2961. params.end = this.end;
  2962. var frame = listener.component.frame;
  2963. if (frame) {
  2964. frame.style.cursor = 'move';
  2965. }
  2966. // add event listeners to handle moving the contents
  2967. // we store the function onmousemove and onmouseup in the timeaxis,
  2968. // so we can remove the eventlisteners lateron in the function onmouseup
  2969. var me = this;
  2970. if (!params.onMouseMove) {
  2971. params.onMouseMove = function (event) {
  2972. me._onMouseMove(event, listener);
  2973. };
  2974. util.addEventListener(document, "mousemove", params.onMouseMove);
  2975. }
  2976. if (!params.onMouseUp) {
  2977. params.onMouseUp = function (event) {
  2978. me._onMouseUp(event, listener);
  2979. };
  2980. util.addEventListener(document, "mouseup", params.onMouseUp);
  2981. }
  2982. util.preventDefault(event);
  2983. };
  2984. /**
  2985. * Perform moving operating.
  2986. * This function activated from within the funcion TimeAxis._onMouseDown().
  2987. * @param {Event} event
  2988. * @param {Object} listener
  2989. * @private
  2990. */
  2991. Range.prototype._onMouseMove = function (event, listener) {
  2992. event = event || window.event;
  2993. var params = listener.params;
  2994. // calculate change in mouse position
  2995. var mouseX = util.getPageX(event);
  2996. var mouseY = util.getPageY(event);
  2997. if (params.mouseX == undefined) {
  2998. params.mouseX = mouseX;
  2999. }
  3000. if (params.mouseY == undefined) {
  3001. params.mouseY = mouseY;
  3002. }
  3003. var diffX = mouseX - params.mouseX;
  3004. var diffY = mouseY - params.mouseY;
  3005. var diff = (listener.direction == 'horizontal') ? diffX : diffY;
  3006. // if mouse movement is big enough, register it as a "moved" event
  3007. if (Math.abs(diff) >= 1) {
  3008. params.moved = true;
  3009. }
  3010. var interval = (params.end - params.start);
  3011. var width = (listener.direction == 'horizontal') ?
  3012. listener.component.width : listener.component.height;
  3013. var diffRange = -diff / width * interval;
  3014. this._applyRange(params.start + diffRange, params.end + diffRange);
  3015. // fire a rangechange event
  3016. this._trigger('rangechange');
  3017. util.preventDefault(event);
  3018. };
  3019. /**
  3020. * Stop moving operating.
  3021. * This function activated from within the function Range._onMouseDown().
  3022. * @param {event} event
  3023. * @param {Object} listener
  3024. * @private
  3025. */
  3026. Range.prototype._onMouseUp = function (event, listener) {
  3027. event = event || window.event;
  3028. var params = listener.params;
  3029. if (listener.component.frame) {
  3030. listener.component.frame.style.cursor = 'auto';
  3031. }
  3032. // remove event listeners here, important for Safari
  3033. if (params.onMouseMove) {
  3034. util.removeEventListener(document, "mousemove", params.onMouseMove);
  3035. params.onMouseMove = null;
  3036. }
  3037. if (params.onMouseUp) {
  3038. util.removeEventListener(document, "mouseup", params.onMouseUp);
  3039. params.onMouseUp = null;
  3040. }
  3041. //util.preventDefault(event);
  3042. if (params.moved) {
  3043. // fire a rangechanged event
  3044. this._trigger('rangechanged');
  3045. }
  3046. };
  3047. /**
  3048. * Event handler for mouse wheel event, used to zoom
  3049. * Code from http://adomas.org/javascript-mouse-wheel/
  3050. * @param {Event} event
  3051. * @param {Object} listener
  3052. * @private
  3053. */
  3054. Range.prototype._onMouseWheel = function(event, listener) {
  3055. event = event || window.event;
  3056. // retrieve delta
  3057. var delta = 0;
  3058. if (event.wheelDelta) { /* IE/Opera. */
  3059. delta = event.wheelDelta / 120;
  3060. } else if (event.detail) { /* Mozilla case. */
  3061. // In Mozilla, sign of delta is different than in IE.
  3062. // Also, delta is multiple of 3.
  3063. delta = -event.detail / 3;
  3064. }
  3065. // If delta is nonzero, handle it.
  3066. // Basically, delta is now positive if wheel was scrolled up,
  3067. // and negative, if wheel was scrolled down.
  3068. if (delta) {
  3069. var me = this;
  3070. var zoom = function () {
  3071. // perform the zoom action. Delta is normally 1 or -1
  3072. var zoomFactor = delta / 5.0;
  3073. var zoomAround = null;
  3074. var frame = listener.component.frame;
  3075. if (frame) {
  3076. var size, conversion;
  3077. if (listener.direction == 'horizontal') {
  3078. size = listener.component.width;
  3079. conversion = me.conversion(size);
  3080. var frameLeft = util.getAbsoluteLeft(frame);
  3081. var mouseX = util.getPageX(event);
  3082. zoomAround = (mouseX - frameLeft) / conversion.factor + conversion.offset;
  3083. }
  3084. else {
  3085. size = listener.component.height;
  3086. conversion = me.conversion(size);
  3087. var frameTop = util.getAbsoluteTop(frame);
  3088. var mouseY = util.getPageY(event);
  3089. zoomAround = ((frameTop + size - mouseY) - frameTop) / conversion.factor + conversion.offset;
  3090. }
  3091. }
  3092. me.zoom(zoomFactor, zoomAround);
  3093. };
  3094. zoom();
  3095. }
  3096. // Prevent default actions caused by mouse wheel.
  3097. // That might be ugly, but we handle scrolls somehow
  3098. // anyway, so don't bother here...
  3099. util.preventDefault(event);
  3100. };
  3101. /**
  3102. * Zoom the range the given zoomfactor in or out. Start and end date will
  3103. * be adjusted, and the timeline will be redrawn. You can optionally give a
  3104. * date around which to zoom.
  3105. * For example, try zoomfactor = 0.1 or -0.1
  3106. * @param {Number} zoomFactor Zooming amount. Positive value will zoom in,
  3107. * negative value will zoom out
  3108. * @param {Number} zoomAround Value around which will be zoomed. Optional
  3109. */
  3110. Range.prototype.zoom = function(zoomFactor, zoomAround) {
  3111. // if zoomAroundDate is not provided, take it half between start Date and end Date
  3112. if (zoomAround == null) {
  3113. zoomAround = (this.start + this.end) / 2;
  3114. }
  3115. // prevent zoom factor larger than 1 or smaller than -1 (larger than 1 will
  3116. // result in a start>=end )
  3117. if (zoomFactor >= 1) {
  3118. zoomFactor = 0.9;
  3119. }
  3120. if (zoomFactor <= -1) {
  3121. zoomFactor = -0.9;
  3122. }
  3123. // adjust a negative factor such that zooming in with 0.1 equals zooming
  3124. // out with a factor -0.1
  3125. if (zoomFactor < 0) {
  3126. zoomFactor = zoomFactor / (1 + zoomFactor);
  3127. }
  3128. // zoom start and end relative to the zoomAround value
  3129. var startDiff = (this.start - zoomAround);
  3130. var endDiff = (this.end - zoomAround);
  3131. // calculate new start and end
  3132. var newStart = this.start - startDiff * zoomFactor;
  3133. var newEnd = this.end - endDiff * zoomFactor;
  3134. this.setRange(newStart, newEnd);
  3135. };
  3136. /**
  3137. * Move the range with a given factor to the left or right. Start and end
  3138. * value will be adjusted. For example, try moveFactor = 0.1 or -0.1
  3139. * @param {Number} moveFactor Moving amount. Positive value will move right,
  3140. * negative value will move left
  3141. */
  3142. Range.prototype.move = function(moveFactor) {
  3143. // zoom start Date and end Date relative to the zoomAroundDate
  3144. var diff = (this.end - this.start);
  3145. // apply new values
  3146. var newStart = this.start + diff * moveFactor;
  3147. var newEnd = this.end + diff * moveFactor;
  3148. // TODO: reckon with min and max range
  3149. this.start = newStart;
  3150. this.end = newEnd;
  3151. };
  3152. /**
  3153. * @constructor Controller
  3154. *
  3155. * A Controller controls the reflows and repaints of all visual components
  3156. */
  3157. function Controller () {
  3158. this.id = util.randomUUID();
  3159. this.components = {};
  3160. this.repaintTimer = undefined;
  3161. this.reflowTimer = undefined;
  3162. }
  3163. /**
  3164. * Add a component to the controller
  3165. * @param {Component} component
  3166. */
  3167. Controller.prototype.add = function add(component) {
  3168. // validate the component
  3169. if (component.id == undefined) {
  3170. throw new Error('Component has no field id');
  3171. }
  3172. if (!(component instanceof Component) && !(component instanceof Controller)) {
  3173. throw new TypeError('Component must be an instance of ' +
  3174. 'prototype Component or Controller');
  3175. }
  3176. // add the component
  3177. component.controller = this;
  3178. this.components[component.id] = component;
  3179. };
  3180. /**
  3181. * Remove a component from the controller
  3182. * @param {Component | String} component
  3183. */
  3184. Controller.prototype.remove = function remove(component) {
  3185. var id;
  3186. for (id in this.components) {
  3187. if (this.components.hasOwnProperty(id)) {
  3188. if (id == component || this.components[id] == component) {
  3189. break;
  3190. }
  3191. }
  3192. }
  3193. if (id) {
  3194. delete this.components[id];
  3195. }
  3196. };
  3197. /**
  3198. * Request a reflow. The controller will schedule a reflow
  3199. * @param {Boolean} [force] If true, an immediate reflow is forced. Default
  3200. * is false.
  3201. */
  3202. Controller.prototype.requestReflow = function requestReflow(force) {
  3203. if (force) {
  3204. this.reflow();
  3205. }
  3206. else {
  3207. if (!this.reflowTimer) {
  3208. var me = this;
  3209. this.reflowTimer = setTimeout(function () {
  3210. me.reflowTimer = undefined;
  3211. me.reflow();
  3212. }, 0);
  3213. }
  3214. }
  3215. };
  3216. /**
  3217. * Request a repaint. The controller will schedule a repaint
  3218. * @param {Boolean} [force] If true, an immediate repaint is forced. Default
  3219. * is false.
  3220. */
  3221. Controller.prototype.requestRepaint = function requestRepaint(force) {
  3222. if (force) {
  3223. this.repaint();
  3224. }
  3225. else {
  3226. if (!this.repaintTimer) {
  3227. var me = this;
  3228. this.repaintTimer = setTimeout(function () {
  3229. me.repaintTimer = undefined;
  3230. me.repaint();
  3231. }, 0);
  3232. }
  3233. }
  3234. };
  3235. /**
  3236. * Repaint all components
  3237. */
  3238. Controller.prototype.repaint = function repaint() {
  3239. var changed = false;
  3240. // cancel any running repaint request
  3241. if (this.repaintTimer) {
  3242. clearTimeout(this.repaintTimer);
  3243. this.repaintTimer = undefined;
  3244. }
  3245. var done = {};
  3246. function repaint(component, id) {
  3247. if (!(id in done)) {
  3248. // first repaint the components on which this component is dependent
  3249. if (component.depends) {
  3250. component.depends.forEach(function (dep) {
  3251. repaint(dep, dep.id);
  3252. });
  3253. }
  3254. if (component.parent) {
  3255. repaint(component.parent, component.parent.id);
  3256. }
  3257. // repaint the component itself and mark as done
  3258. changed = component.repaint() || changed;
  3259. done[id] = true;
  3260. }
  3261. }
  3262. util.forEach(this.components, repaint);
  3263. // immediately reflow when needed
  3264. if (changed) {
  3265. this.reflow();
  3266. }
  3267. // TODO: limit the number of nested reflows/repaints, prevent loop
  3268. };
  3269. /**
  3270. * Reflow all components
  3271. */
  3272. Controller.prototype.reflow = function reflow() {
  3273. var resized = false;
  3274. // cancel any running repaint request
  3275. if (this.reflowTimer) {
  3276. clearTimeout(this.reflowTimer);
  3277. this.reflowTimer = undefined;
  3278. }
  3279. var done = {};
  3280. function reflow(component, id) {
  3281. if (!(id in done)) {
  3282. // first reflow the components on which this component is dependent
  3283. if (component.depends) {
  3284. component.depends.forEach(function (dep) {
  3285. reflow(dep, dep.id);
  3286. });
  3287. }
  3288. if (component.parent) {
  3289. reflow(component.parent, component.parent.id);
  3290. }
  3291. // reflow the component itself and mark as done
  3292. resized = component.reflow() || resized;
  3293. done[id] = true;
  3294. }
  3295. }
  3296. util.forEach(this.components, reflow);
  3297. // immediately repaint when needed
  3298. if (resized) {
  3299. this.repaint();
  3300. }
  3301. // TODO: limit the number of nested reflows/repaints, prevent loop
  3302. };
  3303. /**
  3304. * Prototype for visual components
  3305. */
  3306. function Component () {
  3307. this.id = null;
  3308. this.parent = null;
  3309. this.depends = null;
  3310. this.controller = null;
  3311. this.options = null;
  3312. this.frame = null; // main DOM element
  3313. this.top = 0;
  3314. this.left = 0;
  3315. this.width = 0;
  3316. this.height = 0;
  3317. }
  3318. /**
  3319. * Set parameters for the frame. Parameters will be merged in current parameter
  3320. * set.
  3321. * @param {Object} options Available parameters:
  3322. * {String | function} [className]
  3323. * {EventBus} [eventBus]
  3324. * {String | Number | function} [left]
  3325. * {String | Number | function} [top]
  3326. * {String | Number | function} [width]
  3327. * {String | Number | function} [height]
  3328. */
  3329. Component.prototype.setOptions = function setOptions(options) {
  3330. if (options) {
  3331. util.extend(this.options, options);
  3332. if (this.controller) {
  3333. this.requestRepaint();
  3334. this.requestReflow();
  3335. }
  3336. }
  3337. };
  3338. /**
  3339. * Get an option value by name
  3340. * The function will first check this.options object, and else will check
  3341. * this.defaultOptions.
  3342. * @param {String} name
  3343. * @return {*} value
  3344. */
  3345. Component.prototype.getOption = function getOption(name) {
  3346. var value;
  3347. if (this.options) {
  3348. value = this.options[name];
  3349. }
  3350. if (value === undefined && this.defaultOptions) {
  3351. value = this.defaultOptions[name];
  3352. }
  3353. return value;
  3354. };
  3355. /**
  3356. * Get the container element of the component, which can be used by a child to
  3357. * add its own widgets. Not all components do have a container for childs, in
  3358. * that case null is returned.
  3359. * @returns {HTMLElement | null} container
  3360. */
  3361. // TODO: get rid of the getContainer and getFrame methods, provide these via the options
  3362. Component.prototype.getContainer = function getContainer() {
  3363. // should be implemented by the component
  3364. return null;
  3365. };
  3366. /**
  3367. * Get the frame element of the component, the outer HTML DOM element.
  3368. * @returns {HTMLElement | null} frame
  3369. */
  3370. Component.prototype.getFrame = function getFrame() {
  3371. return this.frame;
  3372. };
  3373. /**
  3374. * Repaint the component
  3375. * @return {Boolean} changed
  3376. */
  3377. Component.prototype.repaint = function repaint() {
  3378. // should be implemented by the component
  3379. return false;
  3380. };
  3381. /**
  3382. * Reflow the component
  3383. * @return {Boolean} resized
  3384. */
  3385. Component.prototype.reflow = function reflow() {
  3386. // should be implemented by the component
  3387. return false;
  3388. };
  3389. /**
  3390. * Hide the component from the DOM
  3391. * @return {Boolean} changed
  3392. */
  3393. Component.prototype.hide = function hide() {
  3394. if (this.frame && this.frame.parentNode) {
  3395. this.frame.parentNode.removeChild(this.frame);
  3396. return true;
  3397. }
  3398. else {
  3399. return false;
  3400. }
  3401. };
  3402. /**
  3403. * Show the component in the DOM (when not already visible).
  3404. * A repaint will be executed when the component is not visible
  3405. * @return {Boolean} changed
  3406. */
  3407. Component.prototype.show = function show() {
  3408. if (!this.frame || !this.frame.parentNode) {
  3409. return this.repaint();
  3410. }
  3411. else {
  3412. return false;
  3413. }
  3414. };
  3415. /**
  3416. * Request a repaint. The controller will schedule a repaint
  3417. */
  3418. Component.prototype.requestRepaint = function requestRepaint() {
  3419. if (this.controller) {
  3420. this.controller.requestRepaint();
  3421. }
  3422. else {
  3423. throw new Error('Cannot request a repaint: no controller configured');
  3424. // TODO: just do a repaint when no parent is configured?
  3425. }
  3426. };
  3427. /**
  3428. * Request a reflow. The controller will schedule a reflow
  3429. */
  3430. Component.prototype.requestReflow = function requestReflow() {
  3431. if (this.controller) {
  3432. this.controller.requestReflow();
  3433. }
  3434. else {
  3435. throw new Error('Cannot request a reflow: no controller configured');
  3436. // TODO: just do a reflow when no parent is configured?
  3437. }
  3438. };
  3439. /**
  3440. * A panel can contain components
  3441. * @param {Component} [parent]
  3442. * @param {Component[]} [depends] Components on which this components depends
  3443. * (except for the parent)
  3444. * @param {Object} [options] Available parameters:
  3445. * {String | Number | function} [left]
  3446. * {String | Number | function} [top]
  3447. * {String | Number | function} [width]
  3448. * {String | Number | function} [height]
  3449. * {String | function} [className]
  3450. * @constructor Panel
  3451. * @extends Component
  3452. */
  3453. function Panel(parent, depends, options) {
  3454. this.id = util.randomUUID();
  3455. this.parent = parent;
  3456. this.depends = depends;
  3457. this.options = options || {};
  3458. }
  3459. Panel.prototype = new Component();
  3460. /**
  3461. * Set options. Will extend the current options.
  3462. * @param {Object} [options] Available parameters:
  3463. * {String | function} [className]
  3464. * {String | Number | function} [left]
  3465. * {String | Number | function} [top]
  3466. * {String | Number | function} [width]
  3467. * {String | Number | function} [height]
  3468. */
  3469. Panel.prototype.setOptions = Component.prototype.setOptions;
  3470. /**
  3471. * Get the container element of the panel, which can be used by a child to
  3472. * add its own widgets.
  3473. * @returns {HTMLElement} container
  3474. */
  3475. Panel.prototype.getContainer = function () {
  3476. return this.frame;
  3477. };
  3478. /**
  3479. * Repaint the component
  3480. * @return {Boolean} changed
  3481. */
  3482. Panel.prototype.repaint = function () {
  3483. var changed = 0,
  3484. update = util.updateProperty,
  3485. asSize = util.option.asSize,
  3486. options = this.options,
  3487. frame = this.frame;
  3488. if (!frame) {
  3489. frame = document.createElement('div');
  3490. frame.className = 'panel';
  3491. var className = options.className;
  3492. if (className) {
  3493. if (typeof className == 'function') {
  3494. util.addClassName(frame, String(className()));
  3495. }
  3496. else {
  3497. util.addClassName(frame, String(className));
  3498. }
  3499. }
  3500. this.frame = frame;
  3501. changed += 1;
  3502. }
  3503. if (!frame.parentNode) {
  3504. if (!this.parent) {
  3505. throw new Error('Cannot repaint panel: no parent attached');
  3506. }
  3507. var parentContainer = this.parent.getContainer();
  3508. if (!parentContainer) {
  3509. throw new Error('Cannot repaint panel: parent has no container element');
  3510. }
  3511. parentContainer.appendChild(frame);
  3512. changed += 1;
  3513. }
  3514. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3515. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3516. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3517. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3518. return (changed > 0);
  3519. };
  3520. /**
  3521. * Reflow the component
  3522. * @return {Boolean} resized
  3523. */
  3524. Panel.prototype.reflow = function () {
  3525. var changed = 0,
  3526. update = util.updateProperty,
  3527. frame = this.frame;
  3528. if (frame) {
  3529. changed += update(this, 'top', frame.offsetTop);
  3530. changed += update(this, 'left', frame.offsetLeft);
  3531. changed += update(this, 'width', frame.offsetWidth);
  3532. changed += update(this, 'height', frame.offsetHeight);
  3533. }
  3534. else {
  3535. changed += 1;
  3536. }
  3537. return (changed > 0);
  3538. };
  3539. /**
  3540. * A root panel can hold components. The root panel must be initialized with
  3541. * a DOM element as container.
  3542. * @param {HTMLElement} container
  3543. * @param {Object} [options] Available parameters: see RootPanel.setOptions.
  3544. * @constructor RootPanel
  3545. * @extends Panel
  3546. */
  3547. function RootPanel(container, options) {
  3548. this.id = util.randomUUID();
  3549. this.container = container;
  3550. this.options = options || {};
  3551. this.defaultOptions = {
  3552. autoResize: true
  3553. };
  3554. this.listeners = {}; // event listeners
  3555. }
  3556. RootPanel.prototype = new Panel();
  3557. /**
  3558. * Set options. Will extend the current options.
  3559. * @param {Object} [options] Available parameters:
  3560. * {String | function} [className]
  3561. * {String | Number | function} [left]
  3562. * {String | Number | function} [top]
  3563. * {String | Number | function} [width]
  3564. * {String | Number | function} [height]
  3565. * {Boolean | function} [autoResize]
  3566. */
  3567. RootPanel.prototype.setOptions = Component.prototype.setOptions;
  3568. /**
  3569. * Repaint the component
  3570. * @return {Boolean} changed
  3571. */
  3572. RootPanel.prototype.repaint = function () {
  3573. var changed = 0,
  3574. update = util.updateProperty,
  3575. asSize = util.option.asSize,
  3576. options = this.options,
  3577. frame = this.frame;
  3578. if (!frame) {
  3579. frame = document.createElement('div');
  3580. frame.className = 'vis timeline rootpanel';
  3581. var className = options.className;
  3582. if (className) {
  3583. util.addClassName(frame, util.option.asString(className));
  3584. }
  3585. this.frame = frame;
  3586. changed += 1;
  3587. }
  3588. if (!frame.parentNode) {
  3589. if (!this.container) {
  3590. throw new Error('Cannot repaint root panel: no container attached');
  3591. }
  3592. this.container.appendChild(frame);
  3593. changed += 1;
  3594. }
  3595. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  3596. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3597. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3598. changed += update(frame.style, 'height', asSize(options.height, '100%'));
  3599. this._updateEventEmitters();
  3600. this._updateWatch();
  3601. return (changed > 0);
  3602. };
  3603. /**
  3604. * Reflow the component
  3605. * @return {Boolean} resized
  3606. */
  3607. RootPanel.prototype.reflow = function () {
  3608. var changed = 0,
  3609. update = util.updateProperty,
  3610. frame = this.frame;
  3611. if (frame) {
  3612. changed += update(this, 'top', frame.offsetTop);
  3613. changed += update(this, 'left', frame.offsetLeft);
  3614. changed += update(this, 'width', frame.offsetWidth);
  3615. changed += update(this, 'height', frame.offsetHeight);
  3616. }
  3617. else {
  3618. changed += 1;
  3619. }
  3620. return (changed > 0);
  3621. };
  3622. /**
  3623. * Update watching for resize, depending on the current option
  3624. * @private
  3625. */
  3626. RootPanel.prototype._updateWatch = function () {
  3627. var autoResize = this.getOption('autoResize');
  3628. if (autoResize) {
  3629. this._watch();
  3630. }
  3631. else {
  3632. this._unwatch();
  3633. }
  3634. };
  3635. /**
  3636. * Watch for changes in the size of the frame. On resize, the Panel will
  3637. * automatically redraw itself.
  3638. * @private
  3639. */
  3640. RootPanel.prototype._watch = function () {
  3641. var me = this;
  3642. this._unwatch();
  3643. var checkSize = function () {
  3644. var autoResize = me.getOption('autoResize');
  3645. if (!autoResize) {
  3646. // stop watching when the option autoResize is changed to false
  3647. me._unwatch();
  3648. return;
  3649. }
  3650. if (me.frame) {
  3651. // check whether the frame is resized
  3652. if ((me.frame.clientWidth != me.width) ||
  3653. (me.frame.clientHeight != me.height)) {
  3654. me.requestReflow();
  3655. }
  3656. }
  3657. };
  3658. // TODO: automatically cleanup the event listener when the frame is deleted
  3659. util.addEventListener(window, 'resize', checkSize);
  3660. this.watchTimer = setInterval(checkSize, 1000);
  3661. };
  3662. /**
  3663. * Stop watching for a resize of the frame.
  3664. * @private
  3665. */
  3666. RootPanel.prototype._unwatch = function () {
  3667. if (this.watchTimer) {
  3668. clearInterval(this.watchTimer);
  3669. this.watchTimer = undefined;
  3670. }
  3671. // TODO: remove event listener on window.resize
  3672. };
  3673. /**
  3674. * Event handler
  3675. * @param {String} event name of the event, for example 'click', 'mousemove'
  3676. * @param {function} callback callback handler, invoked with the raw HTML Event
  3677. * as parameter.
  3678. */
  3679. RootPanel.prototype.on = function (event, callback) {
  3680. // register the listener at this component
  3681. var arr = this.listeners[event];
  3682. if (!arr) {
  3683. arr = [];
  3684. this.listeners[event] = arr;
  3685. }
  3686. arr.push(callback);
  3687. this._updateEventEmitters();
  3688. };
  3689. /**
  3690. * Update the event listeners for all event emitters
  3691. * @private
  3692. */
  3693. RootPanel.prototype._updateEventEmitters = function () {
  3694. if (this.listeners) {
  3695. var me = this;
  3696. util.forEach(this.listeners, function (listeners, event) {
  3697. if (!me.emitters) {
  3698. me.emitters = {};
  3699. }
  3700. if (!(event in me.emitters)) {
  3701. // create event
  3702. var frame = me.frame;
  3703. if (frame) {
  3704. //console.log('Created a listener for event ' + event + ' on component ' + me.id); // TODO: cleanup logging
  3705. var callback = function(event) {
  3706. listeners.forEach(function (listener) {
  3707. // TODO: filter on event target!
  3708. listener(event);
  3709. });
  3710. };
  3711. me.emitters[event] = callback;
  3712. util.addEventListener(frame, event, callback);
  3713. }
  3714. }
  3715. });
  3716. // TODO: be able to delete event listeners
  3717. // TODO: be able to move event listeners to a parent when available
  3718. }
  3719. };
  3720. /**
  3721. * A horizontal time axis
  3722. * @param {Component} parent
  3723. * @param {Component[]} [depends] Components on which this components depends
  3724. * (except for the parent)
  3725. * @param {Object} [options] See TimeAxis.setOptions for the available
  3726. * options.
  3727. * @constructor TimeAxis
  3728. * @extends Component
  3729. */
  3730. function TimeAxis (parent, depends, options) {
  3731. this.id = util.randomUUID();
  3732. this.parent = parent;
  3733. this.depends = depends;
  3734. this.dom = {
  3735. majorLines: [],
  3736. majorTexts: [],
  3737. minorLines: [],
  3738. minorTexts: [],
  3739. redundant: {
  3740. majorLines: [],
  3741. majorTexts: [],
  3742. minorLines: [],
  3743. minorTexts: []
  3744. }
  3745. };
  3746. this.props = {
  3747. range: {
  3748. start: 0,
  3749. end: 0,
  3750. minimumStep: 0
  3751. },
  3752. lineTop: 0
  3753. };
  3754. this.options = options || {};
  3755. this.defaultOptions = {
  3756. orientation: 'bottom', // supported: 'top', 'bottom'
  3757. // TODO: implement timeaxis orientations 'left' and 'right'
  3758. showMinorLabels: true,
  3759. showMajorLabels: true
  3760. };
  3761. this.conversion = null;
  3762. this.range = null;
  3763. }
  3764. TimeAxis.prototype = new Component();
  3765. // TODO: comment options
  3766. TimeAxis.prototype.setOptions = Component.prototype.setOptions;
  3767. /**
  3768. * Set a range (start and end)
  3769. * @param {Range | Object} range A Range or an object containing start and end.
  3770. */
  3771. TimeAxis.prototype.setRange = function (range) {
  3772. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  3773. throw new TypeError('Range must be an instance of Range, ' +
  3774. 'or an object containing start and end.');
  3775. }
  3776. this.range = range;
  3777. };
  3778. /**
  3779. * Convert a position on screen (pixels) to a datetime
  3780. * @param {int} x Position on the screen in pixels
  3781. * @return {Date} time The datetime the corresponds with given position x
  3782. */
  3783. TimeAxis.prototype.toTime = function(x) {
  3784. var conversion = this.conversion;
  3785. return new Date(x / conversion.factor + conversion.offset);
  3786. };
  3787. /**
  3788. * Convert a datetime (Date object) into a position on the screen
  3789. * @param {Date} time A date
  3790. * @return {int} x The position on the screen in pixels which corresponds
  3791. * with the given date.
  3792. * @private
  3793. */
  3794. TimeAxis.prototype.toScreen = function(time) {
  3795. var conversion = this.conversion;
  3796. return (time.valueOf() - conversion.offset) * conversion.factor;
  3797. };
  3798. /**
  3799. * Repaint the component
  3800. * @return {Boolean} changed
  3801. */
  3802. TimeAxis.prototype.repaint = function () {
  3803. var changed = 0,
  3804. update = util.updateProperty,
  3805. asSize = util.option.asSize,
  3806. options = this.options,
  3807. orientation = this.getOption('orientation'),
  3808. props = this.props,
  3809. step = this.step;
  3810. var frame = this.frame;
  3811. if (!frame) {
  3812. frame = document.createElement('div');
  3813. this.frame = frame;
  3814. changed += 1;
  3815. }
  3816. frame.className = 'axis ' + orientation;
  3817. // TODO: custom className?
  3818. if (!frame.parentNode) {
  3819. if (!this.parent) {
  3820. throw new Error('Cannot repaint time axis: no parent attached');
  3821. }
  3822. var parentContainer = this.parent.getContainer();
  3823. if (!parentContainer) {
  3824. throw new Error('Cannot repaint time axis: parent has no container element');
  3825. }
  3826. parentContainer.appendChild(frame);
  3827. changed += 1;
  3828. }
  3829. var parent = frame.parentNode;
  3830. if (parent) {
  3831. var beforeChild = frame.nextSibling;
  3832. parent.removeChild(frame); // take frame offline while updating (is almost twice as fast)
  3833. var defaultTop = (orientation == 'bottom' && this.props.parentHeight && this.height) ?
  3834. (this.props.parentHeight - this.height) + 'px' :
  3835. '0px';
  3836. changed += update(frame.style, 'top', asSize(options.top, defaultTop));
  3837. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  3838. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  3839. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  3840. // get characters width and height
  3841. this._repaintMeasureChars();
  3842. if (this.step) {
  3843. this._repaintStart();
  3844. step.first();
  3845. var xFirstMajorLabel = undefined;
  3846. var max = 0;
  3847. while (step.hasNext() && max < 1000) {
  3848. max++;
  3849. var cur = step.getCurrent(),
  3850. x = this.toScreen(cur),
  3851. isMajor = step.isMajor();
  3852. // TODO: lines must have a width, such that we can create css backgrounds
  3853. if (this.getOption('showMinorLabels')) {
  3854. this._repaintMinorText(x, step.getLabelMinor());
  3855. }
  3856. if (isMajor && this.getOption('showMajorLabels')) {
  3857. if (x > 0) {
  3858. if (xFirstMajorLabel == undefined) {
  3859. xFirstMajorLabel = x;
  3860. }
  3861. this._repaintMajorText(x, step.getLabelMajor());
  3862. }
  3863. this._repaintMajorLine(x);
  3864. }
  3865. else {
  3866. this._repaintMinorLine(x);
  3867. }
  3868. step.next();
  3869. }
  3870. // create a major label on the left when needed
  3871. if (this.getOption('showMajorLabels')) {
  3872. var leftTime = this.toTime(0),
  3873. leftText = step.getLabelMajor(leftTime),
  3874. widthText = leftText.length * (props.majorCharWidth || 10) + 10; // upper bound estimation
  3875. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  3876. this._repaintMajorText(0, leftText);
  3877. }
  3878. }
  3879. this._repaintEnd();
  3880. }
  3881. this._repaintLine();
  3882. // put frame online again
  3883. if (beforeChild) {
  3884. parent.insertBefore(frame, beforeChild);
  3885. }
  3886. else {
  3887. parent.appendChild(frame)
  3888. }
  3889. }
  3890. return (changed > 0);
  3891. };
  3892. /**
  3893. * Start a repaint. Move all DOM elements to a redundant list, where they
  3894. * can be picked for re-use, or can be cleaned up in the end
  3895. * @private
  3896. */
  3897. TimeAxis.prototype._repaintStart = function () {
  3898. var dom = this.dom,
  3899. redundant = dom.redundant;
  3900. redundant.majorLines = dom.majorLines;
  3901. redundant.majorTexts = dom.majorTexts;
  3902. redundant.minorLines = dom.minorLines;
  3903. redundant.minorTexts = dom.minorTexts;
  3904. dom.majorLines = [];
  3905. dom.majorTexts = [];
  3906. dom.minorLines = [];
  3907. dom.minorTexts = [];
  3908. };
  3909. /**
  3910. * End a repaint. Cleanup leftover DOM elements in the redundant list
  3911. * @private
  3912. */
  3913. TimeAxis.prototype._repaintEnd = function () {
  3914. util.forEach(this.dom.redundant, function (arr) {
  3915. while (arr.length) {
  3916. var elem = arr.pop();
  3917. if (elem && elem.parentNode) {
  3918. elem.parentNode.removeChild(elem);
  3919. }
  3920. }
  3921. });
  3922. };
  3923. /**
  3924. * Create a minor label for the axis at position x
  3925. * @param {Number} x
  3926. * @param {String} text
  3927. * @private
  3928. */
  3929. TimeAxis.prototype._repaintMinorText = function (x, text) {
  3930. // reuse redundant label
  3931. var label = this.dom.redundant.minorTexts.shift();
  3932. if (!label) {
  3933. // create new label
  3934. var content = document.createTextNode('');
  3935. label = document.createElement('div');
  3936. label.appendChild(content);
  3937. label.className = 'text minor';
  3938. this.frame.appendChild(label);
  3939. }
  3940. this.dom.minorTexts.push(label);
  3941. label.childNodes[0].nodeValue = text;
  3942. label.style.left = x + 'px';
  3943. label.style.top = this.props.minorLabelTop + 'px';
  3944. //label.title = title; // TODO: this is a heavy operation
  3945. };
  3946. /**
  3947. * Create a Major label for the axis at position x
  3948. * @param {Number} x
  3949. * @param {String} text
  3950. * @private
  3951. */
  3952. TimeAxis.prototype._repaintMajorText = function (x, text) {
  3953. // reuse redundant label
  3954. var label = this.dom.redundant.majorTexts.shift();
  3955. if (!label) {
  3956. // create label
  3957. var content = document.createTextNode(text);
  3958. label = document.createElement('div');
  3959. label.className = 'text major';
  3960. label.appendChild(content);
  3961. this.frame.appendChild(label);
  3962. }
  3963. this.dom.majorTexts.push(label);
  3964. label.childNodes[0].nodeValue = text;
  3965. label.style.top = this.props.majorLabelTop + 'px';
  3966. label.style.left = x + 'px';
  3967. //label.title = title; // TODO: this is a heavy operation
  3968. };
  3969. /**
  3970. * Create a minor line for the axis at position x
  3971. * @param {Number} x
  3972. * @private
  3973. */
  3974. TimeAxis.prototype._repaintMinorLine = function (x) {
  3975. // reuse redundant line
  3976. var line = this.dom.redundant.minorLines.shift();
  3977. if (!line) {
  3978. // create vertical line
  3979. line = document.createElement('div');
  3980. line.className = 'grid vertical minor';
  3981. this.frame.appendChild(line);
  3982. }
  3983. this.dom.minorLines.push(line);
  3984. var props = this.props;
  3985. line.style.top = props.minorLineTop + 'px';
  3986. line.style.height = props.minorLineHeight + 'px';
  3987. line.style.left = (x - props.minorLineWidth / 2) + 'px';
  3988. };
  3989. /**
  3990. * Create a Major line for the axis at position x
  3991. * @param {Number} x
  3992. * @private
  3993. */
  3994. TimeAxis.prototype._repaintMajorLine = function (x) {
  3995. // reuse redundant line
  3996. var line = this.dom.redundant.majorLines.shift();
  3997. if (!line) {
  3998. // create vertical line
  3999. line = document.createElement('DIV');
  4000. line.className = 'grid vertical major';
  4001. this.frame.appendChild(line);
  4002. }
  4003. this.dom.majorLines.push(line);
  4004. var props = this.props;
  4005. line.style.top = props.majorLineTop + 'px';
  4006. line.style.left = (x - props.majorLineWidth / 2) + 'px';
  4007. line.style.height = props.majorLineHeight + 'px';
  4008. };
  4009. /**
  4010. * Repaint the horizontal line for the axis
  4011. * @private
  4012. */
  4013. TimeAxis.prototype._repaintLine = function() {
  4014. var line = this.dom.line,
  4015. frame = this.frame,
  4016. options = this.options;
  4017. // line before all axis elements
  4018. if (this.getOption('showMinorLabels') || this.getOption('showMajorLabels')) {
  4019. if (line) {
  4020. // put this line at the end of all childs
  4021. frame.removeChild(line);
  4022. frame.appendChild(line);
  4023. }
  4024. else {
  4025. // create the axis line
  4026. line = document.createElement('div');
  4027. line.className = 'grid horizontal major';
  4028. frame.appendChild(line);
  4029. this.dom.line = line;
  4030. }
  4031. line.style.top = this.props.lineTop + 'px';
  4032. }
  4033. else {
  4034. if (line && axis.parentElement) {
  4035. frame.removeChild(axis.line);
  4036. delete this.dom.line;
  4037. }
  4038. }
  4039. };
  4040. /**
  4041. * Create characters used to determine the size of text on the axis
  4042. * @private
  4043. */
  4044. TimeAxis.prototype._repaintMeasureChars = function () {
  4045. // calculate the width and height of a single character
  4046. // this is used to calculate the step size, and also the positioning of the
  4047. // axis
  4048. var dom = this.dom,
  4049. text;
  4050. if (!dom.measureCharMinor) {
  4051. text = document.createTextNode('0');
  4052. var measureCharMinor = document.createElement('DIV');
  4053. measureCharMinor.className = 'text minor measure';
  4054. measureCharMinor.appendChild(text);
  4055. this.frame.appendChild(measureCharMinor);
  4056. dom.measureCharMinor = measureCharMinor;
  4057. }
  4058. if (!dom.measureCharMajor) {
  4059. text = document.createTextNode('0');
  4060. var measureCharMajor = document.createElement('DIV');
  4061. measureCharMajor.className = 'text major measure';
  4062. measureCharMajor.appendChild(text);
  4063. this.frame.appendChild(measureCharMajor);
  4064. dom.measureCharMajor = measureCharMajor;
  4065. }
  4066. };
  4067. /**
  4068. * Reflow the component
  4069. * @return {Boolean} resized
  4070. */
  4071. TimeAxis.prototype.reflow = function () {
  4072. var changed = 0,
  4073. update = util.updateProperty,
  4074. frame = this.frame,
  4075. range = this.range;
  4076. if (!range) {
  4077. throw new Error('Cannot repaint time axis: no range configured');
  4078. }
  4079. if (frame) {
  4080. changed += update(this, 'top', frame.offsetTop);
  4081. changed += update(this, 'left', frame.offsetLeft);
  4082. // calculate size of a character
  4083. var props = this.props,
  4084. showMinorLabels = this.getOption('showMinorLabels'),
  4085. showMajorLabels = this.getOption('showMajorLabels'),
  4086. measureCharMinor = this.dom.measureCharMinor,
  4087. measureCharMajor = this.dom.measureCharMajor;
  4088. if (measureCharMinor) {
  4089. props.minorCharHeight = measureCharMinor.clientHeight;
  4090. props.minorCharWidth = measureCharMinor.clientWidth;
  4091. }
  4092. if (measureCharMajor) {
  4093. props.majorCharHeight = measureCharMajor.clientHeight;
  4094. props.majorCharWidth = measureCharMajor.clientWidth;
  4095. }
  4096. var parentHeight = frame.parentNode ? frame.parentNode.offsetHeight : 0;
  4097. if (parentHeight != props.parentHeight) {
  4098. props.parentHeight = parentHeight;
  4099. changed += 1;
  4100. }
  4101. switch (this.getOption('orientation')) {
  4102. case 'bottom':
  4103. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4104. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4105. props.minorLabelTop = 0;
  4106. props.majorLabelTop = props.minorLabelTop + props.minorLabelHeight;
  4107. props.minorLineTop = -this.top;
  4108. props.minorLineHeight = Math.max(this.top + props.majorLabelHeight, 0);
  4109. props.minorLineWidth = 1; // TODO: really calculate width
  4110. props.majorLineTop = -this.top;
  4111. props.majorLineHeight = Math.max(this.top + props.minorLabelHeight + props.majorLabelHeight, 0);
  4112. props.majorLineWidth = 1; // TODO: really calculate width
  4113. props.lineTop = 0;
  4114. break;
  4115. case 'top':
  4116. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  4117. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  4118. props.majorLabelTop = 0;
  4119. props.minorLabelTop = props.majorLabelTop + props.majorLabelHeight;
  4120. props.minorLineTop = props.minorLabelTop;
  4121. props.minorLineHeight = Math.max(parentHeight - props.majorLabelHeight - this.top);
  4122. props.minorLineWidth = 1; // TODO: really calculate width
  4123. props.majorLineTop = 0;
  4124. props.majorLineHeight = Math.max(parentHeight - this.top);
  4125. props.majorLineWidth = 1; // TODO: really calculate width
  4126. props.lineTop = props.majorLabelHeight + props.minorLabelHeight;
  4127. break;
  4128. default:
  4129. throw new Error('Unkown orientation "' + this.getOption('orientation') + '"');
  4130. }
  4131. var height = props.minorLabelHeight + props.majorLabelHeight;
  4132. changed += update(this, 'width', frame.offsetWidth);
  4133. changed += update(this, 'height', height);
  4134. // calculate range and step
  4135. this._updateConversion();
  4136. var start = util.convert(range.start, 'Date'),
  4137. end = util.convert(range.end, 'Date'),
  4138. minimumStep = this.toTime((props.minorCharWidth || 10) * 5) - this.toTime(0);
  4139. this.step = new TimeStep(start, end, minimumStep);
  4140. changed += update(props.range, 'start', start.valueOf());
  4141. changed += update(props.range, 'end', end.valueOf());
  4142. changed += update(props.range, 'minimumStep', minimumStep.valueOf());
  4143. }
  4144. return (changed > 0);
  4145. };
  4146. /**
  4147. * Calculate the factor and offset to convert a position on screen to the
  4148. * corresponding date and vice versa.
  4149. * After the method _updateConversion is executed once, the methods toTime
  4150. * and toScreen can be used.
  4151. * @private
  4152. */
  4153. TimeAxis.prototype._updateConversion = function() {
  4154. var range = this.range;
  4155. if (!range) {
  4156. throw new Error('No range configured');
  4157. }
  4158. if (range.conversion) {
  4159. this.conversion = range.conversion(this.width);
  4160. }
  4161. else {
  4162. this.conversion = Range.conversion(range.start, range.end, this.width);
  4163. }
  4164. };
  4165. /**
  4166. * An ItemSet holds a set of items and ranges which can be displayed in a
  4167. * range. The width is determined by the parent of the ItemSet, and the height
  4168. * is determined by the size of the items.
  4169. * @param {Component} parent
  4170. * @param {Component[]} [depends] Components on which this components depends
  4171. * (except for the parent)
  4172. * @param {Object} [options] See ItemSet.setOptions for the available
  4173. * options.
  4174. * @constructor ItemSet
  4175. * @extends Panel
  4176. */
  4177. // TODO: improve performance by replacing all Array.forEach with a for loop
  4178. function ItemSet(parent, depends, options) {
  4179. this.id = util.randomUUID();
  4180. this.parent = parent;
  4181. this.depends = depends;
  4182. // one options object is shared by this itemset and all its items
  4183. this.options = options || {};
  4184. this.defaultOptions = {
  4185. type: 'box',
  4186. align: 'center',
  4187. orientation: 'bottom',
  4188. margin: {
  4189. axis: 20,
  4190. item: 10
  4191. },
  4192. padding: 5
  4193. };
  4194. this.dom = {};
  4195. var me = this;
  4196. this.itemsData = null; // DataSet
  4197. this.range = null; // Range or Object {start: number, end: number}
  4198. this.listeners = {
  4199. 'add': function (event, params, senderId) {
  4200. if (senderId != me.id) {
  4201. me._onAdd(params.items);
  4202. }
  4203. },
  4204. 'update': function (event, params, senderId) {
  4205. if (senderId != me.id) {
  4206. me._onUpdate(params.items);
  4207. }
  4208. },
  4209. 'remove': function (event, params, senderId) {
  4210. if (senderId != me.id) {
  4211. me._onRemove(params.items);
  4212. }
  4213. }
  4214. };
  4215. this.items = {}; // object with an Item for every data item
  4216. this.queue = {}; // queue with id/actions: 'add', 'update', 'delete'
  4217. this.stack = new Stack(this, Object.create(this.options));
  4218. this.conversion = null;
  4219. // TODO: ItemSet should also attach event listeners for rangechange and rangechanged, like timeaxis
  4220. }
  4221. ItemSet.prototype = new Panel();
  4222. // available item types will be registered here
  4223. ItemSet.types = {
  4224. box: ItemBox,
  4225. range: ItemRange,
  4226. point: ItemPoint
  4227. };
  4228. /**
  4229. * Set options for the ItemSet. Existing options will be extended/overwritten.
  4230. * @param {Object} [options] The following options are available:
  4231. * {String | function} [className]
  4232. * class name for the itemset
  4233. * {String} [type]
  4234. * Default type for the items. Choose from 'box'
  4235. * (default), 'point', or 'range'. The default
  4236. * Style can be overwritten by individual items.
  4237. * {String} align
  4238. * Alignment for the items, only applicable for
  4239. * ItemBox. Choose 'center' (default), 'left', or
  4240. * 'right'.
  4241. * {String} orientation
  4242. * Orientation of the item set. Choose 'top' or
  4243. * 'bottom' (default).
  4244. * {Number} margin.axis
  4245. * Margin between the axis and the items in pixels.
  4246. * Default is 20.
  4247. * {Number} margin.item
  4248. * Margin between items in pixels. Default is 10.
  4249. * {Number} padding
  4250. * Padding of the contents of an item in pixels.
  4251. * Must correspond with the items css. Default is 5.
  4252. */
  4253. ItemSet.prototype.setOptions = Component.prototype.setOptions;
  4254. /**
  4255. * Set range (start and end).
  4256. * @param {Range | Object} range A Range or an object containing start and end.
  4257. */
  4258. ItemSet.prototype.setRange = function setRange(range) {
  4259. if (!(range instanceof Range) && (!range || !range.start || !range.end)) {
  4260. throw new TypeError('Range must be an instance of Range, ' +
  4261. 'or an object containing start and end.');
  4262. }
  4263. this.range = range;
  4264. };
  4265. /**
  4266. * Repaint the component
  4267. * @return {Boolean} changed
  4268. */
  4269. ItemSet.prototype.repaint = function repaint() {
  4270. var changed = 0,
  4271. update = util.updateProperty,
  4272. asSize = util.option.asSize,
  4273. options = this.options,
  4274. orientation = this.getOption('orientation'),
  4275. defaultOptions = this.defaultOptions,
  4276. frame = this.frame;
  4277. if (!frame) {
  4278. frame = document.createElement('div');
  4279. frame.className = 'itemset';
  4280. var className = options.className;
  4281. if (className) {
  4282. util.addClassName(frame, util.option.asString(className));
  4283. }
  4284. // create background panel
  4285. var background = document.createElement('div');
  4286. background.className = 'background';
  4287. frame.appendChild(background);
  4288. this.dom.background = background;
  4289. // create foreground panel
  4290. var foreground = document.createElement('div');
  4291. foreground.className = 'foreground';
  4292. frame.appendChild(foreground);
  4293. this.dom.foreground = foreground;
  4294. // create axis panel
  4295. var axis = document.createElement('div');
  4296. axis.className = 'itemset-axis';
  4297. //frame.appendChild(axis);
  4298. this.dom.axis = axis;
  4299. this.frame = frame;
  4300. changed += 1;
  4301. }
  4302. if (!this.parent) {
  4303. throw new Error('Cannot repaint itemset: no parent attached');
  4304. }
  4305. var parentContainer = this.parent.getContainer();
  4306. if (!parentContainer) {
  4307. throw new Error('Cannot repaint itemset: parent has no container element');
  4308. }
  4309. if (!frame.parentNode) {
  4310. parentContainer.appendChild(frame);
  4311. changed += 1;
  4312. }
  4313. if (!this.dom.axis.parentNode) {
  4314. parentContainer.appendChild(this.dom.axis);
  4315. changed += 1;
  4316. }
  4317. // reposition frame
  4318. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  4319. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  4320. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  4321. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  4322. // reposition axis
  4323. changed += update(this.dom.axis.style, 'left', asSize(options.left, '0px'));
  4324. changed += update(this.dom.axis.style, 'width', asSize(options.width, '100%'));
  4325. if (orientation == 'bottom') {
  4326. changed += update(this.dom.axis.style, 'top', (this.height + this.top) + 'px');
  4327. }
  4328. else { // orientation == 'top'
  4329. changed += update(this.dom.axis.style, 'top', this.top + 'px');
  4330. }
  4331. this._updateConversion();
  4332. var me = this,
  4333. queue = this.queue,
  4334. itemsData = this.itemsData,
  4335. items = this.items,
  4336. dataOptions = {
  4337. fields: [(itemsData && itemsData.fieldId || 'id'), 'start', 'end', 'content', 'type']
  4338. };
  4339. // TODO: copy options from the itemset itself?
  4340. // show/hide added/changed/removed items
  4341. Object.keys(queue).forEach(function (id) {
  4342. //var entry = queue[id];
  4343. var action = queue[id];
  4344. var item = items[id];
  4345. //var item = entry.item;
  4346. //noinspection FallthroughInSwitchStatementJS
  4347. switch (action) {
  4348. case 'add':
  4349. case 'update':
  4350. var itemData = itemsData && itemsData.get(id, dataOptions);
  4351. if (itemData) {
  4352. var type = itemData.type ||
  4353. (itemData.start && itemData.end && 'range') ||
  4354. options.type ||
  4355. 'box';
  4356. var constructor = ItemSet.types[type];
  4357. // TODO: how to handle items with invalid data? hide them and give a warning? or throw an error?
  4358. if (item) {
  4359. // update item
  4360. if (!constructor || !(item instanceof constructor)) {
  4361. // item type has changed, hide and delete the item
  4362. changed += item.hide();
  4363. item = null;
  4364. }
  4365. else {
  4366. item.data = itemData; // TODO: create a method item.setData ?
  4367. changed++;
  4368. }
  4369. }
  4370. if (!item) {
  4371. // create item
  4372. if (constructor) {
  4373. item = new constructor(me, itemData, options, defaultOptions);
  4374. changed++;
  4375. }
  4376. else {
  4377. throw new TypeError('Unknown item type "' + type + '"');
  4378. }
  4379. }
  4380. // force a repaint (not only a reposition)
  4381. item.repaint();
  4382. items[id] = item;
  4383. }
  4384. // update queue
  4385. delete queue[id];
  4386. break;
  4387. case 'remove':
  4388. if (item) {
  4389. // remove DOM of the item
  4390. changed += item.hide();
  4391. }
  4392. // update lists
  4393. delete items[id];
  4394. delete queue[id];
  4395. break;
  4396. default:
  4397. console.log('Error: unknown action "' + action + '"');
  4398. }
  4399. });
  4400. // reposition all items. Show items only when in the visible area
  4401. util.forEach(this.items, function (item) {
  4402. if (item.visible) {
  4403. changed += item.show();
  4404. item.reposition();
  4405. }
  4406. else {
  4407. changed += item.hide();
  4408. }
  4409. });
  4410. return (changed > 0);
  4411. };
  4412. /**
  4413. * Get the foreground container element
  4414. * @return {HTMLElement} foreground
  4415. */
  4416. ItemSet.prototype.getForeground = function getForeground() {
  4417. return this.dom.foreground;
  4418. };
  4419. /**
  4420. * Get the background container element
  4421. * @return {HTMLElement} background
  4422. */
  4423. ItemSet.prototype.getBackground = function getBackground() {
  4424. return this.dom.background;
  4425. };
  4426. /**
  4427. * Get the axis container element
  4428. * @return {HTMLElement} axis
  4429. */
  4430. ItemSet.prototype.getAxis = function getAxis() {
  4431. return this.dom.axis;
  4432. };
  4433. /**
  4434. * Reflow the component
  4435. * @return {Boolean} resized
  4436. */
  4437. ItemSet.prototype.reflow = function reflow () {
  4438. var changed = 0,
  4439. options = this.options,
  4440. marginAxis = options.margin && options.margin.axis || this.defaultOptions.margin.axis,
  4441. marginItem = options.margin && options.margin.item || this.defaultOptions.margin.item,
  4442. update = util.updateProperty,
  4443. asNumber = util.option.asNumber,
  4444. asSize = util.option.asSize,
  4445. frame = this.frame;
  4446. if (frame) {
  4447. this._updateConversion();
  4448. util.forEach(this.items, function (item) {
  4449. changed += item.reflow();
  4450. });
  4451. // TODO: stack.update should be triggered via an event, in stack itself
  4452. // TODO: only update the stack when there are changed items
  4453. this.stack.update();
  4454. var maxHeight = asNumber(options.maxHeight);
  4455. var fixedHeight = (asSize(options.height) != null);
  4456. var height;
  4457. if (fixedHeight) {
  4458. height = frame.offsetHeight;
  4459. }
  4460. else {
  4461. // height is not specified, determine the height from the height and positioned items
  4462. var visibleItems = this.stack.ordered; // TODO: not so nice way to get the filtered items
  4463. if (visibleItems.length) {
  4464. var min = visibleItems[0].top;
  4465. var max = visibleItems[0].top + visibleItems[0].height;
  4466. util.forEach(visibleItems, function (item) {
  4467. min = Math.min(min, item.top);
  4468. max = Math.max(max, (item.top + item.height));
  4469. });
  4470. height = (max - min) + marginAxis + marginItem;
  4471. }
  4472. else {
  4473. height = marginAxis + marginItem;
  4474. }
  4475. }
  4476. if (maxHeight != null) {
  4477. height = Math.min(height, maxHeight);
  4478. }
  4479. changed += update(this, 'height', height);
  4480. // calculate height from items
  4481. changed += update(this, 'top', frame.offsetTop);
  4482. changed += update(this, 'left', frame.offsetLeft);
  4483. changed += update(this, 'width', frame.offsetWidth);
  4484. }
  4485. else {
  4486. changed += 1;
  4487. }
  4488. return (changed > 0);
  4489. };
  4490. /**
  4491. * Hide this component from the DOM
  4492. * @return {Boolean} changed
  4493. */
  4494. ItemSet.prototype.hide = function hide() {
  4495. var changed = false;
  4496. // remove the DOM
  4497. if (this.frame && this.frame.parentNode) {
  4498. this.frame.parentNode.removeChild(this.frame);
  4499. changed = true;
  4500. }
  4501. if (this.dom.axis && this.dom.axis.parentNode) {
  4502. this.dom.axis.parentNode.removeChild(this.dom.axis);
  4503. changed = true;
  4504. }
  4505. return changed;
  4506. };
  4507. /**
  4508. * Set items
  4509. * @param {vis.DataSet | null} items
  4510. */
  4511. ItemSet.prototype.setItems = function setItems(items) {
  4512. var me = this,
  4513. ids,
  4514. oldItemsData = this.itemsData;
  4515. // replace the dataset
  4516. if (!items) {
  4517. this.itemsData = null;
  4518. }
  4519. else if (items instanceof DataSet || items instanceof DataView) {
  4520. this.itemsData = items;
  4521. }
  4522. else {
  4523. throw new TypeError('Data must be an instance of DataSet');
  4524. }
  4525. if (oldItemsData) {
  4526. // unsubscribe from old dataset
  4527. util.forEach(this.listeners, function (callback, event) {
  4528. oldItemsData.unsubscribe(event, callback);
  4529. });
  4530. // remove all drawn items
  4531. ids = oldItemsData.getIds();
  4532. this._onRemove(ids);
  4533. }
  4534. if (this.itemsData) {
  4535. // subscribe to new dataset
  4536. var id = this.id;
  4537. util.forEach(this.listeners, function (callback, event) {
  4538. me.itemsData.subscribe(event, callback, id);
  4539. });
  4540. // draw all new items
  4541. ids = this.itemsData.getIds();
  4542. this._onAdd(ids);
  4543. }
  4544. };
  4545. /**
  4546. * Get the current items items
  4547. * @returns {vis.DataSet | null}
  4548. */
  4549. ItemSet.prototype.getItems = function getItems() {
  4550. return this.itemsData;
  4551. };
  4552. /**
  4553. * Handle updated items
  4554. * @param {Number[]} ids
  4555. * @private
  4556. */
  4557. ItemSet.prototype._onUpdate = function _onUpdate(ids) {
  4558. this._toQueue('update', ids);
  4559. };
  4560. /**
  4561. * Handle changed items
  4562. * @param {Number[]} ids
  4563. * @private
  4564. */
  4565. ItemSet.prototype._onAdd = function _onAdd(ids) {
  4566. this._toQueue('add', ids);
  4567. };
  4568. /**
  4569. * Handle removed items
  4570. * @param {Number[]} ids
  4571. * @private
  4572. */
  4573. ItemSet.prototype._onRemove = function _onRemove(ids) {
  4574. this._toQueue('remove', ids);
  4575. };
  4576. /**
  4577. * Put items in the queue to be added/updated/remove
  4578. * @param {String} action can be 'add', 'update', 'remove'
  4579. * @param {Number[]} ids
  4580. */
  4581. ItemSet.prototype._toQueue = function _toQueue(action, ids) {
  4582. var queue = this.queue;
  4583. ids.forEach(function (id) {
  4584. queue[id] = action;
  4585. });
  4586. if (this.controller) {
  4587. //this.requestReflow();
  4588. this.requestRepaint();
  4589. }
  4590. };
  4591. /**
  4592. * Calculate the factor and offset to convert a position on screen to the
  4593. * corresponding date and vice versa.
  4594. * After the method _updateConversion is executed once, the methods toTime
  4595. * and toScreen can be used.
  4596. * @private
  4597. */
  4598. ItemSet.prototype._updateConversion = function _updateConversion() {
  4599. var range = this.range;
  4600. if (!range) {
  4601. throw new Error('No range configured');
  4602. }
  4603. if (range.conversion) {
  4604. this.conversion = range.conversion(this.width);
  4605. }
  4606. else {
  4607. this.conversion = Range.conversion(range.start, range.end, this.width);
  4608. }
  4609. };
  4610. /**
  4611. * Convert a position on screen (pixels) to a datetime
  4612. * Before this method can be used, the method _updateConversion must be
  4613. * executed once.
  4614. * @param {int} x Position on the screen in pixels
  4615. * @return {Date} time The datetime the corresponds with given position x
  4616. */
  4617. ItemSet.prototype.toTime = function toTime(x) {
  4618. var conversion = this.conversion;
  4619. return new Date(x / conversion.factor + conversion.offset);
  4620. };
  4621. /**
  4622. * Convert a datetime (Date object) into a position on the screen
  4623. * Before this method can be used, the method _updateConversion must be
  4624. * executed once.
  4625. * @param {Date} time A date
  4626. * @return {int} x The position on the screen in pixels which corresponds
  4627. * with the given date.
  4628. */
  4629. ItemSet.prototype.toScreen = function toScreen(time) {
  4630. var conversion = this.conversion;
  4631. return (time.valueOf() - conversion.offset) * conversion.factor;
  4632. };
  4633. /**
  4634. * @constructor Item
  4635. * @param {ItemSet} parent
  4636. * @param {Object} data Object containing (optional) parameters type,
  4637. * start, end, content, group, className.
  4638. * @param {Object} [options] Options to set initial property values
  4639. * @param {Object} [defaultOptions] default options
  4640. * // TODO: describe available options
  4641. */
  4642. function Item (parent, data, options, defaultOptions) {
  4643. this.parent = parent;
  4644. this.data = data;
  4645. this.dom = null;
  4646. this.options = options || {};
  4647. this.defaultOptions = defaultOptions || {};
  4648. this.selected = false;
  4649. this.visible = false;
  4650. this.top = 0;
  4651. this.left = 0;
  4652. this.width = 0;
  4653. this.height = 0;
  4654. }
  4655. /**
  4656. * Select current item
  4657. */
  4658. Item.prototype.select = function select() {
  4659. this.selected = true;
  4660. };
  4661. /**
  4662. * Unselect current item
  4663. */
  4664. Item.prototype.unselect = function unselect() {
  4665. this.selected = false;
  4666. };
  4667. /**
  4668. * Show the Item in the DOM (when not already visible)
  4669. * @return {Boolean} changed
  4670. */
  4671. Item.prototype.show = function show() {
  4672. return false;
  4673. };
  4674. /**
  4675. * Hide the Item from the DOM (when visible)
  4676. * @return {Boolean} changed
  4677. */
  4678. Item.prototype.hide = function hide() {
  4679. return false;
  4680. };
  4681. /**
  4682. * Repaint the item
  4683. * @return {Boolean} changed
  4684. */
  4685. Item.prototype.repaint = function repaint() {
  4686. // should be implemented by the item
  4687. return false;
  4688. };
  4689. /**
  4690. * Reflow the item
  4691. * @return {Boolean} resized
  4692. */
  4693. Item.prototype.reflow = function reflow() {
  4694. // should be implemented by the item
  4695. return false;
  4696. };
  4697. /**
  4698. * @constructor ItemBox
  4699. * @extends Item
  4700. * @param {ItemSet} parent
  4701. * @param {Object} data Object containing parameters start
  4702. * content, className.
  4703. * @param {Object} [options] Options to set initial property values
  4704. * @param {Object} [defaultOptions] default options
  4705. * // TODO: describe available options
  4706. */
  4707. function ItemBox (parent, data, options, defaultOptions) {
  4708. this.props = {
  4709. dot: {
  4710. left: 0,
  4711. top: 0,
  4712. width: 0,
  4713. height: 0
  4714. },
  4715. line: {
  4716. top: 0,
  4717. left: 0,
  4718. width: 0,
  4719. height: 0
  4720. }
  4721. };
  4722. Item.call(this, parent, data, options, defaultOptions);
  4723. }
  4724. ItemBox.prototype = new Item (null, null);
  4725. /**
  4726. * Select the item
  4727. * @override
  4728. */
  4729. ItemBox.prototype.select = function select() {
  4730. this.selected = true;
  4731. // TODO: select and unselect
  4732. };
  4733. /**
  4734. * Unselect the item
  4735. * @override
  4736. */
  4737. ItemBox.prototype.unselect = function unselect() {
  4738. this.selected = false;
  4739. // TODO: select and unselect
  4740. };
  4741. /**
  4742. * Repaint the item
  4743. * @return {Boolean} changed
  4744. */
  4745. ItemBox.prototype.repaint = function repaint() {
  4746. // TODO: make an efficient repaint
  4747. var changed = false;
  4748. var dom = this.dom;
  4749. if (!dom) {
  4750. this._create();
  4751. dom = this.dom;
  4752. changed = true;
  4753. }
  4754. if (dom) {
  4755. if (!this.parent) {
  4756. throw new Error('Cannot repaint item: no parent attached');
  4757. }
  4758. var foreground = this.parent.getForeground();
  4759. if (!foreground) {
  4760. throw new Error('Cannot repaint time axis: ' +
  4761. 'parent has no foreground container element');
  4762. }
  4763. var background = this.parent.getBackground();
  4764. if (!background) {
  4765. throw new Error('Cannot repaint time axis: ' +
  4766. 'parent has no background container element');
  4767. }
  4768. var axis = this.parent.getAxis();
  4769. if (!background) {
  4770. throw new Error('Cannot repaint time axis: ' +
  4771. 'parent has no axis container element');
  4772. }
  4773. if (!dom.box.parentNode) {
  4774. foreground.appendChild(dom.box);
  4775. changed = true;
  4776. }
  4777. if (!dom.line.parentNode) {
  4778. background.appendChild(dom.line);
  4779. changed = true;
  4780. }
  4781. if (!dom.dot.parentNode) {
  4782. axis.appendChild(dom.dot);
  4783. changed = true;
  4784. }
  4785. // update contents
  4786. if (this.data.content != this.content) {
  4787. this.content = this.data.content;
  4788. if (this.content instanceof Element) {
  4789. dom.content.innerHTML = '';
  4790. dom.content.appendChild(this.content);
  4791. }
  4792. else if (this.data.content != undefined) {
  4793. dom.content.innerHTML = this.content;
  4794. }
  4795. else {
  4796. throw new Error('Property "content" missing in item ' + this.data.id);
  4797. }
  4798. changed = true;
  4799. }
  4800. // update class
  4801. var className = (this.data.className? ' ' + this.data.className : '') +
  4802. (this.selected ? ' selected' : '');
  4803. if (this.className != className) {
  4804. this.className = className;
  4805. dom.box.className = 'item box' + className;
  4806. dom.line.className = 'item line' + className;
  4807. dom.dot.className = 'item dot' + className;
  4808. changed = true;
  4809. }
  4810. }
  4811. return changed;
  4812. };
  4813. /**
  4814. * Show the item in the DOM (when not already visible). The items DOM will
  4815. * be created when needed.
  4816. * @return {Boolean} changed
  4817. */
  4818. ItemBox.prototype.show = function show() {
  4819. if (!this.dom || !this.dom.box.parentNode) {
  4820. return this.repaint();
  4821. }
  4822. else {
  4823. return false;
  4824. }
  4825. };
  4826. /**
  4827. * Hide the item from the DOM (when visible)
  4828. * @return {Boolean} changed
  4829. */
  4830. ItemBox.prototype.hide = function hide() {
  4831. var changed = false,
  4832. dom = this.dom;
  4833. if (dom) {
  4834. if (dom.box.parentNode) {
  4835. dom.box.parentNode.removeChild(dom.box);
  4836. changed = true;
  4837. }
  4838. if (dom.line.parentNode) {
  4839. dom.line.parentNode.removeChild(dom.line);
  4840. }
  4841. if (dom.dot.parentNode) {
  4842. dom.dot.parentNode.removeChild(dom.dot);
  4843. }
  4844. }
  4845. return changed;
  4846. };
  4847. /**
  4848. * Reflow the item: calculate its actual size and position from the DOM
  4849. * @return {boolean} resized returns true if the axis is resized
  4850. * @override
  4851. */
  4852. ItemBox.prototype.reflow = function reflow() {
  4853. var changed = 0,
  4854. update,
  4855. dom,
  4856. props,
  4857. options,
  4858. margin,
  4859. start,
  4860. align,
  4861. orientation,
  4862. top,
  4863. left,
  4864. data,
  4865. range;
  4866. if (this.data.start == undefined) {
  4867. throw new Error('Property "start" missing in item ' + this.data.id);
  4868. }
  4869. data = this.data;
  4870. range = this.parent && this.parent.range;
  4871. if (data && range) {
  4872. // TODO: account for the width of the item
  4873. var interval = (range.end - range.start);
  4874. this.visible = (data.start > range.start - interval) && (data.start < range.end + interval);
  4875. }
  4876. else {
  4877. this.visible = false;
  4878. }
  4879. if (this.visible) {
  4880. dom = this.dom;
  4881. if (dom) {
  4882. update = util.updateProperty;
  4883. props = this.props;
  4884. options = this.options;
  4885. start = this.parent.toScreen(this.data.start);
  4886. align = options.align || this.defaultOptions.align;
  4887. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  4888. orientation = options.orientation || this.defaultOptions.orientation;
  4889. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  4890. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  4891. changed += update(props.line, 'width', dom.line.offsetWidth);
  4892. changed += update(props.line, 'height', dom.line.offsetHeight);
  4893. changed += update(props.line, 'top', dom.line.offsetTop);
  4894. changed += update(this, 'width', dom.box.offsetWidth);
  4895. changed += update(this, 'height', dom.box.offsetHeight);
  4896. if (align == 'right') {
  4897. left = start - this.width;
  4898. }
  4899. else if (align == 'left') {
  4900. left = start;
  4901. }
  4902. else {
  4903. // default or 'center'
  4904. left = start - this.width / 2;
  4905. }
  4906. changed += update(this, 'left', left);
  4907. changed += update(props.line, 'left', start - props.line.width / 2);
  4908. changed += update(props.dot, 'left', start - props.dot.width / 2);
  4909. changed += update(props.dot, 'top', -props.dot.height / 2);
  4910. if (orientation == 'top') {
  4911. top = margin;
  4912. changed += update(this, 'top', top);
  4913. }
  4914. else {
  4915. // default or 'bottom'
  4916. var parentHeight = this.parent.height;
  4917. top = parentHeight - this.height - margin;
  4918. changed += update(this, 'top', top);
  4919. }
  4920. }
  4921. else {
  4922. changed += 1;
  4923. }
  4924. }
  4925. return (changed > 0);
  4926. };
  4927. /**
  4928. * Create an items DOM
  4929. * @private
  4930. */
  4931. ItemBox.prototype._create = function _create() {
  4932. var dom = this.dom;
  4933. if (!dom) {
  4934. this.dom = dom = {};
  4935. // create the box
  4936. dom.box = document.createElement('DIV');
  4937. // className is updated in repaint()
  4938. // contents box (inside the background box). used for making margins
  4939. dom.content = document.createElement('DIV');
  4940. dom.content.className = 'content';
  4941. dom.box.appendChild(dom.content);
  4942. // line to axis
  4943. dom.line = document.createElement('DIV');
  4944. dom.line.className = 'line';
  4945. // dot on axis
  4946. dom.dot = document.createElement('DIV');
  4947. dom.dot.className = 'dot';
  4948. }
  4949. };
  4950. /**
  4951. * Reposition the item, recalculate its left, top, and width, using the current
  4952. * range and size of the items itemset
  4953. * @override
  4954. */
  4955. ItemBox.prototype.reposition = function reposition() {
  4956. var dom = this.dom,
  4957. props = this.props,
  4958. orientation = this.options.orientation || this.defaultOptions.orientation;
  4959. if (dom) {
  4960. var box = dom.box,
  4961. line = dom.line,
  4962. dot = dom.dot;
  4963. box.style.left = this.left + 'px';
  4964. box.style.top = this.top + 'px';
  4965. line.style.left = props.line.left + 'px';
  4966. if (orientation == 'top') {
  4967. line.style.top = 0 + 'px';
  4968. line.style.height = this.top + 'px';
  4969. }
  4970. else {
  4971. // orientation 'bottom'
  4972. line.style.top = (this.top + this.height) + 'px';
  4973. line.style.height = Math.max(this.parent.height - this.top - this.height +
  4974. this.props.dot.height / 2, 0) + 'px';
  4975. }
  4976. dot.style.left = props.dot.left + 'px';
  4977. dot.style.top = props.dot.top + 'px';
  4978. }
  4979. };
  4980. /**
  4981. * @constructor ItemPoint
  4982. * @extends Item
  4983. * @param {ItemSet} parent
  4984. * @param {Object} data Object containing parameters start
  4985. * content, className.
  4986. * @param {Object} [options] Options to set initial property values
  4987. * @param {Object} [defaultOptions] default options
  4988. * // TODO: describe available options
  4989. */
  4990. function ItemPoint (parent, data, options, defaultOptions) {
  4991. this.props = {
  4992. dot: {
  4993. top: 0,
  4994. width: 0,
  4995. height: 0
  4996. },
  4997. content: {
  4998. height: 0,
  4999. marginLeft: 0
  5000. }
  5001. };
  5002. Item.call(this, parent, data, options, defaultOptions);
  5003. }
  5004. ItemPoint.prototype = new Item (null, null);
  5005. /**
  5006. * Select the item
  5007. * @override
  5008. */
  5009. ItemPoint.prototype.select = function select() {
  5010. this.selected = true;
  5011. // TODO: select and unselect
  5012. };
  5013. /**
  5014. * Unselect the item
  5015. * @override
  5016. */
  5017. ItemPoint.prototype.unselect = function unselect() {
  5018. this.selected = false;
  5019. // TODO: select and unselect
  5020. };
  5021. /**
  5022. * Repaint the item
  5023. * @return {Boolean} changed
  5024. */
  5025. ItemPoint.prototype.repaint = function repaint() {
  5026. // TODO: make an efficient repaint
  5027. var changed = false;
  5028. var dom = this.dom;
  5029. if (!dom) {
  5030. this._create();
  5031. dom = this.dom;
  5032. changed = true;
  5033. }
  5034. if (dom) {
  5035. if (!this.parent) {
  5036. throw new Error('Cannot repaint item: no parent attached');
  5037. }
  5038. var foreground = this.parent.getForeground();
  5039. if (!foreground) {
  5040. throw new Error('Cannot repaint time axis: ' +
  5041. 'parent has no foreground container element');
  5042. }
  5043. if (!dom.point.parentNode) {
  5044. foreground.appendChild(dom.point);
  5045. foreground.appendChild(dom.point);
  5046. changed = true;
  5047. }
  5048. // update contents
  5049. if (this.data.content != this.content) {
  5050. this.content = this.data.content;
  5051. if (this.content instanceof Element) {
  5052. dom.content.innerHTML = '';
  5053. dom.content.appendChild(this.content);
  5054. }
  5055. else if (this.data.content != undefined) {
  5056. dom.content.innerHTML = this.content;
  5057. }
  5058. else {
  5059. throw new Error('Property "content" missing in item ' + this.data.id);
  5060. }
  5061. changed = true;
  5062. }
  5063. // update class
  5064. var className = (this.data.className? ' ' + this.data.className : '') +
  5065. (this.selected ? ' selected' : '');
  5066. if (this.className != className) {
  5067. this.className = className;
  5068. dom.point.className = 'item point' + className;
  5069. changed = true;
  5070. }
  5071. }
  5072. return changed;
  5073. };
  5074. /**
  5075. * Show the item in the DOM (when not already visible). The items DOM will
  5076. * be created when needed.
  5077. * @return {Boolean} changed
  5078. */
  5079. ItemPoint.prototype.show = function show() {
  5080. if (!this.dom || !this.dom.point.parentNode) {
  5081. return this.repaint();
  5082. }
  5083. else {
  5084. return false;
  5085. }
  5086. };
  5087. /**
  5088. * Hide the item from the DOM (when visible)
  5089. * @return {Boolean} changed
  5090. */
  5091. ItemPoint.prototype.hide = function hide() {
  5092. var changed = false,
  5093. dom = this.dom;
  5094. if (dom) {
  5095. if (dom.point.parentNode) {
  5096. dom.point.parentNode.removeChild(dom.point);
  5097. changed = true;
  5098. }
  5099. }
  5100. return changed;
  5101. };
  5102. /**
  5103. * Reflow the item: calculate its actual size from the DOM
  5104. * @return {boolean} resized returns true if the axis is resized
  5105. * @override
  5106. */
  5107. ItemPoint.prototype.reflow = function reflow() {
  5108. var changed = 0,
  5109. update,
  5110. dom,
  5111. props,
  5112. options,
  5113. margin,
  5114. orientation,
  5115. start,
  5116. top,
  5117. data,
  5118. range;
  5119. if (this.data.start == undefined) {
  5120. throw new Error('Property "start" missing in item ' + this.data.id);
  5121. }
  5122. data = this.data;
  5123. range = this.parent && this.parent.range;
  5124. if (data && range) {
  5125. // TODO: account for the width of the item
  5126. var interval = (range.end - range.start);
  5127. this.visible = (data.start > range.start - interval) && (data.start < range.end);
  5128. }
  5129. else {
  5130. this.visible = false;
  5131. }
  5132. if (this.visible) {
  5133. dom = this.dom;
  5134. if (dom) {
  5135. update = util.updateProperty;
  5136. props = this.props;
  5137. options = this.options;
  5138. orientation = options.orientation || this.defaultOptions.orientation;
  5139. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5140. start = this.parent.toScreen(this.data.start);
  5141. changed += update(this, 'width', dom.point.offsetWidth);
  5142. changed += update(this, 'height', dom.point.offsetHeight);
  5143. changed += update(props.dot, 'width', dom.dot.offsetWidth);
  5144. changed += update(props.dot, 'height', dom.dot.offsetHeight);
  5145. changed += update(props.content, 'height', dom.content.offsetHeight);
  5146. if (orientation == 'top') {
  5147. top = margin;
  5148. }
  5149. else {
  5150. // default or 'bottom'
  5151. var parentHeight = this.parent.height;
  5152. top = Math.max(parentHeight - this.height - margin, 0);
  5153. }
  5154. changed += update(this, 'top', top);
  5155. changed += update(this, 'left', start - props.dot.width / 2);
  5156. changed += update(props.content, 'marginLeft', 1.5 * props.dot.width);
  5157. //changed += update(props.content, 'marginRight', 0.5 * props.dot.width); // TODO
  5158. changed += update(props.dot, 'top', (this.height - props.dot.height) / 2);
  5159. }
  5160. else {
  5161. changed += 1;
  5162. }
  5163. }
  5164. return (changed > 0);
  5165. };
  5166. /**
  5167. * Create an items DOM
  5168. * @private
  5169. */
  5170. ItemPoint.prototype._create = function _create() {
  5171. var dom = this.dom;
  5172. if (!dom) {
  5173. this.dom = dom = {};
  5174. // background box
  5175. dom.point = document.createElement('div');
  5176. // className is updated in repaint()
  5177. // contents box, right from the dot
  5178. dom.content = document.createElement('div');
  5179. dom.content.className = 'content';
  5180. dom.point.appendChild(dom.content);
  5181. // dot at start
  5182. dom.dot = document.createElement('div');
  5183. dom.dot.className = 'dot';
  5184. dom.point.appendChild(dom.dot);
  5185. }
  5186. };
  5187. /**
  5188. * Reposition the item, recalculate its left, top, and width, using the current
  5189. * range and size of the items itemset
  5190. * @override
  5191. */
  5192. ItemPoint.prototype.reposition = function reposition() {
  5193. var dom = this.dom,
  5194. props = this.props;
  5195. if (dom) {
  5196. dom.point.style.top = this.top + 'px';
  5197. dom.point.style.left = this.left + 'px';
  5198. dom.content.style.marginLeft = props.content.marginLeft + 'px';
  5199. //dom.content.style.marginRight = props.content.marginRight + 'px'; // TODO
  5200. dom.dot.style.top = props.dot.top + 'px';
  5201. }
  5202. };
  5203. /**
  5204. * @constructor ItemRange
  5205. * @extends Item
  5206. * @param {ItemSet} parent
  5207. * @param {Object} data Object containing parameters start, end
  5208. * content, className.
  5209. * @param {Object} [options] Options to set initial property values
  5210. * @param {Object} [defaultOptions] default options
  5211. * // TODO: describe available options
  5212. */
  5213. function ItemRange (parent, data, options, defaultOptions) {
  5214. this.props = {
  5215. content: {
  5216. left: 0,
  5217. width: 0
  5218. }
  5219. };
  5220. Item.call(this, parent, data, options, defaultOptions);
  5221. }
  5222. ItemRange.prototype = new Item (null, null);
  5223. /**
  5224. * Select the item
  5225. * @override
  5226. */
  5227. ItemRange.prototype.select = function select() {
  5228. this.selected = true;
  5229. // TODO: select and unselect
  5230. };
  5231. /**
  5232. * Unselect the item
  5233. * @override
  5234. */
  5235. ItemRange.prototype.unselect = function unselect() {
  5236. this.selected = false;
  5237. // TODO: select and unselect
  5238. };
  5239. /**
  5240. * Repaint the item
  5241. * @return {Boolean} changed
  5242. */
  5243. ItemRange.prototype.repaint = function repaint() {
  5244. // TODO: make an efficient repaint
  5245. var changed = false;
  5246. var dom = this.dom;
  5247. if (!dom) {
  5248. this._create();
  5249. dom = this.dom;
  5250. changed = true;
  5251. }
  5252. if (dom) {
  5253. if (!this.parent) {
  5254. throw new Error('Cannot repaint item: no parent attached');
  5255. }
  5256. var foreground = this.parent.getForeground();
  5257. if (!foreground) {
  5258. throw new Error('Cannot repaint time axis: ' +
  5259. 'parent has no foreground container element');
  5260. }
  5261. if (!dom.box.parentNode) {
  5262. foreground.appendChild(dom.box);
  5263. changed = true;
  5264. }
  5265. // update content
  5266. if (this.data.content != this.content) {
  5267. this.content = this.data.content;
  5268. if (this.content instanceof Element) {
  5269. dom.content.innerHTML = '';
  5270. dom.content.appendChild(this.content);
  5271. }
  5272. else if (this.data.content != undefined) {
  5273. dom.content.innerHTML = this.content;
  5274. }
  5275. else {
  5276. throw new Error('Property "content" missing in item ' + this.data.id);
  5277. }
  5278. changed = true;
  5279. }
  5280. // update class
  5281. var className = this.data.className ? ('' + this.data.className) : '';
  5282. if (this.className != className) {
  5283. this.className = className;
  5284. dom.box.className = 'item range' + className;
  5285. changed = true;
  5286. }
  5287. }
  5288. return changed;
  5289. };
  5290. /**
  5291. * Show the item in the DOM (when not already visible). The items DOM will
  5292. * be created when needed.
  5293. * @return {Boolean} changed
  5294. */
  5295. ItemRange.prototype.show = function show() {
  5296. if (!this.dom || !this.dom.box.parentNode) {
  5297. return this.repaint();
  5298. }
  5299. else {
  5300. return false;
  5301. }
  5302. };
  5303. /**
  5304. * Hide the item from the DOM (when visible)
  5305. * @return {Boolean} changed
  5306. */
  5307. ItemRange.prototype.hide = function hide() {
  5308. var changed = false,
  5309. dom = this.dom;
  5310. if (dom) {
  5311. if (dom.box.parentNode) {
  5312. dom.box.parentNode.removeChild(dom.box);
  5313. changed = true;
  5314. }
  5315. }
  5316. return changed;
  5317. };
  5318. /**
  5319. * Reflow the item: calculate its actual size from the DOM
  5320. * @return {boolean} resized returns true if the axis is resized
  5321. * @override
  5322. */
  5323. ItemRange.prototype.reflow = function reflow() {
  5324. var changed = 0,
  5325. dom,
  5326. props,
  5327. options,
  5328. margin,
  5329. padding,
  5330. parent,
  5331. start,
  5332. end,
  5333. data,
  5334. range,
  5335. update,
  5336. box,
  5337. parentWidth,
  5338. contentLeft,
  5339. orientation,
  5340. top;
  5341. if (this.data.start == undefined) {
  5342. throw new Error('Property "start" missing in item ' + this.data.id);
  5343. }
  5344. if (this.data.end == undefined) {
  5345. throw new Error('Property "end" missing in item ' + this.data.id);
  5346. }
  5347. data = this.data;
  5348. range = this.parent && this.parent.range;
  5349. if (data && range) {
  5350. // TODO: account for the width of the item. Take some margin
  5351. this.visible = (data.start < range.end) && (data.end > range.start);
  5352. }
  5353. else {
  5354. this.visible = false;
  5355. }
  5356. if (this.visible) {
  5357. dom = this.dom;
  5358. if (dom) {
  5359. props = this.props;
  5360. options = this.options;
  5361. parent = this.parent;
  5362. start = parent.toScreen(this.data.start);
  5363. end = parent.toScreen(this.data.end);
  5364. update = util.updateProperty;
  5365. box = dom.box;
  5366. parentWidth = parent.width;
  5367. orientation = options.orientation || this.defaultOptions.orientation;
  5368. margin = options.margin && options.margin.axis || this.defaultOptions.margin.axis;
  5369. padding = options.padding || this.defaultOptions.padding;
  5370. changed += update(props.content, 'width', dom.content.offsetWidth);
  5371. changed += update(this, 'height', box.offsetHeight);
  5372. // limit the width of the this, as browsers cannot draw very wide divs
  5373. if (start < -parentWidth) {
  5374. start = -parentWidth;
  5375. }
  5376. if (end > 2 * parentWidth) {
  5377. end = 2 * parentWidth;
  5378. }
  5379. // when range exceeds left of the window, position the contents at the left of the visible area
  5380. if (start < 0) {
  5381. contentLeft = Math.min(-start,
  5382. (end - start - props.content.width - 2 * padding));
  5383. // TODO: remove the need for options.padding. it's terrible.
  5384. }
  5385. else {
  5386. contentLeft = 0;
  5387. }
  5388. changed += update(props.content, 'left', contentLeft);
  5389. if (orientation == 'top') {
  5390. top = margin;
  5391. changed += update(this, 'top', top);
  5392. }
  5393. else {
  5394. // default or 'bottom'
  5395. top = parent.height - this.height - margin;
  5396. changed += update(this, 'top', top);
  5397. }
  5398. changed += update(this, 'left', start);
  5399. changed += update(this, 'width', Math.max(end - start, 1)); // TODO: reckon with border width;
  5400. }
  5401. else {
  5402. changed += 1;
  5403. }
  5404. }
  5405. return (changed > 0);
  5406. };
  5407. /**
  5408. * Create an items DOM
  5409. * @private
  5410. */
  5411. ItemRange.prototype._create = function _create() {
  5412. var dom = this.dom;
  5413. if (!dom) {
  5414. this.dom = dom = {};
  5415. // background box
  5416. dom.box = document.createElement('div');
  5417. // className is updated in repaint()
  5418. // contents box
  5419. dom.content = document.createElement('div');
  5420. dom.content.className = 'content';
  5421. dom.box.appendChild(dom.content);
  5422. }
  5423. };
  5424. /**
  5425. * Reposition the item, recalculate its left, top, and width, using the current
  5426. * range and size of the items itemset
  5427. * @override
  5428. */
  5429. ItemRange.prototype.reposition = function reposition() {
  5430. var dom = this.dom,
  5431. props = this.props;
  5432. if (dom) {
  5433. dom.box.style.top = this.top + 'px';
  5434. dom.box.style.left = this.left + 'px';
  5435. dom.box.style.width = this.width + 'px';
  5436. dom.content.style.left = props.content.left + 'px';
  5437. }
  5438. };
  5439. /**
  5440. * @constructor Group
  5441. * @param {GroupSet} parent
  5442. * @param {Number | String} groupId
  5443. * @param {Object} [options] Options to set initial property values
  5444. * // TODO: describe available options
  5445. * @extends Component
  5446. */
  5447. function Group (parent, groupId, options) {
  5448. this.id = util.randomUUID();
  5449. this.parent = parent;
  5450. this.groupId = groupId;
  5451. this.itemsData = null; // DataSet
  5452. this.itemset = null; // ItemSet
  5453. this.options = options || {};
  5454. this.options.top = 0;
  5455. this.props = {
  5456. label: {
  5457. width: 0,
  5458. height: 0
  5459. }
  5460. };
  5461. this.top = 0;
  5462. this.left = 0;
  5463. this.width = 0;
  5464. this.height = 0;
  5465. }
  5466. Group.prototype = new Component();
  5467. // TODO: comment
  5468. Group.prototype.setOptions = Component.prototype.setOptions;
  5469. /**
  5470. * Get the container element of the panel, which can be used by a child to
  5471. * add its own widgets.
  5472. * @returns {HTMLElement} container
  5473. */
  5474. Group.prototype.getContainer = function () {
  5475. return this.parent.getContainer();
  5476. };
  5477. /**
  5478. * Set item set for the group. The group will create a view on the itemset,
  5479. * filtered by the groups id.
  5480. * @param {DataSet | DataView} items
  5481. */
  5482. Group.prototype.setItems = function setItems(items) {
  5483. if (this.itemset) {
  5484. // remove current item set
  5485. this.itemset.hide();
  5486. this.itemset.setItems();
  5487. this.parent.controller.remove(this.itemset);
  5488. this.itemset = null;
  5489. }
  5490. if (items) {
  5491. var groupId = this.groupId;
  5492. var itemsetOptions = Object.create(this.options);
  5493. this.itemset = new ItemSet(this, null, itemsetOptions);
  5494. this.itemset.setRange(this.parent.range);
  5495. this.view = new DataView(items, {
  5496. filter: function (item) {
  5497. return item.group == groupId;
  5498. }
  5499. });
  5500. this.itemset.setItems(this.view);
  5501. this.parent.controller.add(this.itemset);
  5502. }
  5503. };
  5504. /**
  5505. * Repaint the item
  5506. * @return {Boolean} changed
  5507. */
  5508. Group.prototype.repaint = function repaint() {
  5509. return false;
  5510. };
  5511. /**
  5512. * Reflow the item
  5513. * @return {Boolean} resized
  5514. */
  5515. Group.prototype.reflow = function reflow() {
  5516. var changed = 0,
  5517. update = util.updateProperty;
  5518. changed += update(this, 'top', this.itemset ? this.itemset.top : 0);
  5519. changed += update(this, 'height', this.itemset ? this.itemset.height : 0);
  5520. // TODO: reckon with the height of the group label
  5521. if (this.label) {
  5522. var inner = this.label.firstChild;
  5523. changed += update(this.props.label, 'width', inner.clientWidth);
  5524. changed += update(this.props.label, 'height', inner.clientHeight);
  5525. }
  5526. else {
  5527. changed += update(this.props.label, 'width', 0);
  5528. changed += update(this.props.label, 'height', 0);
  5529. }
  5530. return (changed > 0);
  5531. };
  5532. /**
  5533. * An GroupSet holds a set of groups
  5534. * @param {Component} parent
  5535. * @param {Component[]} [depends] Components on which this components depends
  5536. * (except for the parent)
  5537. * @param {Object} [options] See GroupSet.setOptions for the available
  5538. * options.
  5539. * @constructor GroupSet
  5540. * @extends Panel
  5541. */
  5542. function GroupSet(parent, depends, options) {
  5543. this.id = util.randomUUID();
  5544. this.parent = parent;
  5545. this.depends = depends;
  5546. this.options = options || {};
  5547. this.range = null; // Range or Object {start: number, end: number}
  5548. this.itemsData = null; // DataSet with items
  5549. this.groupsData = null; // DataSet with groups
  5550. this.groups = {}; // map with groups
  5551. this.dom = {};
  5552. this.props = {
  5553. labels: {
  5554. width: 0
  5555. }
  5556. };
  5557. // TODO: implement right orientation of the labels
  5558. // changes in groups are queued key/value map containing id/action
  5559. this.queue = {};
  5560. var me = this;
  5561. this.listeners = {
  5562. 'add': function (event, params) {
  5563. me._onAdd(params.items);
  5564. },
  5565. 'update': function (event, params) {
  5566. me._onUpdate(params.items);
  5567. },
  5568. 'remove': function (event, params) {
  5569. me._onRemove(params.items);
  5570. }
  5571. };
  5572. }
  5573. GroupSet.prototype = new Panel();
  5574. /**
  5575. * Set options for the GroupSet. Existing options will be extended/overwritten.
  5576. * @param {Object} [options] The following options are available:
  5577. * {String | function} groupsOrder
  5578. * TODO: describe options
  5579. */
  5580. GroupSet.prototype.setOptions = Component.prototype.setOptions;
  5581. GroupSet.prototype.setRange = function (range) {
  5582. // TODO: implement setRange
  5583. };
  5584. /**
  5585. * Set items
  5586. * @param {vis.DataSet | null} items
  5587. */
  5588. GroupSet.prototype.setItems = function setItems(items) {
  5589. this.itemsData = items;
  5590. for (var id in this.groups) {
  5591. if (this.groups.hasOwnProperty(id)) {
  5592. var group = this.groups[id];
  5593. group.setItems(items);
  5594. }
  5595. }
  5596. };
  5597. /**
  5598. * Get items
  5599. * @return {vis.DataSet | null} items
  5600. */
  5601. GroupSet.prototype.getItems = function getItems() {
  5602. return this.itemsData;
  5603. };
  5604. /**
  5605. * Set range (start and end).
  5606. * @param {Range | Object} range A Range or an object containing start and end.
  5607. */
  5608. GroupSet.prototype.setRange = function setRange(range) {
  5609. this.range = range;
  5610. };
  5611. /**
  5612. * Set groups
  5613. * @param {vis.DataSet} groups
  5614. */
  5615. GroupSet.prototype.setGroups = function setGroups(groups) {
  5616. var me = this,
  5617. ids;
  5618. // unsubscribe from current dataset
  5619. if (this.groupsData) {
  5620. util.forEach(this.listeners, function (callback, event) {
  5621. me.groupsData.unsubscribe(event, callback);
  5622. });
  5623. // remove all drawn groups
  5624. ids = this.groupsData.getIds();
  5625. this._onRemove(ids);
  5626. }
  5627. // replace the dataset
  5628. if (!groups) {
  5629. this.groupsData = null;
  5630. }
  5631. else if (groups instanceof DataSet) {
  5632. this.groupsData = groups;
  5633. }
  5634. else {
  5635. this.groupsData = new DataSet({
  5636. convert: {
  5637. start: 'Date',
  5638. end: 'Date'
  5639. }
  5640. });
  5641. this.groupsData.add(groups);
  5642. }
  5643. if (this.groupsData) {
  5644. // subscribe to new dataset
  5645. var id = this.id;
  5646. util.forEach(this.listeners, function (callback, event) {
  5647. me.groupsData.subscribe(event, callback, id);
  5648. });
  5649. // draw all new groups
  5650. ids = this.groupsData.getIds();
  5651. this._onAdd(ids);
  5652. }
  5653. };
  5654. /**
  5655. * Get groups
  5656. * @return {vis.DataSet | null} groups
  5657. */
  5658. GroupSet.prototype.getGroups = function getGroups() {
  5659. return this.groupsData;
  5660. };
  5661. /**
  5662. * Repaint the component
  5663. * @return {Boolean} changed
  5664. */
  5665. GroupSet.prototype.repaint = function repaint() {
  5666. var changed = 0,
  5667. i, id, group, label,
  5668. update = util.updateProperty,
  5669. asSize = util.option.asSize,
  5670. asElement = util.option.asElement,
  5671. options = this.options,
  5672. frame = this.dom.frame,
  5673. labels = this.dom.labels;
  5674. // create frame
  5675. if (!this.parent) {
  5676. throw new Error('Cannot repaint groupset: no parent attached');
  5677. }
  5678. var parentContainer = this.parent.getContainer();
  5679. if (!parentContainer) {
  5680. throw new Error('Cannot repaint groupset: parent has no container element');
  5681. }
  5682. if (!frame) {
  5683. frame = document.createElement('div');
  5684. frame.className = 'groupset';
  5685. this.dom.frame = frame;
  5686. var className = options.className;
  5687. if (className) {
  5688. util.addClassName(frame, util.option.asString(className));
  5689. }
  5690. changed += 1;
  5691. }
  5692. if (!frame.parentNode) {
  5693. parentContainer.appendChild(frame);
  5694. changed += 1;
  5695. }
  5696. // create labels
  5697. var labelContainer = asElement(options.labelContainer);
  5698. if (!labelContainer) {
  5699. throw new Error('Cannot repaint groupset: option "labelContainer" not defined');
  5700. }
  5701. if (!labels) {
  5702. labels = document.createElement('div');
  5703. labels.className = 'labels';
  5704. //frame.appendChild(labels);
  5705. this.dom.labels = labels;
  5706. }
  5707. if (!labels.parentNode || labels.parentNode != labelContainer) {
  5708. if (labels.parentNode) {
  5709. labels.parentNode.removeChild(labels.parentNode);
  5710. }
  5711. labelContainer.appendChild(labels);
  5712. }
  5713. // reposition frame
  5714. changed += update(frame.style, 'height', asSize(options.height, this.height + 'px'));
  5715. changed += update(frame.style, 'top', asSize(options.top, '0px'));
  5716. changed += update(frame.style, 'left', asSize(options.left, '0px'));
  5717. changed += update(frame.style, 'width', asSize(options.width, '100%'));
  5718. // reposition labels
  5719. changed += update(labels.style, 'top', asSize(options.top, '0px'));
  5720. var me = this,
  5721. queue = this.queue,
  5722. groups = this.groups,
  5723. groupsData = this.groupsData;
  5724. // show/hide added/changed/removed groups
  5725. var ids = Object.keys(queue);
  5726. if (ids.length) {
  5727. ids.forEach(function (id) {
  5728. var action = queue[id];
  5729. var group = groups[id];
  5730. //noinspection FallthroughInSwitchStatementJS
  5731. switch (action) {
  5732. case 'add':
  5733. case 'update':
  5734. if (!group) {
  5735. var groupOptions = Object.create(me.options);
  5736. group = new Group(me, id, groupOptions);
  5737. group.setItems(me.itemsData); // attach items data
  5738. groups[id] = group;
  5739. me.controller.add(group);
  5740. }
  5741. // TODO: update group data
  5742. group.data = groupsData.get(id);
  5743. delete queue[id];
  5744. break;
  5745. case 'remove':
  5746. if (group) {
  5747. group.setItems(); // detach items data
  5748. delete groups[id];
  5749. me.controller.remove(group);
  5750. }
  5751. // update lists
  5752. delete queue[id];
  5753. break;
  5754. default:
  5755. console.log('Error: unknown action "' + action + '"');
  5756. }
  5757. });
  5758. // the groupset depends on each of the groups
  5759. //this.depends = this.groups; // TODO: gives a circular reference through the parent
  5760. // TODO: apply dependencies of the groupset
  5761. // update the top positions of the groups in the correct order
  5762. var orderedGroups = this.groupsData.getIds({
  5763. order: this.options.groupsOrder
  5764. });
  5765. for (i = 0; i < orderedGroups.length; i++) {
  5766. (function (group, prevGroup) {
  5767. var top = 0;
  5768. if (prevGroup) {
  5769. top = function () {
  5770. // TODO: top must reckon with options.maxHeight
  5771. return prevGroup.top + prevGroup.height;
  5772. }
  5773. }
  5774. group.setOptions({
  5775. top: top
  5776. });
  5777. })(groups[orderedGroups[i]], groups[orderedGroups[i - 1]]);
  5778. }
  5779. // (re)create the labels
  5780. while (labels.firstChild) {
  5781. labels.removeChild(labels.firstChild);
  5782. }
  5783. for (i = 0; i < orderedGroups.length; i++) {
  5784. id = orderedGroups[i];
  5785. label = this._createLabel(id);
  5786. labels.appendChild(label);
  5787. }
  5788. changed++;
  5789. }
  5790. // reposition the labels
  5791. // TODO: labels are not displayed correctly when orientation=='top'
  5792. // TODO: width of labelPanel is not immediately updated on a change in groups
  5793. for (id in groups) {
  5794. if (groups.hasOwnProperty(id)) {
  5795. group = groups[id];
  5796. label = group.label;
  5797. if (label) {
  5798. label.style.top = group.top + 'px';
  5799. label.style.height = group.height + 'px';
  5800. }
  5801. }
  5802. }
  5803. return (changed > 0);
  5804. };
  5805. /**
  5806. * Create a label for group with given id
  5807. * @param {Number} id
  5808. * @return {Element} label
  5809. * @private
  5810. */
  5811. GroupSet.prototype._createLabel = function(id) {
  5812. var group = this.groups[id];
  5813. var label = document.createElement('div');
  5814. label.className = 'label';
  5815. var inner = document.createElement('div');
  5816. inner.className = 'inner';
  5817. label.appendChild(inner);
  5818. var content = group.data && group.data.content;
  5819. if (content instanceof Element) {
  5820. inner.appendChild(content);
  5821. }
  5822. else if (content != undefined) {
  5823. inner.innerHTML = content;
  5824. }
  5825. var className = group.data && group.data.className;
  5826. if (className) {
  5827. util.addClassName(label, className);
  5828. }
  5829. group.label = label; // TODO: not so nice, parking labels in the group this way!!!
  5830. return label;
  5831. };
  5832. /**
  5833. * Get container element
  5834. * @return {HTMLElement} container
  5835. */
  5836. GroupSet.prototype.getContainer = function getContainer() {
  5837. return this.dom.frame;
  5838. };
  5839. /**
  5840. * Get the width of the group labels
  5841. * @return {Number} width
  5842. */
  5843. GroupSet.prototype.getLabelsWidth = function getContainer() {
  5844. return this.props.labels.width;
  5845. };
  5846. /**
  5847. * Reflow the component
  5848. * @return {Boolean} resized
  5849. */
  5850. GroupSet.prototype.reflow = function reflow() {
  5851. var changed = 0,
  5852. id, group,
  5853. options = this.options,
  5854. update = util.updateProperty,
  5855. asNumber = util.option.asNumber,
  5856. asSize = util.option.asSize,
  5857. frame = this.dom.frame;
  5858. if (frame) {
  5859. var maxHeight = asNumber(options.maxHeight);
  5860. var fixedHeight = (asSize(options.height) != null);
  5861. var height;
  5862. if (fixedHeight) {
  5863. height = frame.offsetHeight;
  5864. }
  5865. else {
  5866. // height is not specified, calculate the sum of the height of all groups
  5867. height = 0;
  5868. for (id in this.groups) {
  5869. if (this.groups.hasOwnProperty(id)) {
  5870. group = this.groups[id];
  5871. height += group.height;
  5872. }
  5873. }
  5874. }
  5875. if (maxHeight != null) {
  5876. height = Math.min(height, maxHeight);
  5877. }
  5878. changed += update(this, 'height', height);
  5879. changed += update(this, 'top', frame.offsetTop);
  5880. changed += update(this, 'left', frame.offsetLeft);
  5881. changed += update(this, 'width', frame.offsetWidth);
  5882. }
  5883. // calculate the maximum width of the labels
  5884. var width = 0;
  5885. for (id in this.groups) {
  5886. if (this.groups.hasOwnProperty(id)) {
  5887. group = this.groups[id];
  5888. var labelWidth = group.props && group.props.label && group.props.label.width || 0;
  5889. width = Math.max(width, labelWidth);
  5890. }
  5891. }
  5892. changed += update(this.props.labels, 'width', width);
  5893. return (changed > 0);
  5894. };
  5895. /**
  5896. * Hide the component from the DOM
  5897. * @return {Boolean} changed
  5898. */
  5899. GroupSet.prototype.hide = function hide() {
  5900. if (this.dom.frame && this.dom.frame.parentNode) {
  5901. this.dom.frame.parentNode.removeChild(this.dom.frame);
  5902. return true;
  5903. }
  5904. else {
  5905. return false;
  5906. }
  5907. };
  5908. /**
  5909. * Show the component in the DOM (when not already visible).
  5910. * A repaint will be executed when the component is not visible
  5911. * @return {Boolean} changed
  5912. */
  5913. GroupSet.prototype.show = function show() {
  5914. if (!this.dom.frame || !this.dom.frame.parentNode) {
  5915. return this.repaint();
  5916. }
  5917. else {
  5918. return false;
  5919. }
  5920. };
  5921. /**
  5922. * Handle updated groups
  5923. * @param {Number[]} ids
  5924. * @private
  5925. */
  5926. GroupSet.prototype._onUpdate = function _onUpdate(ids) {
  5927. this._toQueue(ids, 'update');
  5928. };
  5929. /**
  5930. * Handle changed groups
  5931. * @param {Number[]} ids
  5932. * @private
  5933. */
  5934. GroupSet.prototype._onAdd = function _onAdd(ids) {
  5935. this._toQueue(ids, 'add');
  5936. };
  5937. /**
  5938. * Handle removed groups
  5939. * @param {Number[]} ids
  5940. * @private
  5941. */
  5942. GroupSet.prototype._onRemove = function _onRemove(ids) {
  5943. this._toQueue(ids, 'remove');
  5944. };
  5945. /**
  5946. * Put groups in the queue to be added/updated/remove
  5947. * @param {Number[]} ids
  5948. * @param {String} action can be 'add', 'update', 'remove'
  5949. */
  5950. GroupSet.prototype._toQueue = function _toQueue(ids, action) {
  5951. var queue = this.queue;
  5952. ids.forEach(function (id) {
  5953. queue[id] = action;
  5954. });
  5955. if (this.controller) {
  5956. //this.requestReflow();
  5957. this.requestRepaint();
  5958. }
  5959. };
  5960. /**
  5961. * Create a timeline visualization
  5962. * @param {HTMLElement} container
  5963. * @param {vis.DataSet | Array | DataTable} [items]
  5964. * @param {Object} [options] See Timeline.setOptions for the available options.
  5965. * @constructor
  5966. */
  5967. function Timeline (container, items, options) {
  5968. var me = this;
  5969. this.options = util.extend({
  5970. orientation: 'bottom',
  5971. min: null,
  5972. max: null,
  5973. zoomMin: 10, // milliseconds
  5974. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  5975. // moveable: true, // TODO: option moveable
  5976. // zoomable: true, // TODO: option zoomable
  5977. showMinorLabels: true,
  5978. showMajorLabels: true,
  5979. autoResize: false
  5980. }, options);
  5981. // controller
  5982. this.controller = new Controller();
  5983. // root panel
  5984. if (!container) {
  5985. throw new Error('No container element provided');
  5986. }
  5987. var rootOptions = Object.create(this.options);
  5988. rootOptions.height = function () {
  5989. if (me.options.height) {
  5990. // fixed height
  5991. return me.options.height;
  5992. }
  5993. else {
  5994. // auto height
  5995. return me.timeaxis.height + me.content.height;
  5996. }
  5997. };
  5998. this.rootPanel = new RootPanel(container, rootOptions);
  5999. this.controller.add(this.rootPanel);
  6000. // item panel
  6001. var itemOptions = Object.create(this.options);
  6002. itemOptions.left = function () {
  6003. return me.labelPanel.width;
  6004. };
  6005. itemOptions.width = function () {
  6006. return me.rootPanel.width - me.labelPanel.width;
  6007. };
  6008. itemOptions.top = null;
  6009. itemOptions.height = null;
  6010. this.itemPanel = new Panel(this.rootPanel, [], itemOptions);
  6011. this.controller.add(this.itemPanel);
  6012. // label panel
  6013. var labelOptions = Object.create(this.options);
  6014. labelOptions.top = null;
  6015. labelOptions.left = null;
  6016. labelOptions.height = null;
  6017. labelOptions.width = function () {
  6018. if (me.content && typeof me.content.getLabelsWidth === 'function') {
  6019. return me.content.getLabelsWidth();
  6020. }
  6021. else {
  6022. return 0;
  6023. }
  6024. };
  6025. this.labelPanel = new Panel(this.rootPanel, [], labelOptions);
  6026. this.controller.add(this.labelPanel);
  6027. // range
  6028. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  6029. this.range = new Range({
  6030. start: now.clone().add('days', -3).valueOf(),
  6031. end: now.clone().add('days', 4).valueOf()
  6032. });
  6033. // TODO: reckon with options moveable and zoomable
  6034. this.range.subscribe(this.rootPanel, 'move', 'horizontal');
  6035. this.range.subscribe(this.rootPanel, 'zoom', 'horizontal');
  6036. this.range.on('rangechange', function () {
  6037. var force = true;
  6038. me.controller.requestReflow(force);
  6039. });
  6040. this.range.on('rangechanged', function () {
  6041. var force = true;
  6042. me.controller.requestReflow(force);
  6043. });
  6044. // TODO: put the listeners in setOptions, be able to dynamically change with options moveable and zoomable
  6045. // time axis
  6046. var timeaxisOptions = Object.create(rootOptions);
  6047. timeaxisOptions.range = this.range;
  6048. timeaxisOptions.left = null;
  6049. timeaxisOptions.top = null;
  6050. timeaxisOptions.width = '100%';
  6051. timeaxisOptions.height = null;
  6052. this.timeaxis = new TimeAxis(this.itemPanel, [], timeaxisOptions);
  6053. this.timeaxis.setRange(this.range);
  6054. this.controller.add(this.timeaxis);
  6055. // create itemset or groupset
  6056. this.setGroups(null);
  6057. this.itemsData = null; // DataSet
  6058. this.groupsData = null; // DataSet
  6059. // set data
  6060. if (items) {
  6061. this.setItems(items);
  6062. }
  6063. }
  6064. /**
  6065. * Set options
  6066. * @param {Object} options TODO: describe the available options
  6067. */
  6068. Timeline.prototype.setOptions = function (options) {
  6069. if (options) {
  6070. util.extend(this.options, options);
  6071. }
  6072. this.controller.reflow();
  6073. this.controller.repaint();
  6074. };
  6075. /**
  6076. * Set items
  6077. * @param {vis.DataSet | Array | DataTable | null} items
  6078. */
  6079. Timeline.prototype.setItems = function(items) {
  6080. var initialLoad = (this.itemsData == null);
  6081. // convert to type DataSet when needed
  6082. var newItemSet;
  6083. if (!items) {
  6084. newItemSet = null;
  6085. }
  6086. else if (items instanceof DataSet) {
  6087. newItemSet = items;
  6088. }
  6089. if (!(items instanceof DataSet)) {
  6090. newItemSet = new DataSet({
  6091. convert: {
  6092. start: 'Date',
  6093. end: 'Date'
  6094. }
  6095. });
  6096. newItemSet.add(items);
  6097. }
  6098. // set items
  6099. this.itemsData = newItemSet;
  6100. this.content.setItems(newItemSet);
  6101. if (initialLoad && (this.options.start == undefined || this.options.end == undefined)) {
  6102. // apply the data range as range
  6103. var dataRange = this.getItemRange();
  6104. // add 5% on both sides
  6105. var min = dataRange.min;
  6106. var max = dataRange.max;
  6107. if (min != null && max != null) {
  6108. var interval = (max.valueOf() - min.valueOf());
  6109. min = new Date(min.valueOf() - interval * 0.05);
  6110. max = new Date(max.valueOf() + interval * 0.05);
  6111. }
  6112. // override specified start and/or end date
  6113. if (this.options.start != undefined) {
  6114. min = new Date(this.options.start.valueOf());
  6115. }
  6116. if (this.options.end != undefined) {
  6117. max = new Date(this.options.end.valueOf());
  6118. }
  6119. // apply range if there is a min or max available
  6120. if (min != null || max != null) {
  6121. this.range.setRange(min, max);
  6122. }
  6123. }
  6124. };
  6125. /**
  6126. * Set groups
  6127. * @param {vis.DataSet | Array | DataTable} groups
  6128. */
  6129. Timeline.prototype.setGroups = function(groups) {
  6130. var me = this;
  6131. this.groupsData = groups;
  6132. // switch content type between ItemSet or GroupSet when needed
  6133. var type = this.groupsData ? GroupSet : ItemSet;
  6134. if (!(this.content instanceof type)) {
  6135. // remove old content set
  6136. if (this.content) {
  6137. this.content.hide();
  6138. if (this.content.setItems) {
  6139. this.content.setItems(); // disconnect from items
  6140. }
  6141. if (this.content.setGroups) {
  6142. this.content.setGroups(); // disconnect from groups
  6143. }
  6144. this.controller.remove(this.content);
  6145. }
  6146. // create new content set
  6147. var options = Object.create(this.options);
  6148. util.extend(options, {
  6149. top: function () {
  6150. if (me.options.orientation == 'top') {
  6151. return me.timeaxis.height;
  6152. }
  6153. else {
  6154. return me.itemPanel.height - me.timeaxis.height - me.content.height;
  6155. }
  6156. },
  6157. left: null,
  6158. width: '100%',
  6159. height: function () {
  6160. if (me.options.height) {
  6161. return me.itemPanel.height - me.timeaxis.height;
  6162. }
  6163. else {
  6164. return null;
  6165. }
  6166. },
  6167. maxHeight: function () {
  6168. if (me.options.maxHeight) {
  6169. if (!util.isNumber(me.options.maxHeight)) {
  6170. throw new TypeError('Number expected for property maxHeight');
  6171. }
  6172. return me.options.maxHeight - me.timeaxis.height;
  6173. }
  6174. else {
  6175. return null;
  6176. }
  6177. },
  6178. labelContainer: function () {
  6179. return me.labelPanel.getContainer();
  6180. }
  6181. });
  6182. this.content = new type(this.itemPanel, [this.timeaxis], options);
  6183. if (this.content.setRange) {
  6184. this.content.setRange(this.range);
  6185. }
  6186. if (this.content.setItems) {
  6187. this.content.setItems(this.itemsData);
  6188. }
  6189. if (this.content.setGroups) {
  6190. this.content.setGroups(this.groupsData);
  6191. }
  6192. this.controller.add(this.content);
  6193. }
  6194. };
  6195. /**
  6196. * Get the data range of the item set.
  6197. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  6198. * When no minimum is found, min==null
  6199. * When no maximum is found, max==null
  6200. */
  6201. Timeline.prototype.getItemRange = function getItemRange() {
  6202. // calculate min from start filed
  6203. var itemsData = this.itemsData,
  6204. min = null,
  6205. max = null;
  6206. if (itemsData) {
  6207. // calculate the minimum value of the field 'start'
  6208. var minItem = itemsData.min('start');
  6209. min = minItem ? minItem.start.valueOf() : null;
  6210. // calculate maximum value of fields 'start' and 'end'
  6211. var maxStartItem = itemsData.max('start');
  6212. if (maxStartItem) {
  6213. max = maxStartItem.start.valueOf();
  6214. }
  6215. var maxEndItem = itemsData.max('end');
  6216. if (maxEndItem) {
  6217. if (max == null) {
  6218. max = maxEndItem.end.valueOf();
  6219. }
  6220. else {
  6221. max = Math.max(max, maxEndItem.end.valueOf());
  6222. }
  6223. }
  6224. }
  6225. return {
  6226. min: (min != null) ? new Date(min) : null,
  6227. max: (max != null) ? new Date(max) : null
  6228. };
  6229. };
  6230. (function(exports) {
  6231. /**
  6232. * Parse a text source containing data in DOT language into a JSON object.
  6233. * The object contains two lists: one with nodes and one with edges.
  6234. *
  6235. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  6236. *
  6237. * @param {String} data Text containing a graph in DOT-notation
  6238. * @return {Object} graph An object containing two parameters:
  6239. * {Object[]} nodes
  6240. * {Object[]} edges
  6241. */
  6242. function parseDOT (data) {
  6243. dot = data;
  6244. return parseGraph();
  6245. }
  6246. // token types enumeration
  6247. var TOKENTYPE = {
  6248. NULL : 0,
  6249. DELIMITER : 1,
  6250. IDENTIFIER: 2,
  6251. UNKNOWN : 3
  6252. };
  6253. // map with all delimiters
  6254. var DELIMITERS = {
  6255. '{': true,
  6256. '}': true,
  6257. '[': true,
  6258. ']': true,
  6259. ';': true,
  6260. '=': true,
  6261. ',': true,
  6262. '->': true,
  6263. '--': true
  6264. };
  6265. var dot = ''; // current dot file
  6266. var index = 0; // current index in dot file
  6267. var c = ''; // current token character in expr
  6268. var token = ''; // current token
  6269. var tokenType = TOKENTYPE.NULL; // type of the token
  6270. /**
  6271. * Get the first character from the dot file.
  6272. * The character is stored into the char c. If the end of the dot file is
  6273. * reached, the function puts an empty string in c.
  6274. */
  6275. function first() {
  6276. index = 0;
  6277. c = dot.charAt(0);
  6278. }
  6279. /**
  6280. * Get the next character from the dot file.
  6281. * The character is stored into the char c. If the end of the dot file is
  6282. * reached, the function puts an empty string in c.
  6283. */
  6284. function next() {
  6285. index++;
  6286. c = dot.charAt(index);
  6287. }
  6288. /**
  6289. * Preview the next character from the dot file.
  6290. * @return {String} cNext
  6291. */
  6292. function nextPreview() {
  6293. return dot.charAt(index + 1);
  6294. }
  6295. /**
  6296. * Test whether given character is alphabetic or numeric
  6297. * @param {String} c
  6298. * @return {Boolean} isAlphaNumeric
  6299. */
  6300. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  6301. function isAlphaNumeric(c) {
  6302. return regexAlphaNumeric.test(c);
  6303. }
  6304. /**
  6305. * Merge all properties of object b into object b
  6306. * @param {Object} a
  6307. * @param {Object} b
  6308. * @return {Object} a
  6309. */
  6310. function merge (a, b) {
  6311. if (!a) {
  6312. a = {};
  6313. }
  6314. if (b) {
  6315. for (var name in b) {
  6316. if (b.hasOwnProperty(name)) {
  6317. a[name] = b[name];
  6318. }
  6319. }
  6320. }
  6321. return a;
  6322. }
  6323. /**
  6324. * Set a value in an object, where the provided parameter name can be a
  6325. * path with nested parameters. For example:
  6326. *
  6327. * var obj = {a: 2};
  6328. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  6329. *
  6330. * @param {Object} obj
  6331. * @param {String} path A parameter name or dot-separated parameter path,
  6332. * like "color.highlight.border".
  6333. * @param {*} value
  6334. */
  6335. function setValue(obj, path, value) {
  6336. var keys = path.split('.');
  6337. var o = obj;
  6338. while (keys.length) {
  6339. var key = keys.shift();
  6340. if (keys.length) {
  6341. // this isn't the end point
  6342. if (!o[key]) {
  6343. o[key] = {};
  6344. }
  6345. o = o[key];
  6346. }
  6347. else {
  6348. // this is the end point
  6349. o[key] = value;
  6350. }
  6351. }
  6352. }
  6353. /**
  6354. * Add a node to a graph object. If there is already a node with
  6355. * the same id, their attributes will be merged.
  6356. * @param {Object} graph
  6357. * @param {Object} node
  6358. */
  6359. function addNode(graph, node) {
  6360. var i, len;
  6361. var current = null;
  6362. // find root graph (in case of subgraph)
  6363. var graphs = [graph]; // list with all graphs from current graph to root graph
  6364. var root = graph;
  6365. while (root.parent) {
  6366. graphs.push(root.parent);
  6367. root = root.parent;
  6368. }
  6369. // find existing node (at root level) by its id
  6370. if (root.nodes) {
  6371. for (i = 0, len = root.nodes.length; i < len; i++) {
  6372. if (node.id === root.nodes[i].id) {
  6373. current = root.nodes[i];
  6374. break;
  6375. }
  6376. }
  6377. }
  6378. if (!current) {
  6379. // this is a new node
  6380. current = {
  6381. id: node.id
  6382. };
  6383. if (graph.node) {
  6384. // clone default attributes
  6385. current.attr = merge(current.attr, graph.node);
  6386. }
  6387. }
  6388. // add node to this (sub)graph and all its parent graphs
  6389. for (i = graphs.length - 1; i >= 0; i--) {
  6390. var g = graphs[i];
  6391. if (!g.nodes) {
  6392. g.nodes = [];
  6393. }
  6394. if (g.nodes.indexOf(current) == -1) {
  6395. g.nodes.push(current);
  6396. }
  6397. }
  6398. // merge attributes
  6399. if (node.attr) {
  6400. current.attr = merge(current.attr, node.attr);
  6401. }
  6402. }
  6403. /**
  6404. * Add an edge to a graph object
  6405. * @param {Object} graph
  6406. * @param {Object} edge
  6407. */
  6408. function addEdge(graph, edge) {
  6409. if (!graph.edges) {
  6410. graph.edges = [];
  6411. }
  6412. graph.edges.push(edge);
  6413. if (graph.edge) {
  6414. var attr = merge({}, graph.edge); // clone default attributes
  6415. edge.attr = merge(attr, edge.attr); // merge attributes
  6416. }
  6417. }
  6418. /**
  6419. * Create an edge to a graph object
  6420. * @param {Object} graph
  6421. * @param {String | Number | Object} from
  6422. * @param {String | Number | Object} to
  6423. * @param {String} type
  6424. * @param {Object | null} attr
  6425. * @return {Object} edge
  6426. */
  6427. function createEdge(graph, from, to, type, attr) {
  6428. var edge = {
  6429. from: from,
  6430. to: to,
  6431. type: type
  6432. };
  6433. if (graph.edge) {
  6434. edge.attr = merge({}, graph.edge); // clone default attributes
  6435. }
  6436. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  6437. return edge;
  6438. }
  6439. /**
  6440. * Get next token in the current dot file.
  6441. * The token and token type are available as token and tokenType
  6442. */
  6443. function getToken() {
  6444. tokenType = TOKENTYPE.NULL;
  6445. token = '';
  6446. // skip over whitespaces
  6447. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  6448. next();
  6449. }
  6450. do {
  6451. var isComment = false;
  6452. // skip comment
  6453. if (c == '#') {
  6454. // find the previous non-space character
  6455. var i = index - 1;
  6456. while (dot.charAt(i) == ' ' || dot.charAt(i) == '\t') {
  6457. i--;
  6458. }
  6459. if (dot.charAt(i) == '\n' || dot.charAt(i) == '') {
  6460. // the # is at the start of a line, this is indeed a line comment
  6461. while (c != '' && c != '\n') {
  6462. next();
  6463. }
  6464. isComment = true;
  6465. }
  6466. }
  6467. if (c == '/' && nextPreview() == '/') {
  6468. // skip line comment
  6469. while (c != '' && c != '\n') {
  6470. next();
  6471. }
  6472. isComment = true;
  6473. }
  6474. if (c == '/' && nextPreview() == '*') {
  6475. // skip block comment
  6476. while (c != '') {
  6477. if (c == '*' && nextPreview() == '/') {
  6478. // end of block comment found. skip these last two characters
  6479. next();
  6480. next();
  6481. break;
  6482. }
  6483. else {
  6484. next();
  6485. }
  6486. }
  6487. isComment = true;
  6488. }
  6489. // skip over whitespaces
  6490. while (c == ' ' || c == '\t' || c == '\n' || c == '\r') { // space, tab, enter
  6491. next();
  6492. }
  6493. }
  6494. while (isComment);
  6495. // check for end of dot file
  6496. if (c == '') {
  6497. // token is still empty
  6498. tokenType = TOKENTYPE.DELIMITER;
  6499. return;
  6500. }
  6501. // check for delimiters consisting of 2 characters
  6502. var c2 = c + nextPreview();
  6503. if (DELIMITERS[c2]) {
  6504. tokenType = TOKENTYPE.DELIMITER;
  6505. token = c2;
  6506. next();
  6507. next();
  6508. return;
  6509. }
  6510. // check for delimiters consisting of 1 character
  6511. if (DELIMITERS[c]) {
  6512. tokenType = TOKENTYPE.DELIMITER;
  6513. token = c;
  6514. next();
  6515. return;
  6516. }
  6517. // check for an identifier (number or string)
  6518. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  6519. if (isAlphaNumeric(c) || c == '-') {
  6520. token += c;
  6521. next();
  6522. while (isAlphaNumeric(c)) {
  6523. token += c;
  6524. next();
  6525. }
  6526. if (token == 'false') {
  6527. token = false; // convert to boolean
  6528. }
  6529. else if (token == 'true') {
  6530. token = true; // convert to boolean
  6531. }
  6532. else if (!isNaN(Number(token))) {
  6533. token = Number(token); // convert to number
  6534. }
  6535. tokenType = TOKENTYPE.IDENTIFIER;
  6536. return;
  6537. }
  6538. // check for a string enclosed by double quotes
  6539. if (c == '"') {
  6540. next();
  6541. while (c != '' && (c != '"' || (c == '"' && nextPreview() == '"'))) {
  6542. token += c;
  6543. if (c == '"') { // skip the escape character
  6544. next();
  6545. }
  6546. next();
  6547. }
  6548. if (c != '"') {
  6549. throw newSyntaxError('End of string " expected');
  6550. }
  6551. next();
  6552. tokenType = TOKENTYPE.IDENTIFIER;
  6553. return;
  6554. }
  6555. // something unknown is found, wrong characters, a syntax error
  6556. tokenType = TOKENTYPE.UNKNOWN;
  6557. while (c != '') {
  6558. token += c;
  6559. next();
  6560. }
  6561. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  6562. }
  6563. /**
  6564. * Parse a graph.
  6565. * @returns {Object} graph
  6566. */
  6567. function parseGraph() {
  6568. var graph = {};
  6569. first();
  6570. getToken();
  6571. // optional strict keyword
  6572. if (token == 'strict') {
  6573. graph.strict = true;
  6574. getToken();
  6575. }
  6576. // graph or digraph keyword
  6577. if (token == 'graph' || token == 'digraph') {
  6578. graph.type = token;
  6579. getToken();
  6580. }
  6581. // optional graph id
  6582. if (tokenType == TOKENTYPE.IDENTIFIER) {
  6583. graph.id = token;
  6584. getToken();
  6585. }
  6586. // open angle bracket
  6587. if (token != '{') {
  6588. throw newSyntaxError('Angle bracket { expected');
  6589. }
  6590. getToken();
  6591. // statements
  6592. parseStatements(graph);
  6593. // close angle bracket
  6594. if (token != '}') {
  6595. throw newSyntaxError('Angle bracket } expected');
  6596. }
  6597. getToken();
  6598. // end of file
  6599. if (token !== '') {
  6600. throw newSyntaxError('End of file expected');
  6601. }
  6602. getToken();
  6603. // remove temporary default properties
  6604. delete graph.node;
  6605. delete graph.edge;
  6606. delete graph.graph;
  6607. return graph;
  6608. }
  6609. /**
  6610. * Parse a list with statements.
  6611. * @param {Object} graph
  6612. */
  6613. function parseStatements (graph) {
  6614. while (token !== '' && token != '}') {
  6615. parseStatement(graph);
  6616. if (token == ';') {
  6617. getToken();
  6618. }
  6619. }
  6620. }
  6621. /**
  6622. * Parse a single statement. Can be a an attribute statement, node
  6623. * statement, a series of node statements and edge statements, or a
  6624. * parameter.
  6625. * @param {Object} graph
  6626. */
  6627. function parseStatement(graph) {
  6628. // parse subgraph
  6629. var subgraph = parseSubgraph(graph);
  6630. if (subgraph) {
  6631. // edge statements
  6632. parseEdge(graph, subgraph);
  6633. return;
  6634. }
  6635. // parse an attribute statement
  6636. var attr = parseAttributeStatement(graph);
  6637. if (attr) {
  6638. return;
  6639. }
  6640. // parse node
  6641. if (tokenType != TOKENTYPE.IDENTIFIER) {
  6642. throw newSyntaxError('Identifier expected');
  6643. }
  6644. var id = token; // id can be a string or a number
  6645. getToken();
  6646. if (token == '=') {
  6647. // id statement
  6648. getToken();
  6649. if (tokenType != TOKENTYPE.IDENTIFIER) {
  6650. throw newSyntaxError('Identifier expected');
  6651. }
  6652. graph[id] = token;
  6653. getToken();
  6654. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  6655. }
  6656. else {
  6657. parseNodeStatement(graph, id);
  6658. }
  6659. }
  6660. /**
  6661. * Parse a subgraph
  6662. * @param {Object} graph parent graph object
  6663. * @return {Object | null} subgraph
  6664. */
  6665. function parseSubgraph (graph) {
  6666. var subgraph = null;
  6667. // optional subgraph keyword
  6668. if (token == 'subgraph') {
  6669. subgraph = {};
  6670. subgraph.type = 'subgraph';
  6671. getToken();
  6672. // optional graph id
  6673. if (tokenType == TOKENTYPE.IDENTIFIER) {
  6674. subgraph.id = token;
  6675. getToken();
  6676. }
  6677. }
  6678. // open angle bracket
  6679. if (token == '{') {
  6680. getToken();
  6681. if (!subgraph) {
  6682. subgraph = {};
  6683. }
  6684. subgraph.parent = graph;
  6685. subgraph.node = graph.node;
  6686. subgraph.edge = graph.edge;
  6687. subgraph.graph = graph.graph;
  6688. // statements
  6689. parseStatements(subgraph);
  6690. // close angle bracket
  6691. if (token != '}') {
  6692. throw newSyntaxError('Angle bracket } expected');
  6693. }
  6694. getToken();
  6695. // remove temporary default properties
  6696. delete subgraph.node;
  6697. delete subgraph.edge;
  6698. delete subgraph.graph;
  6699. delete subgraph.parent;
  6700. // register at the parent graph
  6701. if (!graph.subgraphs) {
  6702. graph.subgraphs = [];
  6703. }
  6704. graph.subgraphs.push(subgraph);
  6705. }
  6706. return subgraph;
  6707. }
  6708. /**
  6709. * parse an attribute statement like "node [shape=circle fontSize=16]".
  6710. * Available keywords are 'node', 'edge', 'graph'.
  6711. * The previous list with default attributes will be replaced
  6712. * @param {Object} graph
  6713. * @returns {String | null} keyword Returns the name of the parsed attribute
  6714. * (node, edge, graph), or null if nothing
  6715. * is parsed.
  6716. */
  6717. function parseAttributeStatement (graph) {
  6718. // attribute statements
  6719. if (token == 'node') {
  6720. getToken();
  6721. // node attributes
  6722. graph.node = parseAttributeList();
  6723. return 'node';
  6724. }
  6725. else if (token == 'edge') {
  6726. getToken();
  6727. // edge attributes
  6728. graph.edge = parseAttributeList();
  6729. return 'edge';
  6730. }
  6731. else if (token == 'graph') {
  6732. getToken();
  6733. // graph attributes
  6734. graph.graph = parseAttributeList();
  6735. return 'graph';
  6736. }
  6737. return null;
  6738. }
  6739. /**
  6740. * parse a node statement
  6741. * @param {Object} graph
  6742. * @param {String | Number} id
  6743. */
  6744. function parseNodeStatement(graph, id) {
  6745. // node statement
  6746. var node = {
  6747. id: id
  6748. };
  6749. var attr = parseAttributeList();
  6750. if (attr) {
  6751. node.attr = attr;
  6752. }
  6753. addNode(graph, node);
  6754. // edge statements
  6755. parseEdge(graph, id);
  6756. }
  6757. /**
  6758. * Parse an edge or a series of edges
  6759. * @param {Object} graph
  6760. * @param {String | Number} from Id of the from node
  6761. */
  6762. function parseEdge(graph, from) {
  6763. while (token == '->' || token == '--') {
  6764. var to;
  6765. var type = token;
  6766. getToken();
  6767. var subgraph = parseSubgraph(graph);
  6768. if (subgraph) {
  6769. to = subgraph;
  6770. }
  6771. else {
  6772. if (tokenType != TOKENTYPE.IDENTIFIER) {
  6773. throw newSyntaxError('Identifier or subgraph expected');
  6774. }
  6775. to = token;
  6776. addNode(graph, {
  6777. id: to
  6778. });
  6779. getToken();
  6780. }
  6781. // parse edge attributes
  6782. var attr = parseAttributeList();
  6783. // create edge
  6784. var edge = createEdge(graph, from, to, type, attr);
  6785. addEdge(graph, edge);
  6786. from = to;
  6787. }
  6788. }
  6789. /**
  6790. * Parse a set with attributes,
  6791. * for example [label="1.000", shape=solid]
  6792. * @return {Object | null} attr
  6793. */
  6794. function parseAttributeList() {
  6795. var attr = null;
  6796. while (token == '[') {
  6797. getToken();
  6798. attr = {};
  6799. while (token !== '' && token != ']') {
  6800. if (tokenType != TOKENTYPE.IDENTIFIER) {
  6801. throw newSyntaxError('Attribute name expected');
  6802. }
  6803. var name = token;
  6804. getToken();
  6805. if (token != '=') {
  6806. throw newSyntaxError('Equal sign = expected');
  6807. }
  6808. getToken();
  6809. if (tokenType != TOKENTYPE.IDENTIFIER) {
  6810. throw newSyntaxError('Attribute value expected');
  6811. }
  6812. var value = token;
  6813. setValue(attr, name, value); // name can be a path
  6814. getToken();
  6815. if (token ==',') {
  6816. getToken();
  6817. }
  6818. }
  6819. if (token != ']') {
  6820. throw newSyntaxError('Bracket ] expected');
  6821. }
  6822. getToken();
  6823. }
  6824. return attr;
  6825. }
  6826. /**
  6827. * Create a syntax error with extra information on current token and index.
  6828. * @param {String} message
  6829. * @returns {SyntaxError} err
  6830. */
  6831. function newSyntaxError(message) {
  6832. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  6833. }
  6834. /**
  6835. * Chop off text after a maximum length
  6836. * @param {String} text
  6837. * @param {Number} maxLength
  6838. * @returns {String}
  6839. */
  6840. function chop (text, maxLength) {
  6841. return (text.length <= maxLength) ? text : (text.substr(0, 27) + '...');
  6842. }
  6843. /**
  6844. * Execute a function fn for each pair of elements in two arrays
  6845. * @param {Array | *} array1
  6846. * @param {Array | *} array2
  6847. * @param {function} fn
  6848. */
  6849. function forEach2(array1, array2, fn) {
  6850. if (array1 instanceof Array) {
  6851. array1.forEach(function (elem1) {
  6852. if (array2 instanceof Array) {
  6853. array2.forEach(function (elem2) {
  6854. fn(elem1, elem2);
  6855. });
  6856. }
  6857. else {
  6858. fn(elem1, array2);
  6859. }
  6860. });
  6861. }
  6862. else {
  6863. if (array2 instanceof Array) {
  6864. array2.forEach(function (elem2) {
  6865. fn(array1, elem2);
  6866. });
  6867. }
  6868. else {
  6869. fn(array1, array2);
  6870. }
  6871. }
  6872. }
  6873. /**
  6874. * Convert a string containing a graph in DOT language into a map containing
  6875. * with nodes and edges in the format of graph.
  6876. * @param {String} data Text containing a graph in DOT-notation
  6877. * @return {Object} graphData
  6878. */
  6879. function DOTToGraph (data) {
  6880. // parse the DOT file
  6881. var dotData = parseDOT(data);
  6882. var graphData = {
  6883. nodes: [],
  6884. edges: [],
  6885. options: {}
  6886. };
  6887. // copy the nodes
  6888. if (dotData.nodes) {
  6889. dotData.nodes.forEach(function (dotNode) {
  6890. var graphNode = {
  6891. id: dotNode.id,
  6892. label: String(dotNode.label || dotNode.id)
  6893. };
  6894. merge(graphNode, dotNode.attr);
  6895. if (graphNode.image) {
  6896. graphNode.shape = 'image';
  6897. }
  6898. graphData.nodes.push(graphNode);
  6899. });
  6900. }
  6901. // copy the edges
  6902. if (dotData.edges) {
  6903. /**
  6904. * Convert an edge in DOT format to an edge with VisGraph format
  6905. * @param {Object} dotEdge
  6906. * @returns {Object} graphEdge
  6907. */
  6908. function convertEdge(dotEdge) {
  6909. var graphEdge = {
  6910. from: dotEdge.from,
  6911. to: dotEdge.to
  6912. };
  6913. merge(graphEdge, dotEdge.attr);
  6914. graphEdge.style = (dotEdge.type == '->') ? 'arrow' : 'line';
  6915. return graphEdge;
  6916. }
  6917. dotData.edges.forEach(function (dotEdge) {
  6918. var from, to;
  6919. if (dotEdge.from instanceof Object) {
  6920. from = dotEdge.from.nodes;
  6921. }
  6922. else {
  6923. from = {
  6924. id: dotEdge.from
  6925. }
  6926. }
  6927. if (dotEdge.to instanceof Object) {
  6928. to = dotEdge.to.nodes;
  6929. }
  6930. else {
  6931. to = {
  6932. id: dotEdge.to
  6933. }
  6934. }
  6935. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  6936. dotEdge.from.edges.forEach(function (subEdge) {
  6937. var graphEdge = convertEdge(subEdge);
  6938. graphData.edges.push(graphEdge);
  6939. });
  6940. }
  6941. forEach2(from, to, function (from, to) {
  6942. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  6943. var graphEdge = convertEdge(subEdge);
  6944. graphData.edges.push(graphEdge);
  6945. });
  6946. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  6947. dotEdge.to.edges.forEach(function (subEdge) {
  6948. var graphEdge = convertEdge(subEdge);
  6949. graphData.edges.push(graphEdge);
  6950. });
  6951. }
  6952. });
  6953. }
  6954. // copy the options
  6955. if (dotData.attr) {
  6956. graphData.options = dotData.attr;
  6957. }
  6958. return graphData;
  6959. }
  6960. // exports
  6961. exports.parseDOT = parseDOT;
  6962. exports.DOTToGraph = DOTToGraph;
  6963. })(typeof util !== 'undefined' ? util : exports);
  6964. /**
  6965. * Canvas shapes used by the Graph
  6966. */
  6967. if (typeof CanvasRenderingContext2D !== 'undefined') {
  6968. /**
  6969. * Draw a circle shape
  6970. */
  6971. CanvasRenderingContext2D.prototype.circle = function(x, y, r) {
  6972. this.beginPath();
  6973. this.arc(x, y, r, 0, 2*Math.PI, false);
  6974. };
  6975. /**
  6976. * Draw a square shape
  6977. * @param {Number} x horizontal center
  6978. * @param {Number} y vertical center
  6979. * @param {Number} r size, width and height of the square
  6980. */
  6981. CanvasRenderingContext2D.prototype.square = function(x, y, r) {
  6982. this.beginPath();
  6983. this.rect(x - r, y - r, r * 2, r * 2);
  6984. };
  6985. /**
  6986. * Draw a triangle shape
  6987. * @param {Number} x horizontal center
  6988. * @param {Number} y vertical center
  6989. * @param {Number} r radius, half the length of the sides of the triangle
  6990. */
  6991. CanvasRenderingContext2D.prototype.triangle = function(x, y, r) {
  6992. // http://en.wikipedia.org/wiki/Equilateral_triangle
  6993. this.beginPath();
  6994. var s = r * 2;
  6995. var s2 = s / 2;
  6996. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  6997. var h = Math.sqrt(s * s - s2 * s2); // height
  6998. this.moveTo(x, y - (h - ir));
  6999. this.lineTo(x + s2, y + ir);
  7000. this.lineTo(x - s2, y + ir);
  7001. this.lineTo(x, y - (h - ir));
  7002. this.closePath();
  7003. };
  7004. /**
  7005. * Draw a triangle shape in downward orientation
  7006. * @param {Number} x horizontal center
  7007. * @param {Number} y vertical center
  7008. * @param {Number} r radius
  7009. */
  7010. CanvasRenderingContext2D.prototype.triangleDown = function(x, y, r) {
  7011. // http://en.wikipedia.org/wiki/Equilateral_triangle
  7012. this.beginPath();
  7013. var s = r * 2;
  7014. var s2 = s / 2;
  7015. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  7016. var h = Math.sqrt(s * s - s2 * s2); // height
  7017. this.moveTo(x, y + (h - ir));
  7018. this.lineTo(x + s2, y - ir);
  7019. this.lineTo(x - s2, y - ir);
  7020. this.lineTo(x, y + (h - ir));
  7021. this.closePath();
  7022. };
  7023. /**
  7024. * Draw a star shape, a star with 5 points
  7025. * @param {Number} x horizontal center
  7026. * @param {Number} y vertical center
  7027. * @param {Number} r radius, half the length of the sides of the triangle
  7028. */
  7029. CanvasRenderingContext2D.prototype.star = function(x, y, r) {
  7030. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  7031. this.beginPath();
  7032. for (var n = 0; n < 10; n++) {
  7033. var radius = (n % 2 === 0) ? r * 1.3 : r * 0.5;
  7034. this.lineTo(
  7035. x + radius * Math.sin(n * 2 * Math.PI / 10),
  7036. y - radius * Math.cos(n * 2 * Math.PI / 10)
  7037. );
  7038. }
  7039. this.closePath();
  7040. };
  7041. /**
  7042. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  7043. */
  7044. CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
  7045. var r2d = Math.PI/180;
  7046. if( w - ( 2 * r ) < 0 ) { r = ( w / 2 ); } //ensure that the radius isn't too large for x
  7047. if( h - ( 2 * r ) < 0 ) { r = ( h / 2 ); } //ensure that the radius isn't too large for y
  7048. this.beginPath();
  7049. this.moveTo(x+r,y);
  7050. this.lineTo(x+w-r,y);
  7051. this.arc(x+w-r,y+r,r,r2d*270,r2d*360,false);
  7052. this.lineTo(x+w,y+h-r);
  7053. this.arc(x+w-r,y+h-r,r,0,r2d*90,false);
  7054. this.lineTo(x+r,y+h);
  7055. this.arc(x+r,y+h-r,r,r2d*90,r2d*180,false);
  7056. this.lineTo(x,y+r);
  7057. this.arc(x+r,y+r,r,r2d*180,r2d*270,false);
  7058. };
  7059. /**
  7060. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7061. */
  7062. CanvasRenderingContext2D.prototype.ellipse = function(x, y, w, h) {
  7063. var kappa = .5522848,
  7064. ox = (w / 2) * kappa, // control point offset horizontal
  7065. oy = (h / 2) * kappa, // control point offset vertical
  7066. xe = x + w, // x-end
  7067. ye = y + h, // y-end
  7068. xm = x + w / 2, // x-middle
  7069. ym = y + h / 2; // y-middle
  7070. this.beginPath();
  7071. this.moveTo(x, ym);
  7072. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7073. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7074. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7075. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7076. };
  7077. /**
  7078. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  7079. */
  7080. CanvasRenderingContext2D.prototype.database = function(x, y, w, h) {
  7081. var f = 1/3;
  7082. var wEllipse = w;
  7083. var hEllipse = h * f;
  7084. var kappa = .5522848,
  7085. ox = (wEllipse / 2) * kappa, // control point offset horizontal
  7086. oy = (hEllipse / 2) * kappa, // control point offset vertical
  7087. xe = x + wEllipse, // x-end
  7088. ye = y + hEllipse, // y-end
  7089. xm = x + wEllipse / 2, // x-middle
  7090. ym = y + hEllipse / 2, // y-middle
  7091. ymb = y + (h - hEllipse/2), // y-midlle, bottom ellipse
  7092. yeb = y + h; // y-end, bottom ellipse
  7093. this.beginPath();
  7094. this.moveTo(xe, ym);
  7095. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  7096. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  7097. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  7098. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  7099. this.lineTo(xe, ymb);
  7100. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  7101. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  7102. this.lineTo(x, ym);
  7103. };
  7104. /**
  7105. * Draw an arrow point (no line)
  7106. */
  7107. CanvasRenderingContext2D.prototype.arrow = function(x, y, angle, length) {
  7108. // tail
  7109. var xt = x - length * Math.cos(angle);
  7110. var yt = y - length * Math.sin(angle);
  7111. // inner tail
  7112. // TODO: allow to customize different shapes
  7113. var xi = x - length * 0.9 * Math.cos(angle);
  7114. var yi = y - length * 0.9 * Math.sin(angle);
  7115. // left
  7116. var xl = xt + length / 3 * Math.cos(angle + 0.5 * Math.PI);
  7117. var yl = yt + length / 3 * Math.sin(angle + 0.5 * Math.PI);
  7118. // right
  7119. var xr = xt + length / 3 * Math.cos(angle - 0.5 * Math.PI);
  7120. var yr = yt + length / 3 * Math.sin(angle - 0.5 * Math.PI);
  7121. this.beginPath();
  7122. this.moveTo(x, y);
  7123. this.lineTo(xl, yl);
  7124. this.lineTo(xi, yi);
  7125. this.lineTo(xr, yr);
  7126. this.closePath();
  7127. };
  7128. /**
  7129. * Sets up the dashedLine functionality for drawing
  7130. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  7131. * @author David Jordan
  7132. * @date 2012-08-08
  7133. */
  7134. CanvasRenderingContext2D.prototype.dashedLine = function(x,y,x2,y2,dashArray){
  7135. if (!dashArray) dashArray=[10,5];
  7136. if (dashLength==0) dashLength = 0.001; // Hack for Safari
  7137. var dashCount = dashArray.length;
  7138. this.moveTo(x, y);
  7139. var dx = (x2-x), dy = (y2-y);
  7140. var slope = dy/dx;
  7141. var distRemaining = Math.sqrt( dx*dx + dy*dy );
  7142. var dashIndex=0, draw=true;
  7143. while (distRemaining>=0.1){
  7144. var dashLength = dashArray[dashIndex++%dashCount];
  7145. if (dashLength > distRemaining) dashLength = distRemaining;
  7146. var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) );
  7147. if (dx<0) xStep = -xStep;
  7148. x += xStep;
  7149. y += slope*xStep;
  7150. this[draw ? 'lineTo' : 'moveTo'](x,y);
  7151. distRemaining -= dashLength;
  7152. draw = !draw;
  7153. }
  7154. };
  7155. // TODO: add diamond shape
  7156. }
  7157. /**
  7158. * @class Node
  7159. * A node. A node can be connected to other nodes via one or multiple edges.
  7160. * @param {object} properties An object containing properties for the node. All
  7161. * properties are optional, except for the id.
  7162. * {number} id Id of the node. Required
  7163. * {string} label Text label for the node
  7164. * {number} x Horizontal position of the node
  7165. * {number} y Vertical position of the node
  7166. * {string} shape Node shape, available:
  7167. * "database", "circle", "ellipse",
  7168. * "box", "image", "text", "dot",
  7169. * "star", "triangle", "triangleDown",
  7170. * "square"
  7171. * {string} image An image url
  7172. * {string} title An title text, can be HTML
  7173. * {anytype} group A group name or number
  7174. * @param {Graph.Images} imagelist A list with images. Only needed
  7175. * when the node has an image
  7176. * @param {Graph.Groups} grouplist A list with groups. Needed for
  7177. * retrieving group properties
  7178. * @param {Object} constants An object with default values for
  7179. * example for the color
  7180. */
  7181. function Node(properties, imagelist, grouplist, constants) {
  7182. this.selected = false;
  7183. this.edges = []; // all edges connected to this node
  7184. this.group = constants.nodes.group;
  7185. this.fontSize = constants.nodes.fontSize;
  7186. this.fontFace = constants.nodes.fontFace;
  7187. this.fontColor = constants.nodes.fontColor;
  7188. this.color = constants.nodes.color;
  7189. // set defaults for the properties
  7190. this.id = undefined;
  7191. this.shape = constants.nodes.shape;
  7192. this.image = constants.nodes.image;
  7193. this.x = 0;
  7194. this.y = 0;
  7195. this.xFixed = false;
  7196. this.yFixed = false;
  7197. this.radius = constants.nodes.radius;
  7198. this.radiusFixed = false;
  7199. this.radiusMin = constants.nodes.radiusMin;
  7200. this.radiusMax = constants.nodes.radiusMax;
  7201. this.imagelist = imagelist;
  7202. this.grouplist = grouplist;
  7203. this.setProperties(properties, constants);
  7204. // mass, force, velocity
  7205. this.mass = 50; // kg (mass is adjusted for the number of connected edges)
  7206. this.fx = 0.0; // external force x
  7207. this.fy = 0.0; // external force y
  7208. this.vx = 0.0; // velocity x
  7209. this.vy = 0.0; // velocity y
  7210. this.minForce = constants.minForce;
  7211. this.damping = 0.9; // damping factor
  7212. };
  7213. /**
  7214. * Attach a edge to the node
  7215. * @param {Edge} edge
  7216. */
  7217. Node.prototype.attachEdge = function(edge) {
  7218. if (this.edges.indexOf(edge) == -1) {
  7219. this.edges.push(edge);
  7220. }
  7221. this._updateMass();
  7222. };
  7223. /**
  7224. * Detach a edge from the node
  7225. * @param {Edge} edge
  7226. */
  7227. Node.prototype.detachEdge = function(edge) {
  7228. var index = this.edges.indexOf(edge);
  7229. if (index != -1) {
  7230. this.edges.splice(index, 1);
  7231. }
  7232. this._updateMass();
  7233. };
  7234. /**
  7235. * Update the nodes mass, which is determined by the number of edges connecting
  7236. * to it (more edges -> heavier node).
  7237. * @private
  7238. */
  7239. Node.prototype._updateMass = function() {
  7240. this.mass = 50 + 20 * this.edges.length; // kg
  7241. };
  7242. /**
  7243. * Set or overwrite properties for the node
  7244. * @param {Object} properties an object with properties
  7245. * @param {Object} constants and object with default, global properties
  7246. */
  7247. Node.prototype.setProperties = function(properties, constants) {
  7248. if (!properties) {
  7249. return;
  7250. }
  7251. // basic properties
  7252. if (properties.id != undefined) {this.id = properties.id;}
  7253. if (properties.label != undefined) {this.label = properties.label;}
  7254. if (properties.title != undefined) {this.title = properties.title;}
  7255. if (properties.group != undefined) {this.group = properties.group;}
  7256. if (properties.x != undefined) {this.x = properties.x;}
  7257. if (properties.y != undefined) {this.y = properties.y;}
  7258. if (properties.value != undefined) {this.value = properties.value;}
  7259. if (this.id === undefined) {
  7260. throw "Node must have an id";
  7261. }
  7262. // copy group properties
  7263. if (this.group) {
  7264. var groupObj = this.grouplist.get(this.group);
  7265. for (var prop in groupObj) {
  7266. if (groupObj.hasOwnProperty(prop)) {
  7267. this[prop] = groupObj[prop];
  7268. }
  7269. }
  7270. }
  7271. // individual shape properties
  7272. if (properties.shape != undefined) {this.shape = properties.shape;}
  7273. if (properties.image != undefined) {this.image = properties.image;}
  7274. if (properties.radius != undefined) {this.radius = properties.radius;}
  7275. if (properties.color != undefined) {this.color = Node.parseColor(properties.color);}
  7276. if (properties.fontColor != undefined) {this.fontColor = properties.fontColor;}
  7277. if (properties.fontSize != undefined) {this.fontSize = properties.fontSize;}
  7278. if (properties.fontFace != undefined) {this.fontFace = properties.fontFace;}
  7279. if (this.image != undefined) {
  7280. if (this.imagelist) {
  7281. this.imageObj = this.imagelist.load(this.image);
  7282. }
  7283. else {
  7284. throw "No imagelist provided";
  7285. }
  7286. }
  7287. this.xFixed = this.xFixed || (properties.x != undefined);
  7288. this.yFixed = this.yFixed || (properties.y != undefined);
  7289. this.radiusFixed = this.radiusFixed || (properties.radius != undefined);
  7290. if (this.shape == 'image') {
  7291. this.radiusMin = constants.nodes.widthMin;
  7292. this.radiusMax = constants.nodes.widthMax;
  7293. }
  7294. // choose draw method depending on the shape
  7295. switch (this.shape) {
  7296. case 'database': this.draw = this._drawDatabase; this.resize = this._resizeDatabase; break;
  7297. case 'box': this.draw = this._drawBox; this.resize = this._resizeBox; break;
  7298. case 'circle': this.draw = this._drawCircle; this.resize = this._resizeCircle; break;
  7299. case 'ellipse': this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  7300. // TODO: add diamond shape
  7301. case 'image': this.draw = this._drawImage; this.resize = this._resizeImage; break;
  7302. case 'text': this.draw = this._drawText; this.resize = this._resizeText; break;
  7303. case 'dot': this.draw = this._drawDot; this.resize = this._resizeShape; break;
  7304. case 'square': this.draw = this._drawSquare; this.resize = this._resizeShape; break;
  7305. case 'triangle': this.draw = this._drawTriangle; this.resize = this._resizeShape; break;
  7306. case 'triangleDown': this.draw = this._drawTriangleDown; this.resize = this._resizeShape; break;
  7307. case 'star': this.draw = this._drawStar; this.resize = this._resizeShape; break;
  7308. default: this.draw = this._drawEllipse; this.resize = this._resizeEllipse; break;
  7309. }
  7310. // reset the size of the node, this can be changed
  7311. this._reset();
  7312. };
  7313. /**
  7314. * Parse a color property into an object with border, background, and
  7315. * hightlight colors
  7316. * @param {Object | String} color
  7317. * @return {Object} colorObject
  7318. */
  7319. Node.parseColor = function(color) {
  7320. var c;
  7321. if (util.isString(color)) {
  7322. c = {
  7323. border: color,
  7324. background: color,
  7325. highlight: {
  7326. border: color,
  7327. background: color
  7328. }
  7329. };
  7330. // TODO: automatically generate a nice highlight color
  7331. }
  7332. else {
  7333. c = {};
  7334. c.background = color.background || 'white';
  7335. c.border = color.border || c.background;
  7336. if (util.isString(color.highlight)) {
  7337. c.highlight = {
  7338. border: color.highlight,
  7339. background: color.highlight
  7340. }
  7341. }
  7342. else {
  7343. c.highlight = {};
  7344. c.highlight.background = color.highlight && color.highlight.background || c.background;
  7345. c.highlight.border = color.highlight && color.highlight.border || c.border;
  7346. }
  7347. }
  7348. return c;
  7349. };
  7350. /**
  7351. * select this node
  7352. */
  7353. Node.prototype.select = function() {
  7354. this.selected = true;
  7355. this._reset();
  7356. };
  7357. /**
  7358. * unselect this node
  7359. */
  7360. Node.prototype.unselect = function() {
  7361. this.selected = false;
  7362. this._reset();
  7363. };
  7364. /**
  7365. * Reset the calculated size of the node, forces it to recalculate its size
  7366. * @private
  7367. */
  7368. Node.prototype._reset = function() {
  7369. this.width = undefined;
  7370. this.height = undefined;
  7371. };
  7372. /**
  7373. * get the title of this node.
  7374. * @return {string} title The title of the node, or undefined when no title
  7375. * has been set.
  7376. */
  7377. Node.prototype.getTitle = function() {
  7378. return this.title;
  7379. };
  7380. /**
  7381. * Calculate the distance to the border of the Node
  7382. * @param {CanvasRenderingContext2D} ctx
  7383. * @param {Number} angle Angle in radians
  7384. * @returns {number} distance Distance to the border in pixels
  7385. */
  7386. Node.prototype.distanceToBorder = function (ctx, angle) {
  7387. var borderWidth = 1;
  7388. if (!this.width) {
  7389. this.resize(ctx);
  7390. }
  7391. //noinspection FallthroughInSwitchStatementJS
  7392. switch (this.shape) {
  7393. case 'circle':
  7394. case 'dot':
  7395. return this.radius + borderWidth;
  7396. case 'ellipse':
  7397. var a = this.width / 2;
  7398. var b = this.height / 2;
  7399. var w = (Math.sin(angle) * a);
  7400. var h = (Math.cos(angle) * b);
  7401. return a * b / Math.sqrt(w * w + h * h);
  7402. // TODO: implement distanceToBorder for database
  7403. // TODO: implement distanceToBorder for triangle
  7404. // TODO: implement distanceToBorder for triangleDown
  7405. case 'box':
  7406. case 'image':
  7407. case 'text':
  7408. default:
  7409. if (this.width) {
  7410. return Math.min(
  7411. Math.abs(this.width / 2 / Math.cos(angle)),
  7412. Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  7413. // TODO: reckon with border radius too in case of box
  7414. }
  7415. else {
  7416. return 0;
  7417. }
  7418. }
  7419. // TODO: implement calculation of distance to border for all shapes
  7420. };
  7421. /**
  7422. * Set forces acting on the node
  7423. * @param {number} fx Force in horizontal direction
  7424. * @param {number} fy Force in vertical direction
  7425. */
  7426. Node.prototype._setForce = function(fx, fy) {
  7427. this.fx = fx;
  7428. this.fy = fy;
  7429. };
  7430. /**
  7431. * Add forces acting on the node
  7432. * @param {number} fx Force in horizontal direction
  7433. * @param {number} fy Force in vertical direction
  7434. * @private
  7435. */
  7436. Node.prototype._addForce = function(fx, fy) {
  7437. this.fx += fx;
  7438. this.fy += fy;
  7439. };
  7440. /**
  7441. * Perform one discrete step for the node
  7442. * @param {number} interval Time interval in seconds
  7443. */
  7444. Node.prototype.discreteStep = function(interval) {
  7445. if (!this.xFixed) {
  7446. var dx = -this.damping * this.vx; // damping force
  7447. var ax = (this.fx + dx) / this.mass; // acceleration
  7448. this.vx += ax / interval; // velocity
  7449. this.x += this.vx / interval; // position
  7450. }
  7451. if (!this.yFixed) {
  7452. var dy = -this.damping * this.vy; // damping force
  7453. var ay = (this.fy + dy) / this.mass; // acceleration
  7454. this.vy += ay / interval; // velocity
  7455. this.y += this.vy / interval; // position
  7456. }
  7457. };
  7458. /**
  7459. * Check if this node has a fixed x and y position
  7460. * @return {boolean} true if fixed, false if not
  7461. */
  7462. Node.prototype.isFixed = function() {
  7463. return (this.xFixed && this.yFixed);
  7464. };
  7465. /**
  7466. * Check if this node is moving
  7467. * @param {number} vmin the minimum velocity considered as "moving"
  7468. * @return {boolean} true if moving, false if it has no velocity
  7469. */
  7470. // TODO: replace this method with calculating the kinetic energy
  7471. Node.prototype.isMoving = function(vmin) {
  7472. return (Math.abs(this.vx) > vmin || Math.abs(this.vy) > vmin ||
  7473. (!this.xFixed && Math.abs(this.fx) > this.minForce) ||
  7474. (!this.yFixed && Math.abs(this.fy) > this.minForce));
  7475. };
  7476. /**
  7477. * check if this node is selecte
  7478. * @return {boolean} selected True if node is selected, else false
  7479. */
  7480. Node.prototype.isSelected = function() {
  7481. return this.selected;
  7482. };
  7483. /**
  7484. * Retrieve the value of the node. Can be undefined
  7485. * @return {Number} value
  7486. */
  7487. Node.prototype.getValue = function() {
  7488. return this.value;
  7489. };
  7490. /**
  7491. * Calculate the distance from the nodes location to the given location (x,y)
  7492. * @param {Number} x
  7493. * @param {Number} y
  7494. * @return {Number} value
  7495. */
  7496. Node.prototype.getDistance = function(x, y) {
  7497. var dx = this.x - x,
  7498. dy = this.y - y;
  7499. return Math.sqrt(dx * dx + dy * dy);
  7500. };
  7501. /**
  7502. * Adjust the value range of the node. The node will adjust it's radius
  7503. * based on its value.
  7504. * @param {Number} min
  7505. * @param {Number} max
  7506. */
  7507. Node.prototype.setValueRange = function(min, max) {
  7508. if (!this.radiusFixed && this.value !== undefined) {
  7509. var scale = (this.radiusMax - this.radiusMin) / (max - min);
  7510. this.radius = (this.value - min) * scale + this.radiusMin;
  7511. }
  7512. };
  7513. /**
  7514. * Draw this node in the given canvas
  7515. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  7516. * @param {CanvasRenderingContext2D} ctx
  7517. */
  7518. Node.prototype.draw = function(ctx) {
  7519. throw "Draw method not initialized for node";
  7520. };
  7521. /**
  7522. * Recalculate the size of this node in the given canvas
  7523. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  7524. * @param {CanvasRenderingContext2D} ctx
  7525. */
  7526. Node.prototype.resize = function(ctx) {
  7527. throw "Resize method not initialized for node";
  7528. };
  7529. /**
  7530. * Check if this object is overlapping with the provided object
  7531. * @param {Object} obj an object with parameters left, top, right, bottom
  7532. * @return {boolean} True if location is located on node
  7533. */
  7534. Node.prototype.isOverlappingWith = function(obj) {
  7535. return (this.left < obj.right &&
  7536. this.left + this.width > obj.left &&
  7537. this.top < obj.bottom &&
  7538. this.top + this.height > obj.top);
  7539. };
  7540. Node.prototype._resizeImage = function (ctx) {
  7541. // TODO: pre calculate the image size
  7542. if (!this.width) { // undefined or 0
  7543. var width, height;
  7544. if (this.value) {
  7545. var scale = this.imageObj.height / this.imageObj.width;
  7546. width = this.radius || this.imageObj.width;
  7547. height = this.radius * scale || this.imageObj.height;
  7548. }
  7549. else {
  7550. width = this.imageObj.width;
  7551. height = this.imageObj.height;
  7552. }
  7553. this.width = width;
  7554. this.height = height;
  7555. }
  7556. };
  7557. Node.prototype._drawImage = function (ctx) {
  7558. this._resizeImage(ctx);
  7559. this.left = this.x - this.width / 2;
  7560. this.top = this.y - this.height / 2;
  7561. var yLabel;
  7562. if (this.imageObj) {
  7563. ctx.drawImage(this.imageObj, this.left, this.top, this.width, this.height);
  7564. yLabel = this.y + this.height / 2;
  7565. }
  7566. else {
  7567. // image still loading... just draw the label for now
  7568. yLabel = this.y;
  7569. }
  7570. this._label(ctx, this.label, this.x, yLabel, undefined, "top");
  7571. };
  7572. Node.prototype._resizeBox = function (ctx) {
  7573. if (!this.width) {
  7574. var margin = 5;
  7575. var textSize = this.getTextSize(ctx);
  7576. this.width = textSize.width + 2 * margin;
  7577. this.height = textSize.height + 2 * margin;
  7578. }
  7579. };
  7580. Node.prototype._drawBox = function (ctx) {
  7581. this._resizeBox(ctx);
  7582. this.left = this.x - this.width / 2;
  7583. this.top = this.y - this.height / 2;
  7584. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  7585. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  7586. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  7587. ctx.roundRect(this.left, this.top, this.width, this.height, this.radius);
  7588. ctx.fill();
  7589. ctx.stroke();
  7590. this._label(ctx, this.label, this.x, this.y);
  7591. };
  7592. Node.prototype._resizeDatabase = function (ctx) {
  7593. if (!this.width) {
  7594. var margin = 5;
  7595. var textSize = this.getTextSize(ctx);
  7596. var size = textSize.width + 2 * margin;
  7597. this.width = size;
  7598. this.height = size;
  7599. }
  7600. };
  7601. Node.prototype._drawDatabase = function (ctx) {
  7602. this._resizeDatabase(ctx);
  7603. this.left = this.x - this.width / 2;
  7604. this.top = this.y - this.height / 2;
  7605. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  7606. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  7607. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  7608. ctx.database(this.x - this.width/2, this.y - this.height*0.5, this.width, this.height);
  7609. ctx.fill();
  7610. ctx.stroke();
  7611. this._label(ctx, this.label, this.x, this.y);
  7612. };
  7613. Node.prototype._resizeCircle = function (ctx) {
  7614. if (!this.width) {
  7615. var margin = 5;
  7616. var textSize = this.getTextSize(ctx);
  7617. var diameter = Math.max(textSize.width, textSize.height) + 2 * margin;
  7618. this.radius = diameter / 2;
  7619. this.width = diameter;
  7620. this.height = diameter;
  7621. }
  7622. };
  7623. Node.prototype._drawCircle = function (ctx) {
  7624. this._resizeCircle(ctx);
  7625. this.left = this.x - this.width / 2;
  7626. this.top = this.y - this.height / 2;
  7627. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  7628. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  7629. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  7630. ctx.circle(this.x, this.y, this.radius);
  7631. ctx.fill();
  7632. ctx.stroke();
  7633. this._label(ctx, this.label, this.x, this.y);
  7634. };
  7635. Node.prototype._resizeEllipse = function (ctx) {
  7636. if (!this.width) {
  7637. var textSize = this.getTextSize(ctx);
  7638. this.width = textSize.width * 1.5;
  7639. this.height = textSize.height * 2;
  7640. if (this.width < this.height) {
  7641. this.width = this.height;
  7642. }
  7643. }
  7644. };
  7645. Node.prototype._drawEllipse = function (ctx) {
  7646. this._resizeEllipse(ctx);
  7647. this.left = this.x - this.width / 2;
  7648. this.top = this.y - this.height / 2;
  7649. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  7650. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  7651. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  7652. ctx.ellipse(this.left, this.top, this.width, this.height);
  7653. ctx.fill();
  7654. ctx.stroke();
  7655. this._label(ctx, this.label, this.x, this.y);
  7656. };
  7657. Node.prototype._drawDot = function (ctx) {
  7658. this._drawShape(ctx, 'circle');
  7659. };
  7660. Node.prototype._drawTriangle = function (ctx) {
  7661. this._drawShape(ctx, 'triangle');
  7662. };
  7663. Node.prototype._drawTriangleDown = function (ctx) {
  7664. this._drawShape(ctx, 'triangleDown');
  7665. };
  7666. Node.prototype._drawSquare = function (ctx) {
  7667. this._drawShape(ctx, 'square');
  7668. };
  7669. Node.prototype._drawStar = function (ctx) {
  7670. this._drawShape(ctx, 'star');
  7671. };
  7672. Node.prototype._resizeShape = function (ctx) {
  7673. if (!this.width) {
  7674. var size = 2 * this.radius;
  7675. this.width = size;
  7676. this.height = size;
  7677. }
  7678. };
  7679. Node.prototype._drawShape = function (ctx, shape) {
  7680. this._resizeShape(ctx);
  7681. this.left = this.x - this.width / 2;
  7682. this.top = this.y - this.height / 2;
  7683. ctx.strokeStyle = this.selected ? this.color.highlight.border : this.color.border;
  7684. ctx.fillStyle = this.selected ? this.color.highlight.background : this.color.background;
  7685. ctx.lineWidth = this.selected ? 2.0 : 1.0;
  7686. ctx[shape](this.x, this.y, this.radius);
  7687. ctx.fill();
  7688. ctx.stroke();
  7689. if (this.label) {
  7690. this._label(ctx, this.label, this.x, this.y + this.height / 2, undefined, 'top');
  7691. }
  7692. };
  7693. Node.prototype._resizeText = function (ctx) {
  7694. if (!this.width) {
  7695. var margin = 5;
  7696. var textSize = this.getTextSize(ctx);
  7697. this.width = textSize.width + 2 * margin;
  7698. this.height = textSize.height + 2 * margin;
  7699. }
  7700. };
  7701. Node.prototype._drawText = function (ctx) {
  7702. this._resizeText(ctx);
  7703. this.left = this.x - this.width / 2;
  7704. this.top = this.y - this.height / 2;
  7705. this._label(ctx, this.label, this.x, this.y);
  7706. };
  7707. Node.prototype._label = function (ctx, text, x, y, align, baseline) {
  7708. if (text) {
  7709. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  7710. ctx.fillStyle = this.fontColor || "black";
  7711. ctx.textAlign = align || "center";
  7712. ctx.textBaseline = baseline || "middle";
  7713. var lines = text.split('\n'),
  7714. lineCount = lines.length,
  7715. fontSize = (this.fontSize + 4),
  7716. yLine = y + (1 - lineCount) / 2 * fontSize;
  7717. for (var i = 0; i < lineCount; i++) {
  7718. ctx.fillText(lines[i], x, yLine);
  7719. yLine += fontSize;
  7720. }
  7721. }
  7722. };
  7723. Node.prototype.getTextSize = function(ctx) {
  7724. if (this.label != undefined) {
  7725. ctx.font = (this.selected ? "bold " : "") + this.fontSize + "px " + this.fontFace;
  7726. var lines = this.label.split('\n'),
  7727. height = (this.fontSize + 4) * lines.length,
  7728. width = 0;
  7729. for (var i = 0, iMax = lines.length; i < iMax; i++) {
  7730. width = Math.max(width, ctx.measureText(lines[i]).width);
  7731. }
  7732. return {"width": width, "height": height};
  7733. }
  7734. else {
  7735. return {"width": 0, "height": 0};
  7736. }
  7737. };
  7738. /**
  7739. * @class Edge
  7740. *
  7741. * A edge connects two nodes
  7742. * @param {Object} properties Object with properties. Must contain
  7743. * At least properties from and to.
  7744. * Available properties: from (number),
  7745. * to (number), label (string, color (string),
  7746. * width (number), style (string),
  7747. * length (number), title (string)
  7748. * @param {Graph} graph A graph object, used to find and edge to
  7749. * nodes.
  7750. * @param {Object} constants An object with default values for
  7751. * example for the color
  7752. */
  7753. function Edge (properties, graph, constants) {
  7754. if (!graph) {
  7755. throw "No graph provided";
  7756. }
  7757. this.graph = graph;
  7758. // initialize constants
  7759. this.widthMin = constants.edges.widthMin;
  7760. this.widthMax = constants.edges.widthMax;
  7761. // initialize variables
  7762. this.id = undefined;
  7763. this.fromId = undefined;
  7764. this.toId = undefined;
  7765. this.style = constants.edges.style;
  7766. this.title = undefined;
  7767. this.width = constants.edges.width;
  7768. this.value = undefined;
  7769. this.length = constants.edges.length;
  7770. this.from = null; // a node
  7771. this.to = null; // a node
  7772. this.connected = false;
  7773. // Added to support dashed lines
  7774. // David Jordan
  7775. // 2012-08-08
  7776. this.dash = util.extend({}, constants.edges.dash); // contains properties length, gap, altLength
  7777. this.stiffness = undefined; // depends on the length of the edge
  7778. this.color = constants.edges.color;
  7779. this.widthFixed = false;
  7780. this.lengthFixed = false;
  7781. this.setProperties(properties, constants);
  7782. }
  7783. /**
  7784. * Set or overwrite properties for the edge
  7785. * @param {Object} properties an object with properties
  7786. * @param {Object} constants and object with default, global properties
  7787. */
  7788. Edge.prototype.setProperties = function(properties, constants) {
  7789. if (!properties) {
  7790. return;
  7791. }
  7792. if (properties.from != undefined) {this.fromId = properties.from;}
  7793. if (properties.to != undefined) {this.toId = properties.to;}
  7794. if (properties.id != undefined) {this.id = properties.id;}
  7795. if (properties.style != undefined) {this.style = properties.style;}
  7796. if (properties.label != undefined) {this.label = properties.label;}
  7797. if (this.label) {
  7798. this.fontSize = constants.edges.fontSize;
  7799. this.fontFace = constants.edges.fontFace;
  7800. this.fontColor = constants.edges.fontColor;
  7801. if (properties.fontColor != undefined) {this.fontColor = properties.fontColor;}
  7802. if (properties.fontSize != undefined) {this.fontSize = properties.fontSize;}
  7803. if (properties.fontFace != undefined) {this.fontFace = properties.fontFace;}
  7804. }
  7805. if (properties.title != undefined) {this.title = properties.title;}
  7806. if (properties.width != undefined) {this.width = properties.width;}
  7807. if (properties.value != undefined) {this.value = properties.value;}
  7808. if (properties.length != undefined) {this.length = properties.length;}
  7809. // Added to support dashed lines
  7810. // David Jordan
  7811. // 2012-08-08
  7812. if (properties.dash) {
  7813. if (properties.dash.length != undefined) {this.dash.length = properties.dash.length;}
  7814. if (properties.dash.gap != undefined) {this.dash.gap = properties.dash.gap;}
  7815. if (properties.dash.altLength != undefined) {this.dash.altLength = properties.dash.altLength;}
  7816. }
  7817. if (properties.color != undefined) {this.color = properties.color;}
  7818. // A node is connected when it has a from and to node.
  7819. this.connect();
  7820. this.widthFixed = this.widthFixed || (properties.width != undefined);
  7821. this.lengthFixed = this.lengthFixed || (properties.length != undefined);
  7822. this.stiffness = 1 / this.length;
  7823. // set draw method based on style
  7824. switch (this.style) {
  7825. case 'line': this.draw = this._drawLine; break;
  7826. case 'arrow': this.draw = this._drawArrow; break;
  7827. case 'arrow-center': this.draw = this._drawArrowCenter; break;
  7828. case 'dash-line': this.draw = this._drawDashLine; break;
  7829. default: this.draw = this._drawLine; break;
  7830. }
  7831. };
  7832. /**
  7833. * Connect an edge to its nodes
  7834. */
  7835. Edge.prototype.connect = function () {
  7836. this.disconnect();
  7837. this.from = this.graph.nodes[this.fromId] || null;
  7838. this.to = this.graph.nodes[this.toId] || null;
  7839. this.connected = (this.from && this.to);
  7840. if (this.connected) {
  7841. this.from.attachEdge(this);
  7842. this.to.attachEdge(this);
  7843. }
  7844. else {
  7845. if (this.from) {
  7846. this.from.detachEdge(this);
  7847. }
  7848. if (this.to) {
  7849. this.to.detachEdge(this);
  7850. }
  7851. }
  7852. };
  7853. /**
  7854. * Disconnect an edge from its nodes
  7855. */
  7856. Edge.prototype.disconnect = function () {
  7857. if (this.from) {
  7858. this.from.detachEdge(this);
  7859. this.from = null;
  7860. }
  7861. if (this.to) {
  7862. this.to.detachEdge(this);
  7863. this.to = null;
  7864. }
  7865. this.connected = false;
  7866. };
  7867. /**
  7868. * get the title of this edge.
  7869. * @return {string} title The title of the edge, or undefined when no title
  7870. * has been set.
  7871. */
  7872. Edge.prototype.getTitle = function() {
  7873. return this.title;
  7874. };
  7875. /**
  7876. * Retrieve the value of the edge. Can be undefined
  7877. * @return {Number} value
  7878. */
  7879. Edge.prototype.getValue = function() {
  7880. return this.value;
  7881. };
  7882. /**
  7883. * Adjust the value range of the edge. The edge will adjust it's width
  7884. * based on its value.
  7885. * @param {Number} min
  7886. * @param {Number} max
  7887. */
  7888. Edge.prototype.setValueRange = function(min, max) {
  7889. if (!this.widthFixed && this.value !== undefined) {
  7890. var factor = (this.widthMax - this.widthMin) / (max - min);
  7891. this.width = (this.value - min) * factor + this.widthMin;
  7892. }
  7893. };
  7894. /**
  7895. * Redraw a edge
  7896. * Draw this edge in the given canvas
  7897. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  7898. * @param {CanvasRenderingContext2D} ctx
  7899. */
  7900. Edge.prototype.draw = function(ctx) {
  7901. throw "Method draw not initialized in edge";
  7902. };
  7903. /**
  7904. * Check if this object is overlapping with the provided object
  7905. * @param {Object} obj an object with parameters left, top
  7906. * @return {boolean} True if location is located on the edge
  7907. */
  7908. Edge.prototype.isOverlappingWith = function(obj) {
  7909. var distMax = 10;
  7910. var xFrom = this.from.x;
  7911. var yFrom = this.from.y;
  7912. var xTo = this.to.x;
  7913. var yTo = this.to.y;
  7914. var xObj = obj.left;
  7915. var yObj = obj.top;
  7916. var dist = Edge._dist(xFrom, yFrom, xTo, yTo, xObj, yObj);
  7917. return (dist < distMax);
  7918. };
  7919. /**
  7920. * Redraw a edge as a line
  7921. * Draw this edge in the given canvas
  7922. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  7923. * @param {CanvasRenderingContext2D} ctx
  7924. * @private
  7925. */
  7926. Edge.prototype._drawLine = function(ctx) {
  7927. // set style
  7928. ctx.strokeStyle = this.color;
  7929. ctx.lineWidth = this._getLineWidth();
  7930. var point;
  7931. if (this.from != this.to) {
  7932. // draw line
  7933. this._line(ctx);
  7934. // draw label
  7935. if (this.label) {
  7936. point = this._pointOnLine(0.5);
  7937. this._label(ctx, this.label, point.x, point.y);
  7938. }
  7939. }
  7940. else {
  7941. var x, y;
  7942. var radius = this.length / 4;
  7943. var node = this.from;
  7944. if (!node.width) {
  7945. node.resize(ctx);
  7946. }
  7947. if (node.width > node.height) {
  7948. x = node.x + node.width / 2;
  7949. y = node.y - radius;
  7950. }
  7951. else {
  7952. x = node.x + radius;
  7953. y = node.y - node.height / 2;
  7954. }
  7955. this._circle(ctx, x, y, radius);
  7956. point = this._pointOnCircle(x, y, radius, 0.5);
  7957. this._label(ctx, this.label, point.x, point.y);
  7958. }
  7959. };
  7960. /**
  7961. * Get the line width of the edge. Depends on width and whether one of the
  7962. * connected nodes is selected.
  7963. * @return {Number} width
  7964. * @private
  7965. */
  7966. Edge.prototype._getLineWidth = function() {
  7967. if (this.from.selected || this.to.selected) {
  7968. return Math.min(this.width * 2, this.widthMax);
  7969. }
  7970. else {
  7971. return this.width;
  7972. }
  7973. };
  7974. /**
  7975. * Draw a line between two nodes
  7976. * @param {CanvasRenderingContext2D} ctx
  7977. * @private
  7978. */
  7979. Edge.prototype._line = function (ctx) {
  7980. // draw a straight line
  7981. ctx.beginPath();
  7982. ctx.moveTo(this.from.x, this.from.y);
  7983. ctx.lineTo(this.to.x, this.to.y);
  7984. ctx.stroke();
  7985. };
  7986. /**
  7987. * Draw a line from a node to itself, a circle
  7988. * @param {CanvasRenderingContext2D} ctx
  7989. * @param {Number} x
  7990. * @param {Number} y
  7991. * @param {Number} radius
  7992. * @private
  7993. */
  7994. Edge.prototype._circle = function (ctx, x, y, radius) {
  7995. // draw a circle
  7996. ctx.beginPath();
  7997. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  7998. ctx.stroke();
  7999. };
  8000. /**
  8001. * Draw label with white background and with the middle at (x, y)
  8002. * @param {CanvasRenderingContext2D} ctx
  8003. * @param {String} text
  8004. * @param {Number} x
  8005. * @param {Number} y
  8006. * @private
  8007. */
  8008. Edge.prototype._label = function (ctx, text, x, y) {
  8009. if (text) {
  8010. // TODO: cache the calculated size
  8011. ctx.font = ((this.from.selected || this.to.selected) ? "bold " : "") +
  8012. this.fontSize + "px " + this.fontFace;
  8013. ctx.fillStyle = 'white';
  8014. var width = ctx.measureText(text).width;
  8015. var height = this.fontSize;
  8016. var left = x - width / 2;
  8017. var top = y - height / 2;
  8018. ctx.fillRect(left, top, width, height);
  8019. // draw text
  8020. ctx.fillStyle = this.fontColor || "black";
  8021. ctx.textAlign = "left";
  8022. ctx.textBaseline = "top";
  8023. ctx.fillText(text, left, top);
  8024. }
  8025. };
  8026. /**
  8027. * Redraw a edge as a dashed line
  8028. * Draw this edge in the given canvas
  8029. * @author David Jordan
  8030. * @date 2012-08-08
  8031. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8032. * @param {CanvasRenderingContext2D} ctx
  8033. * @private
  8034. */
  8035. Edge.prototype._drawDashLine = function(ctx) {
  8036. // set style
  8037. ctx.strokeStyle = this.color;
  8038. ctx.lineWidth = this._getLineWidth();
  8039. // draw dashed line
  8040. ctx.beginPath();
  8041. ctx.lineCap = 'round';
  8042. if (this.dash.altLength != undefined) //If an alt dash value has been set add to the array this value
  8043. {
  8044. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  8045. [this.dash.length,this.dash.gap,this.dash.altLength,this.dash.gap]);
  8046. }
  8047. 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
  8048. {
  8049. ctx.dashedLine(this.from.x,this.from.y,this.to.x,this.to.y,
  8050. [this.dash.length,this.dash.gap]);
  8051. }
  8052. else //If all else fails draw a line
  8053. {
  8054. ctx.moveTo(this.from.x, this.from.y);
  8055. ctx.lineTo(this.to.x, this.to.y);
  8056. }
  8057. ctx.stroke();
  8058. // draw label
  8059. if (this.label) {
  8060. var point = this._pointOnLine(0.5);
  8061. this._label(ctx, this.label, point.x, point.y);
  8062. }
  8063. };
  8064. /**
  8065. * Get a point on a line
  8066. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  8067. * @return {Object} point
  8068. * @private
  8069. */
  8070. Edge.prototype._pointOnLine = function (percentage) {
  8071. return {
  8072. x: (1 - percentage) * this.from.x + percentage * this.to.x,
  8073. y: (1 - percentage) * this.from.y + percentage * this.to.y
  8074. }
  8075. };
  8076. /**
  8077. * Get a point on a circle
  8078. * @param {Number} x
  8079. * @param {Number} y
  8080. * @param {Number} radius
  8081. * @param {Number} percentage. Value between 0 (line start) and 1 (line end)
  8082. * @return {Object} point
  8083. * @private
  8084. */
  8085. Edge.prototype._pointOnCircle = function (x, y, radius, percentage) {
  8086. var angle = (percentage - 3/8) * 2 * Math.PI;
  8087. return {
  8088. x: x + radius * Math.cos(angle),
  8089. y: y - radius * Math.sin(angle)
  8090. }
  8091. };
  8092. /**
  8093. * Redraw a edge as a line with an arrow halfway the line
  8094. * Draw this edge in the given canvas
  8095. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8096. * @param {CanvasRenderingContext2D} ctx
  8097. * @private
  8098. */
  8099. Edge.prototype._drawArrowCenter = function(ctx) {
  8100. var point;
  8101. // set style
  8102. ctx.strokeStyle = this.color;
  8103. ctx.fillStyle = this.color;
  8104. ctx.lineWidth = this._getLineWidth();
  8105. if (this.from != this.to) {
  8106. // draw line
  8107. this._line(ctx);
  8108. // draw an arrow halfway the line
  8109. var angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  8110. var length = 10 + 5 * this.width; // TODO: make customizable?
  8111. point = this._pointOnLine(0.5);
  8112. ctx.arrow(point.x, point.y, angle, length);
  8113. ctx.fill();
  8114. ctx.stroke();
  8115. // draw label
  8116. if (this.label) {
  8117. point = this._pointOnLine(0.5);
  8118. this._label(ctx, this.label, point.x, point.y);
  8119. }
  8120. }
  8121. else {
  8122. // draw circle
  8123. var x, y;
  8124. var radius = this.length / 4;
  8125. var node = this.from;
  8126. if (!node.width) {
  8127. node.resize(ctx);
  8128. }
  8129. if (node.width > node.height) {
  8130. x = node.x + node.width / 2;
  8131. y = node.y - radius;
  8132. }
  8133. else {
  8134. x = node.x + radius;
  8135. y = node.y - node.height / 2;
  8136. }
  8137. this._circle(ctx, x, y, radius);
  8138. // draw all arrows
  8139. var angle = 0.2 * Math.PI;
  8140. var length = 10 + 5 * this.width; // TODO: make customizable?
  8141. point = this._pointOnCircle(x, y, radius, 0.5);
  8142. ctx.arrow(point.x, point.y, angle, length);
  8143. ctx.fill();
  8144. ctx.stroke();
  8145. // draw label
  8146. if (this.label) {
  8147. point = this._pointOnCircle(x, y, radius, 0.5);
  8148. this._label(ctx, this.label, point.x, point.y);
  8149. }
  8150. }
  8151. };
  8152. /**
  8153. * Redraw a edge as a line with an arrow
  8154. * Draw this edge in the given canvas
  8155. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  8156. * @param {CanvasRenderingContext2D} ctx
  8157. * @private
  8158. */
  8159. Edge.prototype._drawArrow = function(ctx) {
  8160. // set style
  8161. ctx.strokeStyle = this.color;
  8162. ctx.fillStyle = this.color;
  8163. ctx.lineWidth = this._getLineWidth();
  8164. // draw line
  8165. var angle, length;
  8166. if (this.from != this.to) {
  8167. // calculate length and angle of the line
  8168. angle = Math.atan2((this.to.y - this.from.y), (this.to.x - this.from.x));
  8169. var dx = (this.to.x - this.from.x);
  8170. var dy = (this.to.y - this.from.y);
  8171. var lEdge = Math.sqrt(dx * dx + dy * dy);
  8172. var lFrom = this.from.distanceToBorder(ctx, angle + Math.PI);
  8173. var pFrom = (lEdge - lFrom) / lEdge;
  8174. var xFrom = (pFrom) * this.from.x + (1 - pFrom) * this.to.x;
  8175. var yFrom = (pFrom) * this.from.y + (1 - pFrom) * this.to.y;
  8176. var lTo = this.to.distanceToBorder(ctx, angle);
  8177. var pTo = (lEdge - lTo) / lEdge;
  8178. var xTo = (1 - pTo) * this.from.x + pTo * this.to.x;
  8179. var yTo = (1 - pTo) * this.from.y + pTo * this.to.y;
  8180. ctx.beginPath();
  8181. ctx.moveTo(xFrom, yFrom);
  8182. ctx.lineTo(xTo, yTo);
  8183. ctx.stroke();
  8184. // draw arrow at the end of the line
  8185. length = 10 + 5 * this.width; // TODO: make customizable?
  8186. ctx.arrow(xTo, yTo, angle, length);
  8187. ctx.fill();
  8188. ctx.stroke();
  8189. // draw label
  8190. if (this.label) {
  8191. var point = this._pointOnLine(0.5);
  8192. this._label(ctx, this.label, point.x, point.y);
  8193. }
  8194. }
  8195. else {
  8196. // draw circle
  8197. var node = this.from;
  8198. var x, y, arrow;
  8199. var radius = this.length / 4;
  8200. if (!node.width) {
  8201. node.resize(ctx);
  8202. }
  8203. if (node.width > node.height) {
  8204. x = node.x + node.width / 2;
  8205. y = node.y - radius;
  8206. arrow = {
  8207. x: x,
  8208. y: node.y,
  8209. angle: 0.9 * Math.PI
  8210. };
  8211. }
  8212. else {
  8213. x = node.x + radius;
  8214. y = node.y - node.height / 2;
  8215. arrow = {
  8216. x: node.x,
  8217. y: y,
  8218. angle: 0.6 * Math.PI
  8219. };
  8220. }
  8221. ctx.beginPath();
  8222. // TODO: do not draw a circle, but an arc
  8223. // TODO: similarly, for a line without arrows, draw to the border of the nodes instead of the center
  8224. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  8225. ctx.stroke();
  8226. // draw all arrows
  8227. length = 10 + 5 * this.width; // TODO: make customizable?
  8228. ctx.arrow(arrow.x, arrow.y, arrow.angle, length);
  8229. ctx.fill();
  8230. ctx.stroke();
  8231. // draw label
  8232. if (this.label) {
  8233. point = this._pointOnCircle(x, y, radius, 0.5);
  8234. this._label(ctx, this.label, point.x, point.y);
  8235. }
  8236. }
  8237. };
  8238. /**
  8239. * Calculate the distance between a point (x3,y3) and a line segment from
  8240. * (x1,y1) to (x2,y2).
  8241. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  8242. * @param {number} x1
  8243. * @param {number} y1
  8244. * @param {number} x2
  8245. * @param {number} y2
  8246. * @param {number} x3
  8247. * @param {number} y3
  8248. * @private
  8249. */
  8250. Edge._dist = function (x1,y1, x2,y2, x3,y3) { // x3,y3 is the point
  8251. var px = x2-x1,
  8252. py = y2-y1,
  8253. something = px*px + py*py,
  8254. u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  8255. if (u > 1) {
  8256. u = 1;
  8257. }
  8258. else if (u < 0) {
  8259. u = 0;
  8260. }
  8261. var x = x1 + u * px,
  8262. y = y1 + u * py,
  8263. dx = x - x3,
  8264. dy = y - y3;
  8265. //# Note: If the actual distance does not matter,
  8266. //# if you only want to compare what this function
  8267. //# returns to other results of this function, you
  8268. //# can just return the squared distance instead
  8269. //# (i.e. remove the sqrt) to gain a little performance
  8270. return Math.sqrt(dx*dx + dy*dy);
  8271. };
  8272. /**
  8273. * Popup is a class to create a popup window with some text
  8274. * @param {Element} container The container object.
  8275. * @param {Number} [x]
  8276. * @param {Number} [y]
  8277. * @param {String} [text]
  8278. */
  8279. function Popup(container, x, y, text) {
  8280. if (container) {
  8281. this.container = container;
  8282. }
  8283. else {
  8284. this.container = document.body;
  8285. }
  8286. this.x = 0;
  8287. this.y = 0;
  8288. this.padding = 5;
  8289. if (x !== undefined && y !== undefined ) {
  8290. this.setPosition(x, y);
  8291. }
  8292. if (text !== undefined) {
  8293. this.setText(text);
  8294. }
  8295. // create the frame
  8296. this.frame = document.createElement("div");
  8297. var style = this.frame.style;
  8298. style.position = "absolute";
  8299. style.visibility = "hidden";
  8300. style.border = "1px solid #666";
  8301. style.color = "black";
  8302. style.padding = this.padding + "px";
  8303. style.backgroundColor = "#FFFFC6";
  8304. style.borderRadius = "3px";
  8305. style.MozBorderRadius = "3px";
  8306. style.WebkitBorderRadius = "3px";
  8307. style.boxShadow = "3px 3px 10px rgba(128, 128, 128, 0.5)";
  8308. style.whiteSpace = "nowrap";
  8309. this.container.appendChild(this.frame);
  8310. };
  8311. /**
  8312. * @param {number} x Horizontal position of the popup window
  8313. * @param {number} y Vertical position of the popup window
  8314. */
  8315. Popup.prototype.setPosition = function(x, y) {
  8316. this.x = parseInt(x);
  8317. this.y = parseInt(y);
  8318. };
  8319. /**
  8320. * Set the text for the popup window. This can be HTML code
  8321. * @param {string} text
  8322. */
  8323. Popup.prototype.setText = function(text) {
  8324. this.frame.innerHTML = text;
  8325. };
  8326. /**
  8327. * Show the popup window
  8328. * @param {boolean} show Optional. Show or hide the window
  8329. */
  8330. Popup.prototype.show = function (show) {
  8331. if (show === undefined) {
  8332. show = true;
  8333. }
  8334. if (show) {
  8335. var height = this.frame.clientHeight;
  8336. var width = this.frame.clientWidth;
  8337. var maxHeight = this.frame.parentNode.clientHeight;
  8338. var maxWidth = this.frame.parentNode.clientWidth;
  8339. var top = (this.y - height);
  8340. if (top + height + this.padding > maxHeight) {
  8341. top = maxHeight - height - this.padding;
  8342. }
  8343. if (top < this.padding) {
  8344. top = this.padding;
  8345. }
  8346. var left = this.x;
  8347. if (left + width + this.padding > maxWidth) {
  8348. left = maxWidth - width - this.padding;
  8349. }
  8350. if (left < this.padding) {
  8351. left = this.padding;
  8352. }
  8353. this.frame.style.left = left + "px";
  8354. this.frame.style.top = top + "px";
  8355. this.frame.style.visibility = "visible";
  8356. }
  8357. else {
  8358. this.hide();
  8359. }
  8360. };
  8361. /**
  8362. * Hide the popup window
  8363. */
  8364. Popup.prototype.hide = function () {
  8365. this.frame.style.visibility = "hidden";
  8366. };
  8367. /**
  8368. * @class Groups
  8369. * This class can store groups and properties specific for groups.
  8370. */
  8371. Groups = function () {
  8372. this.clear();
  8373. this.defaultIndex = 0;
  8374. };
  8375. /**
  8376. * default constants for group colors
  8377. */
  8378. Groups.DEFAULT = [
  8379. {border: "#2B7CE9", background: "#97C2FC", highlight: {border: "#2B7CE9", background: "#D2E5FF"}}, // blue
  8380. {border: "#FFA500", background: "#FFFF00", highlight: {border: "#FFA500", background: "#FFFFA3"}}, // yellow
  8381. {border: "#FA0A10", background: "#FB7E81", highlight: {border: "#FA0A10", background: "#FFAFB1"}}, // red
  8382. {border: "#41A906", background: "#7BE141", highlight: {border: "#41A906", background: "#A1EC76"}}, // green
  8383. {border: "#E129F0", background: "#EB7DF4", highlight: {border: "#E129F0", background: "#F0B3F5"}}, // magenta
  8384. {border: "#7C29F0", background: "#AD85E4", highlight: {border: "#7C29F0", background: "#D3BDF0"}}, // purple
  8385. {border: "#C37F00", background: "#FFA807", highlight: {border: "#C37F00", background: "#FFCA66"}}, // orange
  8386. {border: "#4220FB", background: "#6E6EFD", highlight: {border: "#4220FB", background: "#9B9BFD"}}, // darkblue
  8387. {border: "#FD5A77", background: "#FFC0CB", highlight: {border: "#FD5A77", background: "#FFD1D9"}}, // pink
  8388. {border: "#4AD63A", background: "#C2FABC", highlight: {border: "#4AD63A", background: "#E6FFE3"}} // mint
  8389. ];
  8390. /**
  8391. * Clear all groups
  8392. */
  8393. Groups.prototype.clear = function () {
  8394. this.groups = {};
  8395. this.groups.length = function()
  8396. {
  8397. var i = 0;
  8398. for ( var p in this ) {
  8399. if (this.hasOwnProperty(p)) {
  8400. i++;
  8401. }
  8402. }
  8403. return i;
  8404. }
  8405. };
  8406. /**
  8407. * get group properties of a groupname. If groupname is not found, a new group
  8408. * is added.
  8409. * @param {*} groupname Can be a number, string, Date, etc.
  8410. * @return {Object} group The created group, containing all group properties
  8411. */
  8412. Groups.prototype.get = function (groupname) {
  8413. var group = this.groups[groupname];
  8414. if (group == undefined) {
  8415. // create new group
  8416. var index = this.defaultIndex % Groups.DEFAULT.length;
  8417. this.defaultIndex++;
  8418. group = {};
  8419. group.color = Groups.DEFAULT[index];
  8420. this.groups[groupname] = group;
  8421. }
  8422. return group;
  8423. };
  8424. /**
  8425. * Add a custom group style
  8426. * @param {String} groupname
  8427. * @param {Object} style An object containing borderColor,
  8428. * backgroundColor, etc.
  8429. * @return {Object} group The created group object
  8430. */
  8431. Groups.prototype.add = function (groupname, style) {
  8432. this.groups[groupname] = style;
  8433. if (style.color) {
  8434. style.color = Node.parseColor(style.color);
  8435. }
  8436. return style;
  8437. };
  8438. /**
  8439. * @class Images
  8440. * This class loads images and keeps them stored.
  8441. */
  8442. Images = function () {
  8443. this.images = {};
  8444. this.callback = undefined;
  8445. };
  8446. /**
  8447. * Set an onload callback function. This will be called each time an image
  8448. * is loaded
  8449. * @param {function} callback
  8450. */
  8451. Images.prototype.setOnloadCallback = function(callback) {
  8452. this.callback = callback;
  8453. };
  8454. /**
  8455. *
  8456. * @param {string} url Url of the image
  8457. * @return {Image} img The image object
  8458. */
  8459. Images.prototype.load = function(url) {
  8460. var img = this.images[url];
  8461. if (img == undefined) {
  8462. // create the image
  8463. var images = this;
  8464. img = new Image();
  8465. this.images[url] = img;
  8466. img.onload = function() {
  8467. if (images.callback) {
  8468. images.callback(this);
  8469. }
  8470. };
  8471. img.src = url;
  8472. }
  8473. return img;
  8474. };
  8475. /**
  8476. * @constructor Graph
  8477. * Create a graph visualization, displaying nodes and edges.
  8478. *
  8479. * @param {Element} container The DOM element in which the Graph will
  8480. * be created. Normally a div element.
  8481. * @param {Object} data An object containing parameters
  8482. * {Array} nodes
  8483. * {Array} edges
  8484. * @param {Object} options Options
  8485. */
  8486. function Graph (container, data, options) {
  8487. // create variables and set default values
  8488. this.containerElement = container;
  8489. this.width = '100%';
  8490. this.height = '100%';
  8491. this.refreshRate = 50; // milliseconds
  8492. this.stabilize = true; // stabilize before displaying the graph
  8493. this.selectable = true;
  8494. // set constant values
  8495. this.constants = {
  8496. nodes: {
  8497. radiusMin: 5,
  8498. radiusMax: 20,
  8499. radius: 5,
  8500. distance: 100, // px
  8501. shape: 'ellipse',
  8502. image: undefined,
  8503. widthMin: 16, // px
  8504. widthMax: 64, // px
  8505. fontColor: 'black',
  8506. fontSize: 14, // px
  8507. //fontFace: verdana,
  8508. fontFace: 'arial',
  8509. color: {
  8510. border: '#2B7CE9',
  8511. background: '#97C2FC',
  8512. highlight: {
  8513. border: '#2B7CE9',
  8514. background: '#D2E5FF'
  8515. }
  8516. },
  8517. borderColor: '#2B7CE9',
  8518. backgroundColor: '#97C2FC',
  8519. highlightColor: '#D2E5FF',
  8520. group: undefined
  8521. },
  8522. edges: {
  8523. widthMin: 1,
  8524. widthMax: 15,
  8525. width: 1,
  8526. style: 'line',
  8527. color: '#343434',
  8528. fontColor: '#343434',
  8529. fontSize: 14, // px
  8530. fontFace: 'arial',
  8531. //distance: 100, //px
  8532. length: 100, // px
  8533. dash: {
  8534. length: 10,
  8535. gap: 5,
  8536. altLength: undefined
  8537. }
  8538. },
  8539. minForce: 0.05,
  8540. minVelocity: 0.02, // px/s
  8541. maxIterations: 1000 // maximum number of iteration to stabilize
  8542. };
  8543. var graph = this;
  8544. this.nodes = {}; // object with Node objects
  8545. this.edges = {}; // object with Edge objects
  8546. // TODO: create a counter to keep track on the number of nodes having values
  8547. // TODO: create a counter to keep track on the number of nodes currently moving
  8548. // TODO: create a counter to keep track on the number of edges having values
  8549. this.nodesData = null; // A DataSet or DataView
  8550. this.edgesData = null; // A DataSet or DataView
  8551. // create event listeners used to subscribe on the DataSets of the nodes and edges
  8552. var me = this;
  8553. this.nodesListeners = {
  8554. 'add': function (event, params) {
  8555. me._addNodes(params.items);
  8556. me.start();
  8557. },
  8558. 'update': function (event, params) {
  8559. me._updateNodes(params.items);
  8560. me.start();
  8561. },
  8562. 'remove': function (event, params) {
  8563. me._removeNodes(params.items);
  8564. me.start();
  8565. }
  8566. };
  8567. this.edgesListeners = {
  8568. 'add': function (event, params) {
  8569. me._addEdges(params.items);
  8570. me.start();
  8571. },
  8572. 'update': function (event, params) {
  8573. me._updateEdges(params.items);
  8574. me.start();
  8575. },
  8576. 'remove': function (event, params) {
  8577. me._removeEdges(params.items);
  8578. me.start();
  8579. }
  8580. };
  8581. this.groups = new Groups(); // object with groups
  8582. this.images = new Images(); // object with images
  8583. this.images.setOnloadCallback(function () {
  8584. graph._redraw();
  8585. });
  8586. // properties of the data
  8587. this.moving = false; // True if any of the nodes have an undefined position
  8588. this.selection = [];
  8589. this.timer = undefined;
  8590. // create a frame and canvas
  8591. this._create();
  8592. // apply options
  8593. this.setOptions(options);
  8594. // draw data
  8595. this.setData(data);
  8596. }
  8597. /**
  8598. * Set nodes and edges, and optionally options as well.
  8599. *
  8600. * @param {Object} data Object containing parameters:
  8601. * {Array | DataSet | DataView} [nodes] Array with nodes
  8602. * {Array | DataSet | DataView} [edges] Array with edges
  8603. * {String} [dot] String containing data in DOT format
  8604. * {Options} [options] Object with options
  8605. */
  8606. Graph.prototype.setData = function(data) {
  8607. if (data && data.dot && (data.nodes || data.edges)) {
  8608. throw new SyntaxError('Data must contain either parameter "dot" or ' +
  8609. ' parameter pair "nodes" and "edges", but not both.');
  8610. }
  8611. // set options
  8612. this.setOptions(data && data.options);
  8613. // set all data
  8614. if (data && data.dot) {
  8615. // parse DOT file
  8616. if(data && data.dot) {
  8617. var dotData = vis.util.DOTToGraph(data.dot);
  8618. this.setData(dotData);
  8619. return;
  8620. }
  8621. }
  8622. else {
  8623. this._setNodes(data && data.nodes);
  8624. this._setEdges(data && data.edges);
  8625. }
  8626. // find a stable position or start animating to a stable position
  8627. if (this.stabilize) {
  8628. this._doStabilize();
  8629. }
  8630. this.start();
  8631. };
  8632. /**
  8633. * Set options
  8634. * @param {Object} options
  8635. */
  8636. Graph.prototype.setOptions = function (options) {
  8637. if (options) {
  8638. // retrieve parameter values
  8639. if (options.width != undefined) {this.width = options.width;}
  8640. if (options.height != undefined) {this.height = options.height;}
  8641. if (options.stabilize != undefined) {this.stabilize = options.stabilize;}
  8642. if (options.selectable != undefined) {this.selectable = options.selectable;}
  8643. // TODO: work out these options and document them
  8644. if (options.edges) {
  8645. for (var prop in options.edges) {
  8646. if (options.edges.hasOwnProperty(prop)) {
  8647. this.constants.edges[prop] = options.edges[prop];
  8648. }
  8649. }
  8650. if (options.edges.length != undefined &&
  8651. options.nodes && options.nodes.distance == undefined) {
  8652. this.constants.edges.length = options.edges.length;
  8653. this.constants.nodes.distance = options.edges.length * 1.25;
  8654. }
  8655. if (!options.edges.fontColor) {
  8656. this.constants.edges.fontColor = options.edges.color;
  8657. }
  8658. // Added to support dashed lines
  8659. // David Jordan
  8660. // 2012-08-08
  8661. if (options.edges.dash) {
  8662. if (options.edges.dash.length != undefined) {
  8663. this.constants.edges.dash.length = options.edges.dash.length;
  8664. }
  8665. if (options.edges.dash.gap != undefined) {
  8666. this.constants.edges.dash.gap = options.edges.dash.gap;
  8667. }
  8668. if (options.edges.dash.altLength != undefined) {
  8669. this.constants.edges.dash.altLength = options.edges.dash.altLength;
  8670. }
  8671. }
  8672. }
  8673. if (options.nodes) {
  8674. for (prop in options.nodes) {
  8675. if (options.nodes.hasOwnProperty(prop)) {
  8676. this.constants.nodes[prop] = options.nodes[prop];
  8677. }
  8678. }
  8679. if (options.nodes.color) {
  8680. this.constants.nodes.color = Node.parseColor(options.nodes.color);
  8681. }
  8682. /*
  8683. if (options.nodes.widthMin) this.constants.nodes.radiusMin = options.nodes.widthMin;
  8684. if (options.nodes.widthMax) this.constants.nodes.radiusMax = options.nodes.widthMax;
  8685. */
  8686. }
  8687. if (options.groups) {
  8688. for (var groupname in options.groups) {
  8689. if (options.groups.hasOwnProperty(groupname)) {
  8690. var group = options.groups[groupname];
  8691. this.groups.add(groupname, group);
  8692. }
  8693. }
  8694. }
  8695. }
  8696. this.setSize(this.width, this.height);
  8697. this._setTranslation(this.frame.clientWidth / 2, this.frame.clientHeight / 2);
  8698. this._setScale(1);
  8699. };
  8700. /**
  8701. * fire an event
  8702. * @param {String} event The name of an event, for example "select"
  8703. * @param {Object} params Optional object with event parameters
  8704. * @private
  8705. */
  8706. Graph.prototype._trigger = function (event, params) {
  8707. events.trigger(this, event, params);
  8708. };
  8709. /**
  8710. * Create the main frame for the Graph.
  8711. * This function is executed once when a Graph object is created. The frame
  8712. * contains a canvas, and this canvas contains all objects like the axis and
  8713. * nodes.
  8714. * @private
  8715. */
  8716. Graph.prototype._create = function () {
  8717. // remove all elements from the container element.
  8718. while (this.containerElement.hasChildNodes()) {
  8719. this.containerElement.removeChild(this.containerElement.firstChild);
  8720. }
  8721. this.frame = document.createElement("div");
  8722. this.frame.className = "graph-frame";
  8723. this.frame.style.position = "relative";
  8724. this.frame.style.overflow = "hidden";
  8725. // create the graph canvas (HTML canvas element)
  8726. this.frame.canvas = document.createElement( "canvas" );
  8727. this.frame.canvas.style.position = "relative";
  8728. this.frame.appendChild(this.frame.canvas);
  8729. if (!this.frame.canvas.getContext) {
  8730. var noCanvas = document.createElement( "DIV" );
  8731. noCanvas.style.color = "red";
  8732. noCanvas.style.fontWeight = "bold" ;
  8733. noCanvas.style.padding = "10px";
  8734. noCanvas.innerHTML = "Error: your browser does not support HTML canvas";
  8735. this.frame.canvas.appendChild(noCanvas);
  8736. }
  8737. // create event listeners
  8738. var me = this;
  8739. var onmousedown = function (event) {me._onMouseDown(event);};
  8740. var onmousemove = function (event) {me._onMouseMoveTitle(event);};
  8741. var onmousewheel = function (event) {me._onMouseWheel(event);};
  8742. var ontouchstart = function (event) {me._onTouchStart(event);};
  8743. vis.util.addEventListener(this.frame.canvas, "mousedown", onmousedown);
  8744. vis.util.addEventListener(this.frame.canvas, "mousemove", onmousemove);
  8745. vis.util.addEventListener(this.frame.canvas, "mousewheel", onmousewheel);
  8746. vis.util.addEventListener(this.frame.canvas, "touchstart", ontouchstart);
  8747. // add the frame to the container element
  8748. this.containerElement.appendChild(this.frame);
  8749. };
  8750. /**
  8751. * handle on mouse down event
  8752. * @private
  8753. */
  8754. Graph.prototype._onMouseDown = function (event) {
  8755. event = event || window.event;
  8756. if (!this.selectable) {
  8757. return;
  8758. }
  8759. // check if mouse is still down (may be up when focus is lost for example
  8760. // in an iframe)
  8761. if (this.leftButtonDown) {
  8762. this._onMouseUp(event);
  8763. }
  8764. // only react on left mouse button down
  8765. this.leftButtonDown = event.which ? (event.which == 1) : (event.button == 1);
  8766. if (!this.leftButtonDown && !this.touchDown) {
  8767. return;
  8768. }
  8769. // add event listeners to handle moving the contents
  8770. // we store the function onmousemove and onmouseup in the timeline, so we can
  8771. // remove the eventlisteners lateron in the function mouseUp()
  8772. var me = this;
  8773. if (!this.onmousemove) {
  8774. this.onmousemove = function (event) {me._onMouseMove(event);};
  8775. vis.util.addEventListener(document, "mousemove", me.onmousemove);
  8776. }
  8777. if (!this.onmouseup) {
  8778. this.onmouseup = function (event) {me._onMouseUp(event);};
  8779. vis.util.addEventListener(document, "mouseup", me.onmouseup);
  8780. }
  8781. vis.util.preventDefault(event);
  8782. // store the start x and y position of the mouse
  8783. this.startMouseX = util.getPageX(event);
  8784. this.startMouseY = util.getPageY(event);
  8785. this.startFrameLeft = vis.util.getAbsoluteLeft(this.frame.canvas);
  8786. this.startFrameTop = vis.util.getAbsoluteTop(this.frame.canvas);
  8787. this.startTranslation = this._getTranslation();
  8788. this.ctrlKeyDown = event.ctrlKey;
  8789. this.shiftKeyDown = event.shiftKey;
  8790. var obj = {
  8791. left: this._xToCanvas(this.startMouseX - this.startFrameLeft),
  8792. top: this._yToCanvas(this.startMouseY - this.startFrameTop),
  8793. right: this._xToCanvas(this.startMouseX - this.startFrameLeft),
  8794. bottom: this._yToCanvas(this.startMouseY - this.startFrameTop)
  8795. };
  8796. var overlappingNodes = this._getNodesOverlappingWith(obj);
  8797. // if there are overlapping nodes, select the last one, this is the
  8798. // one which is drawn on top of the others
  8799. this.startClickedObj = (overlappingNodes.length > 0) ?
  8800. overlappingNodes[overlappingNodes.length - 1] : undefined;
  8801. if (this.startClickedObj) {
  8802. // move clicked node with the mouse
  8803. // make the clicked node temporarily fixed, and store their original state
  8804. var node = this.nodes[this.startClickedObj];
  8805. this.startClickedObj.xFixed = node.xFixed;
  8806. this.startClickedObj.yFixed = node.yFixed;
  8807. node.xFixed = true;
  8808. node.yFixed = true;
  8809. if (!this.ctrlKeyDown || !node.isSelected()) {
  8810. // select this node
  8811. this._selectNodes([this.startClickedObj], this.ctrlKeyDown);
  8812. }
  8813. else {
  8814. // unselect this node
  8815. this._unselectNodes([this.startClickedObj]);
  8816. }
  8817. if (!this.moving) {
  8818. this._redraw();
  8819. }
  8820. }
  8821. else if (this.shiftKeyDown) {
  8822. // start selection of multiple nodes
  8823. }
  8824. else {
  8825. // start moving the graph
  8826. this.moved = false;
  8827. }
  8828. };
  8829. /**
  8830. * handle on mouse move event
  8831. * @param {Event} event
  8832. * @private
  8833. */
  8834. Graph.prototype._onMouseMove = function (event) {
  8835. event = event || window.event;
  8836. if (!this.selectable) {
  8837. return;
  8838. }
  8839. var mouseX = util.getPageX(event);
  8840. var mouseY = util.getPageY(event);
  8841. this.mouseX = mouseX;
  8842. this.mouseY = mouseY;
  8843. if (this.startClickedObj) {
  8844. var node = this.nodes[this.startClickedObj];
  8845. if (!this.startClickedObj.xFixed)
  8846. node.x = this._xToCanvas(mouseX - this.startFrameLeft);
  8847. if (!this.startClickedObj.yFixed)
  8848. node.y = this._yToCanvas(mouseY - this.startFrameTop);
  8849. // start animation if not yet running
  8850. if (!this.moving) {
  8851. this.moving = true;
  8852. this.start();
  8853. }
  8854. }
  8855. else if (this.shiftKeyDown) {
  8856. // draw a rect from start mouse location to current mouse location
  8857. if (this.frame.selRect == undefined) {
  8858. this.frame.selRect = document.createElement("DIV");
  8859. this.frame.appendChild(this.frame.selRect);
  8860. this.frame.selRect.style.position = "absolute";
  8861. this.frame.selRect.style.border = "1px dashed red";
  8862. }
  8863. var left = Math.min(this.startMouseX, mouseX) - this.startFrameLeft;
  8864. var top = Math.min(this.startMouseY, mouseY) - this.startFrameTop;
  8865. var right = Math.max(this.startMouseX, mouseX) - this.startFrameLeft;
  8866. var bottom = Math.max(this.startMouseY, mouseY) - this.startFrameTop;
  8867. this.frame.selRect.style.left = left + "px";
  8868. this.frame.selRect.style.top = top + "px";
  8869. this.frame.selRect.style.width = (right - left) + "px";
  8870. this.frame.selRect.style.height = (bottom - top) + "px";
  8871. }
  8872. else {
  8873. // move the graph
  8874. var diffX = mouseX - this.startMouseX;
  8875. var diffY = mouseY - this.startMouseY;
  8876. this._setTranslation(
  8877. this.startTranslation.x + diffX,
  8878. this.startTranslation.y + diffY);
  8879. this._redraw();
  8880. this.moved = true;
  8881. }
  8882. vis.util.preventDefault(event);
  8883. };
  8884. /**
  8885. * handle on mouse up event
  8886. * @param {Event} event
  8887. * @private
  8888. */
  8889. Graph.prototype._onMouseUp = function (event) {
  8890. event = event || window.event;
  8891. if (!this.selectable) {
  8892. return;
  8893. }
  8894. // remove event listeners here, important for Safari
  8895. if (this.onmousemove) {
  8896. vis.util.removeEventListener(document, "mousemove", this.onmousemove);
  8897. this.onmousemove = undefined;
  8898. }
  8899. if (this.onmouseup) {
  8900. vis.util.removeEventListener(document, "mouseup", this.onmouseup);
  8901. this.onmouseup = undefined;
  8902. }
  8903. vis.util.preventDefault(event);
  8904. // check selected nodes
  8905. var endMouseX = util.getPageX(event) || this.mouseX || 0;
  8906. var endMouseY = util.getPageY(event) || this.mouseY || 0;
  8907. var ctrlKey = event ? event.ctrlKey : window.event.ctrlKey;
  8908. if (this.startClickedObj) {
  8909. // restore the original fixed state
  8910. var node = this.nodes[this.startClickedObj];
  8911. node.xFixed = this.startClickedObj.xFixed;
  8912. node.yFixed = this.startClickedObj.yFixed;
  8913. }
  8914. else if (this.shiftKeyDown) {
  8915. // select nodes inside selection area
  8916. var obj = {
  8917. "left": this._xToCanvas(Math.min(this.startMouseX, endMouseX) - this.startFrameLeft),
  8918. "top": this._yToCanvas(Math.min(this.startMouseY, endMouseY) - this.startFrameTop),
  8919. "right": this._xToCanvas(Math.max(this.startMouseX, endMouseX) - this.startFrameLeft),
  8920. "bottom": this._yToCanvas(Math.max(this.startMouseY, endMouseY) - this.startFrameTop)
  8921. };
  8922. var overlappingNodes = this._getNodesOverlappingWith(obj);
  8923. this._selectNodes(overlappingNodes, ctrlKey);
  8924. this.redraw();
  8925. // remove the selection rectangle
  8926. if (this.frame.selRect) {
  8927. this.frame.removeChild(this.frame.selRect);
  8928. this.frame.selRect = undefined;
  8929. }
  8930. }
  8931. else {
  8932. if (!this.ctrlKeyDown && !this.moved) {
  8933. // remove selection
  8934. this._unselectNodes();
  8935. this._redraw();
  8936. }
  8937. }
  8938. this.leftButtonDown = false;
  8939. this.ctrlKeyDown = false;
  8940. };
  8941. /**
  8942. * Event handler for mouse wheel event, used to zoom the timeline
  8943. * Code from http://adomas.org/javascript-mouse-wheel/
  8944. * @param {Event} event
  8945. * @private
  8946. */
  8947. Graph.prototype._onMouseWheel = function(event) {
  8948. event = event || window.event;
  8949. var mouseX = util.getPageX(event);
  8950. var mouseY = util.getPageY(event);
  8951. // retrieve delta
  8952. var delta = 0;
  8953. if (event.wheelDelta) { /* IE/Opera. */
  8954. delta = event.wheelDelta/120;
  8955. } else if (event.detail) { /* Mozilla case. */
  8956. // In Mozilla, sign of delta is different than in IE.
  8957. // Also, delta is multiple of 3.
  8958. delta = -event.detail/3;
  8959. }
  8960. // If delta is nonzero, handle it.
  8961. // Basically, delta is now positive if wheel was scrolled up,
  8962. // and negative, if wheel was scrolled down.
  8963. if (delta) {
  8964. // determine zoom factor, and adjust the zoom factor such that zooming in
  8965. // and zooming out correspond wich each other
  8966. var zoom = delta / 10;
  8967. if (delta < 0) {
  8968. zoom = zoom / (1 - zoom);
  8969. }
  8970. var scaleOld = this._getScale();
  8971. var scaleNew = scaleOld * (1 + zoom);
  8972. if (scaleNew < 0.01) {
  8973. scaleNew = 0.01;
  8974. }
  8975. if (scaleNew > 10) {
  8976. scaleNew = 10;
  8977. }
  8978. var frameLeft = vis.util.getAbsoluteLeft(this.frame.canvas);
  8979. var frameTop = vis.util.getAbsoluteTop(this.frame.canvas);
  8980. var x = mouseX - frameLeft;
  8981. var y = mouseY - frameTop;
  8982. var translation = this._getTranslation();
  8983. var scaleFrac = scaleNew / scaleOld;
  8984. var tx = (1 - scaleFrac) * x + translation.x * scaleFrac;
  8985. var ty = (1 - scaleFrac) * y + translation.y * scaleFrac;
  8986. this._setScale(scaleNew);
  8987. this._setTranslation(tx, ty);
  8988. this._redraw();
  8989. }
  8990. // Prevent default actions caused by mouse wheel.
  8991. // That might be ugly, but we handle scrolls somehow
  8992. // anyway, so don't bother here...
  8993. vis.util.preventDefault(event);
  8994. };
  8995. /**
  8996. * Mouse move handler for checking whether the title moves over a node with a title.
  8997. * @param {Event} event
  8998. * @private
  8999. */
  9000. Graph.prototype._onMouseMoveTitle = function (event) {
  9001. event = event || window.event;
  9002. var startMouseX = util.getPageX(event);
  9003. var startMouseY = util.getPageY(event);
  9004. this.startFrameLeft = this.startFrameLeft || vis.util.getAbsoluteLeft(this.frame.canvas);
  9005. this.startFrameTop = this.startFrameTop || vis.util.getAbsoluteTop(this.frame.canvas);
  9006. var x = startMouseX - this.startFrameLeft;
  9007. var y = startMouseY - this.startFrameTop;
  9008. // check if the previously selected node is still selected
  9009. if (this.popupNode) {
  9010. this._checkHidePopup(x, y);
  9011. }
  9012. // start a timeout that will check if the mouse is positioned above
  9013. // an element
  9014. var me = this;
  9015. var checkShow = function() {
  9016. me._checkShowPopup(x, y);
  9017. };
  9018. if (this.popupTimer) {
  9019. clearInterval(this.popupTimer); // stop any running timer
  9020. }
  9021. if (!this.leftButtonDown) {
  9022. this.popupTimer = setTimeout(checkShow, 300);
  9023. }
  9024. };
  9025. /**
  9026. * Check if there is an element on the given position in the graph
  9027. * (a node or edge). If so, and if this element has a title,
  9028. * show a popup window with its title.
  9029. *
  9030. * @param {number} x
  9031. * @param {number} y
  9032. * @private
  9033. */
  9034. Graph.prototype._checkShowPopup = function (x, y) {
  9035. var obj = {
  9036. "left" : this._xToCanvas(x),
  9037. "top" : this._yToCanvas(y),
  9038. "right" : this._xToCanvas(x),
  9039. "bottom" : this._yToCanvas(y)
  9040. };
  9041. var id;
  9042. var lastPopupNode = this.popupNode;
  9043. if (this.popupNode == undefined) {
  9044. // search the nodes for overlap, select the top one in case of multiple nodes
  9045. var nodes = this.nodes;
  9046. for (id in nodes) {
  9047. if (nodes.hasOwnProperty(id)) {
  9048. var node = nodes[id];
  9049. if (node.getTitle() != undefined && node.isOverlappingWith(obj)) {
  9050. this.popupNode = node;
  9051. break;
  9052. }
  9053. }
  9054. }
  9055. }
  9056. if (this.popupNode == undefined) {
  9057. // search the edges for overlap
  9058. var edges = this.edges;
  9059. for (id in edges) {
  9060. if (edges.hasOwnProperty(id)) {
  9061. var edge = edges[id];
  9062. if (edge.connected && (edge.getTitle() != undefined) &&
  9063. edge.isOverlappingWith(obj)) {
  9064. this.popupNode = edge;
  9065. break;
  9066. }
  9067. }
  9068. }
  9069. }
  9070. if (this.popupNode) {
  9071. // show popup message window
  9072. if (this.popupNode != lastPopupNode) {
  9073. var me = this;
  9074. if (!me.popup) {
  9075. me.popup = new Popup(me.frame);
  9076. }
  9077. // adjust a small offset such that the mouse cursor is located in the
  9078. // bottom left location of the popup, and you can easily move over the
  9079. // popup area
  9080. me.popup.setPosition(x - 3, y - 3);
  9081. me.popup.setText(me.popupNode.getTitle());
  9082. me.popup.show();
  9083. }
  9084. }
  9085. else {
  9086. if (this.popup) {
  9087. this.popup.hide();
  9088. }
  9089. }
  9090. };
  9091. /**
  9092. * Check if the popup must be hided, which is the case when the mouse is no
  9093. * longer hovering on the object
  9094. * @param {number} x
  9095. * @param {number} y
  9096. * @private
  9097. */
  9098. Graph.prototype._checkHidePopup = function (x, y) {
  9099. var obj = {
  9100. "left" : x,
  9101. "top" : y,
  9102. "right" : x,
  9103. "bottom" : y
  9104. };
  9105. if (!this.popupNode || !this.popupNode.isOverlappingWith(obj) ) {
  9106. this.popupNode = undefined;
  9107. if (this.popup) {
  9108. this.popup.hide();
  9109. }
  9110. }
  9111. };
  9112. /**
  9113. * Event handler for touchstart event on mobile devices
  9114. * @param {Event} event
  9115. * @private
  9116. */
  9117. Graph.prototype._onTouchStart = function(event) {
  9118. vis.util.preventDefault(event);
  9119. if (this.touchDown) {
  9120. // if already moving, return
  9121. return;
  9122. }
  9123. this.touchDown = true;
  9124. var me = this;
  9125. if (!this.ontouchmove) {
  9126. this.ontouchmove = function (event) {me._onTouchMove(event);};
  9127. vis.util.addEventListener(document, "touchmove", this.ontouchmove);
  9128. }
  9129. if (!this.ontouchend) {
  9130. this.ontouchend = function (event) {me._onTouchEnd(event);};
  9131. vis.util.addEventListener(document, "touchend", this.ontouchend);
  9132. }
  9133. this._onMouseDown(event);
  9134. };
  9135. /**
  9136. * Event handler for touchmove event on mobile devices
  9137. * @param {Event} event
  9138. * @private
  9139. */
  9140. Graph.prototype._onTouchMove = function(event) {
  9141. vis.util.preventDefault(event);
  9142. this._onMouseMove(event);
  9143. };
  9144. /**
  9145. * Event handler for touchend event on mobile devices
  9146. * @param {Event} event
  9147. * @private
  9148. */
  9149. Graph.prototype._onTouchEnd = function(event) {
  9150. vis.util.preventDefault(event);
  9151. this.touchDown = false;
  9152. if (this.ontouchmove) {
  9153. vis.util.removeEventListener(document, "touchmove", this.ontouchmove);
  9154. this.ontouchmove = undefined;
  9155. }
  9156. if (this.ontouchend) {
  9157. vis.util.removeEventListener(document, "touchend", this.ontouchend);
  9158. this.ontouchend = undefined;
  9159. }
  9160. this._onMouseUp(event);
  9161. };
  9162. /**
  9163. * Unselect selected nodes. If no selection array is provided, all nodes
  9164. * are unselected
  9165. * @param {Object[]} selection Array with selection objects, each selection
  9166. * object has a parameter row. Optional
  9167. * @param {Boolean} triggerSelect If true (default), the select event
  9168. * is triggered when nodes are unselected
  9169. * @return {Boolean} changed True if the selection is changed
  9170. * @private
  9171. */
  9172. Graph.prototype._unselectNodes = function(selection, triggerSelect) {
  9173. var changed = false;
  9174. var i, iMax, id;
  9175. if (selection) {
  9176. // remove provided selections
  9177. for (i = 0, iMax = selection.length; i < iMax; i++) {
  9178. id = selection[i];
  9179. this.nodes[id].unselect();
  9180. var j = 0;
  9181. while (j < this.selection.length) {
  9182. if (this.selection[j] == id) {
  9183. this.selection.splice(j, 1);
  9184. changed = true;
  9185. }
  9186. else {
  9187. j++;
  9188. }
  9189. }
  9190. }
  9191. }
  9192. else if (this.selection && this.selection.length) {
  9193. // remove all selections
  9194. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  9195. id = this.selection[i];
  9196. this.nodes[id].unselect();
  9197. changed = true;
  9198. }
  9199. this.selection = [];
  9200. }
  9201. if (changed && (triggerSelect == true || triggerSelect == undefined)) {
  9202. // fire the select event
  9203. this._trigger('select');
  9204. }
  9205. return changed;
  9206. };
  9207. /**
  9208. * select all nodes on given location x, y
  9209. * @param {Array} selection an array with node ids
  9210. * @param {boolean} append If true, the new selection will be appended to the
  9211. * current selection (except for duplicate entries)
  9212. * @return {Boolean} changed True if the selection is changed
  9213. * @private
  9214. */
  9215. Graph.prototype._selectNodes = function(selection, append) {
  9216. var changed = false;
  9217. var i, iMax;
  9218. // TODO: the selectNodes method is a little messy, rework this
  9219. // check if the current selection equals the desired selection
  9220. var selectionAlreadyThere = true;
  9221. if (selection.length != this.selection.length) {
  9222. selectionAlreadyThere = false;
  9223. }
  9224. else {
  9225. for (i = 0, iMax = Math.min(selection.length, this.selection.length); i < iMax; i++) {
  9226. if (selection[i] != this.selection[i]) {
  9227. selectionAlreadyThere = false;
  9228. break;
  9229. }
  9230. }
  9231. }
  9232. if (selectionAlreadyThere) {
  9233. return changed;
  9234. }
  9235. if (append == undefined || append == false) {
  9236. // first deselect any selected node
  9237. var triggerSelect = false;
  9238. changed = this._unselectNodes(undefined, triggerSelect);
  9239. }
  9240. for (i = 0, iMax = selection.length; i < iMax; i++) {
  9241. // add each of the new selections, but only when they are not duplicate
  9242. var id = selection[i];
  9243. var isDuplicate = (this.selection.indexOf(id) != -1);
  9244. if (!isDuplicate) {
  9245. this.nodes[id].select();
  9246. this.selection.push(id);
  9247. changed = true;
  9248. }
  9249. }
  9250. if (changed) {
  9251. // fire the select event
  9252. this._trigger('select');
  9253. }
  9254. return changed;
  9255. };
  9256. /**
  9257. * retrieve all nodes overlapping with given object
  9258. * @param {Object} obj An object with parameters left, top, right, bottom
  9259. * @return {Object[]} An array with selection objects containing
  9260. * the parameter row.
  9261. * @private
  9262. */
  9263. Graph.prototype._getNodesOverlappingWith = function (obj) {
  9264. var nodes = this.nodes,
  9265. overlappingNodes = [];
  9266. for (var id in nodes) {
  9267. if (nodes.hasOwnProperty(id)) {
  9268. if (nodes[id].isOverlappingWith(obj)) {
  9269. overlappingNodes.push(id);
  9270. }
  9271. }
  9272. }
  9273. return overlappingNodes;
  9274. };
  9275. /**
  9276. * retrieve the currently selected nodes
  9277. * @return {Number[] | String[]} selection An array with the ids of the
  9278. * selected nodes.
  9279. */
  9280. Graph.prototype.getSelection = function() {
  9281. return this.selection.concat([]);
  9282. };
  9283. /**
  9284. * select zero or more nodes
  9285. * @param {Number[] | String[]} selection An array with the ids of the
  9286. * selected nodes.
  9287. */
  9288. Graph.prototype.setSelection = function(selection) {
  9289. var i, iMax, id;
  9290. if (selection.length == undefined)
  9291. throw "Selection must be an array with ids";
  9292. // first unselect any selected node
  9293. for (i = 0, iMax = this.selection.length; i < iMax; i++) {
  9294. id = this.selection[i];
  9295. this.nodes[id].unselect();
  9296. }
  9297. this.selection = [];
  9298. for (i = 0, iMax = selection.length; i < iMax; i++) {
  9299. id = selection[i];
  9300. var node = this.nodes[id];
  9301. if (!node) {
  9302. throw new RangeError('Node with id "' + id + '" not found');
  9303. }
  9304. node.select();
  9305. this.selection.push(id);
  9306. }
  9307. this.redraw();
  9308. };
  9309. /**
  9310. * Validate the selection: remove ids of nodes which no longer exist
  9311. * @private
  9312. */
  9313. Graph.prototype._updateSelection = function () {
  9314. var i = 0;
  9315. while (i < this.selection.length) {
  9316. var id = this.selection[i];
  9317. if (!this.nodes[id]) {
  9318. this.selection.splice(i, 1);
  9319. }
  9320. else {
  9321. i++;
  9322. }
  9323. }
  9324. };
  9325. /**
  9326. * Temporary method to test calculating a hub value for the nodes
  9327. * @param {number} level Maximum number edges between two nodes in order
  9328. * to call them connected. Optional, 1 by default
  9329. * @return {Number[]} connectioncount array with the connection count
  9330. * for each node
  9331. * @private
  9332. */
  9333. Graph.prototype._getConnectionCount = function(level) {
  9334. if (level == undefined) {
  9335. level = 1;
  9336. }
  9337. // get the nodes connected to given nodes
  9338. function getConnectedNodes(nodes) {
  9339. var connectedNodes = [];
  9340. for (var j = 0, jMax = nodes.length; j < jMax; j++) {
  9341. var node = nodes[j];
  9342. // find all nodes connected to this node
  9343. var edges = node.edges;
  9344. for (var i = 0, iMax = edges.length; i < iMax; i++) {
  9345. var edge = edges[i];
  9346. var other = null;
  9347. // check if connected
  9348. if (edge.from == node)
  9349. other = edge.to;
  9350. else if (edge.to == node)
  9351. other = edge.from;
  9352. // check if the other node is not already in the list with nodes
  9353. var k, kMax;
  9354. if (other) {
  9355. for (k = 0, kMax = nodes.length; k < kMax; k++) {
  9356. if (nodes[k] == other) {
  9357. other = null;
  9358. break;
  9359. }
  9360. }
  9361. }
  9362. if (other) {
  9363. for (k = 0, kMax = connectedNodes.length; k < kMax; k++) {
  9364. if (connectedNodes[k] == other) {
  9365. other = null;
  9366. break;
  9367. }
  9368. }
  9369. }
  9370. if (other)
  9371. connectedNodes.push(other);
  9372. }
  9373. }
  9374. return connectedNodes;
  9375. }
  9376. var connections = [];
  9377. var nodes = this.nodes;
  9378. for (var id in nodes) {
  9379. if (nodes.hasOwnProperty(id)) {
  9380. var c = [nodes[id]];
  9381. for (var l = 0; l < level; l++) {
  9382. c = c.concat(getConnectedNodes(c));
  9383. }
  9384. connections.push(c);
  9385. }
  9386. }
  9387. var hubs = [];
  9388. for (var i = 0, len = connections.length; i < len; i++) {
  9389. hubs.push(connections[i].length);
  9390. }
  9391. return hubs;
  9392. };
  9393. /**
  9394. * Set a new size for the graph
  9395. * @param {string} width Width in pixels or percentage (for example "800px"
  9396. * or "50%")
  9397. * @param {string} height Height in pixels or percentage (for example "400px"
  9398. * or "30%")
  9399. */
  9400. Graph.prototype.setSize = function(width, height) {
  9401. this.frame.style.width = width;
  9402. this.frame.style.height = height;
  9403. this.frame.canvas.style.width = "100%";
  9404. this.frame.canvas.style.height = "100%";
  9405. this.frame.canvas.width = this.frame.canvas.clientWidth;
  9406. this.frame.canvas.height = this.frame.canvas.clientHeight;
  9407. };
  9408. /**
  9409. * Set a data set with nodes for the graph
  9410. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  9411. * @private
  9412. */
  9413. Graph.prototype._setNodes = function(nodes) {
  9414. var oldNodesData = this.nodesData;
  9415. if (nodes instanceof DataSet || nodes instanceof DataView) {
  9416. this.nodesData = nodes;
  9417. }
  9418. else if (nodes instanceof Array) {
  9419. this.nodesData = new DataSet();
  9420. this.nodesData.add(nodes);
  9421. }
  9422. else if (!nodes) {
  9423. this.nodesData = new DataSet();
  9424. }
  9425. else {
  9426. throw new TypeError('Array or DataSet expected');
  9427. }
  9428. if (oldNodesData) {
  9429. // unsubscribe from old dataset
  9430. util.forEach(this.nodesListeners, function (callback, event) {
  9431. oldNodesData.unsubscribe(event, callback);
  9432. });
  9433. }
  9434. // remove drawn nodes
  9435. this.nodes = {};
  9436. if (this.nodesData) {
  9437. // subscribe to new dataset
  9438. var me = this;
  9439. util.forEach(this.nodesListeners, function (callback, event) {
  9440. me.nodesData.subscribe(event, callback);
  9441. });
  9442. // draw all new nodes
  9443. var ids = this.nodesData.getIds();
  9444. this._addNodes(ids);
  9445. }
  9446. this._updateSelection();
  9447. };
  9448. /**
  9449. * Add nodes
  9450. * @param {Number[] | String[]} ids
  9451. * @private
  9452. */
  9453. Graph.prototype._addNodes = function(ids) {
  9454. var id;
  9455. for (var i = 0, len = ids.length; i < len; i++) {
  9456. id = ids[i];
  9457. var data = this.nodesData.get(id);
  9458. var node = new Node(data, this.images, this.groups, this.constants);
  9459. this.nodes[id] = node; // note: this may replace an existing node
  9460. if (!node.isFixed()) {
  9461. // TODO: position new nodes in a smarter way!
  9462. var radius = this.constants.edges.length * 2;
  9463. var count = ids.length;
  9464. var angle = 2 * Math.PI * (i / count);
  9465. node.x = radius * Math.cos(angle);
  9466. node.y = radius * Math.sin(angle);
  9467. // note: no not use node.isMoving() here, as that gives the current
  9468. // velocity of the node, which is zero after creation of the node.
  9469. this.moving = true;
  9470. }
  9471. }
  9472. this._reconnectEdges();
  9473. this._updateValueRange(this.nodes);
  9474. };
  9475. /**
  9476. * Update existing nodes, or create them when not yet existing
  9477. * @param {Number[] | String[]} ids
  9478. * @private
  9479. */
  9480. Graph.prototype._updateNodes = function(ids) {
  9481. var nodes = this.nodes,
  9482. nodesData = this.nodesData;
  9483. for (var i = 0, len = ids.length; i < len; i++) {
  9484. var id = ids[i];
  9485. var node = nodes[id];
  9486. var data = nodesData.get(id);
  9487. if (node) {
  9488. // update node
  9489. node.setProperties(data, this.constants);
  9490. }
  9491. else {
  9492. // create node
  9493. node = new Node(properties, this.images, this.groups, this.constants);
  9494. nodes[id] = node;
  9495. if (!node.isFixed()) {
  9496. this.moving = true;
  9497. }
  9498. }
  9499. }
  9500. this._reconnectEdges();
  9501. this._updateValueRange(nodes);
  9502. };
  9503. /**
  9504. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  9505. * @param {Number[] | String[]} ids
  9506. * @private
  9507. */
  9508. Graph.prototype._removeNodes = function(ids) {
  9509. var nodes = this.nodes;
  9510. for (var i = 0, len = ids.length; i < len; i++) {
  9511. var id = ids[i];
  9512. delete nodes[id];
  9513. }
  9514. this._reconnectEdges();
  9515. this._updateSelection();
  9516. this._updateValueRange(nodes);
  9517. };
  9518. /**
  9519. * Load edges by reading the data table
  9520. * @param {Array | DataSet | DataView} edges The data containing the edges.
  9521. * @private
  9522. * @private
  9523. */
  9524. Graph.prototype._setEdges = function(edges) {
  9525. var oldEdgesData = this.edgesData;
  9526. if (edges instanceof DataSet || edges instanceof DataView) {
  9527. this.edgesData = edges;
  9528. }
  9529. else if (edges instanceof Array) {
  9530. this.edgesData = new DataSet();
  9531. this.edgesData.add(edges);
  9532. }
  9533. else if (!edges) {
  9534. this.edgesData = new DataSet();
  9535. }
  9536. else {
  9537. throw new TypeError('Array or DataSet expected');
  9538. }
  9539. if (oldEdgesData) {
  9540. // unsubscribe from old dataset
  9541. util.forEach(this.edgesListeners, function (callback, event) {
  9542. oldEdgesData.unsubscribe(event, callback);
  9543. });
  9544. }
  9545. // remove drawn edges
  9546. this.edges = {};
  9547. if (this.edgesData) {
  9548. // subscribe to new dataset
  9549. var me = this;
  9550. util.forEach(this.edgesListeners, function (callback, event) {
  9551. me.edgesData.subscribe(event, callback);
  9552. });
  9553. // draw all new nodes
  9554. var ids = this.edgesData.getIds();
  9555. this._addEdges(ids);
  9556. }
  9557. this._reconnectEdges();
  9558. };
  9559. /**
  9560. * Add edges
  9561. * @param {Number[] | String[]} ids
  9562. * @private
  9563. */
  9564. Graph.prototype._addEdges = function (ids) {
  9565. var edges = this.edges,
  9566. edgesData = this.edgesData;
  9567. for (var i = 0, len = ids.length; i < len; i++) {
  9568. var id = ids[i];
  9569. var oldEdge = edges[id];
  9570. if (oldEdge) {
  9571. oldEdge.disconnect();
  9572. }
  9573. var data = edgesData.get(id);
  9574. edges[id] = new Edge(data, this, this.constants);
  9575. }
  9576. this.moving = true;
  9577. this._updateValueRange(edges);
  9578. };
  9579. /**
  9580. * Update existing edges, or create them when not yet existing
  9581. * @param {Number[] | String[]} ids
  9582. * @private
  9583. */
  9584. Graph.prototype._updateEdges = function (ids) {
  9585. var edges = this.edges,
  9586. edgesData = this.edgesData;
  9587. for (var i = 0, len = ids.length; i < len; i++) {
  9588. var id = ids[i];
  9589. var data = edgesData.get(id);
  9590. var edge = edges[id];
  9591. if (edge) {
  9592. // update edge
  9593. edge.disconnect();
  9594. edge.setProperties(data, this.constants);
  9595. edge.connect();
  9596. }
  9597. else {
  9598. // create edge
  9599. edge = new Edge(data, this, this.constants);
  9600. this.edges[id] = edge;
  9601. }
  9602. }
  9603. this.moving = true;
  9604. this._updateValueRange(edges);
  9605. };
  9606. /**
  9607. * Remove existing edges. Non existing ids will be ignored
  9608. * @param {Number[] | String[]} ids
  9609. * @private
  9610. */
  9611. Graph.prototype._removeEdges = function (ids) {
  9612. var edges = this.edges;
  9613. for (var i = 0, len = ids.length; i < len; i++) {
  9614. var id = ids[i];
  9615. var edge = edges[id];
  9616. if (edge) {
  9617. edge.disconnect();
  9618. delete edges[id];
  9619. }
  9620. }
  9621. this.moving = true;
  9622. this._updateValueRange(edges);
  9623. };
  9624. /**
  9625. * Reconnect all edges
  9626. * @private
  9627. */
  9628. Graph.prototype._reconnectEdges = function() {
  9629. var id,
  9630. nodes = this.nodes,
  9631. edges = this.edges;
  9632. for (id in nodes) {
  9633. if (nodes.hasOwnProperty(id)) {
  9634. nodes[id].edges = [];
  9635. }
  9636. }
  9637. for (id in edges) {
  9638. if (edges.hasOwnProperty(id)) {
  9639. var edge = edges[id];
  9640. edge.from = null;
  9641. edge.to = null;
  9642. edge.connect();
  9643. }
  9644. }
  9645. };
  9646. /**
  9647. * Update the values of all object in the given array according to the current
  9648. * value range of the objects in the array.
  9649. * @param {Object} obj An object containing a set of Edges or Nodes
  9650. * The objects must have a method getValue() and
  9651. * setValueRange(min, max).
  9652. * @private
  9653. */
  9654. Graph.prototype._updateValueRange = function(obj) {
  9655. var id;
  9656. // determine the range of the objects
  9657. var valueMin = undefined;
  9658. var valueMax = undefined;
  9659. for (id in obj) {
  9660. if (obj.hasOwnProperty(id)) {
  9661. var value = obj[id].getValue();
  9662. if (value !== undefined) {
  9663. valueMin = (valueMin === undefined) ? value : Math.min(value, valueMin);
  9664. valueMax = (valueMax === undefined) ? value : Math.max(value, valueMax);
  9665. }
  9666. }
  9667. }
  9668. // adjust the range of all objects
  9669. if (valueMin !== undefined && valueMax !== undefined) {
  9670. for (id in obj) {
  9671. if (obj.hasOwnProperty(id)) {
  9672. obj[id].setValueRange(valueMin, valueMax);
  9673. }
  9674. }
  9675. }
  9676. };
  9677. /**
  9678. * Redraw the graph with the current data
  9679. * chart will be resized too.
  9680. */
  9681. Graph.prototype.redraw = function() {
  9682. this.setSize(this.width, this.height);
  9683. this._redraw();
  9684. };
  9685. /**
  9686. * Redraw the graph with the current data
  9687. * @private
  9688. */
  9689. Graph.prototype._redraw = function() {
  9690. var ctx = this.frame.canvas.getContext("2d");
  9691. // clear the canvas
  9692. var w = this.frame.canvas.width;
  9693. var h = this.frame.canvas.height;
  9694. ctx.clearRect(0, 0, w, h);
  9695. // set scaling and translation
  9696. ctx.save();
  9697. ctx.translate(this.translation.x, this.translation.y);
  9698. ctx.scale(this.scale, this.scale);
  9699. this._drawEdges(ctx);
  9700. this._drawNodes(ctx);
  9701. // restore original scaling and translation
  9702. ctx.restore();
  9703. };
  9704. /**
  9705. * Set the translation of the graph
  9706. * @param {Number} offsetX Horizontal offset
  9707. * @param {Number} offsetY Vertical offset
  9708. * @private
  9709. */
  9710. Graph.prototype._setTranslation = function(offsetX, offsetY) {
  9711. if (this.translation === undefined) {
  9712. this.translation = {
  9713. "x": 0,
  9714. "y": 0
  9715. };
  9716. }
  9717. if (offsetX !== undefined) {
  9718. this.translation.x = offsetX;
  9719. }
  9720. if (offsetY !== undefined) {
  9721. this.translation.y = offsetY;
  9722. }
  9723. };
  9724. /**
  9725. * Get the translation of the graph
  9726. * @return {Object} translation An object with parameters x and y, both a number
  9727. * @private
  9728. */
  9729. Graph.prototype._getTranslation = function() {
  9730. return {
  9731. "x": this.translation.x,
  9732. "y": this.translation.y
  9733. };
  9734. };
  9735. /**
  9736. * Scale the graph
  9737. * @param {Number} scale Scaling factor 1.0 is unscaled
  9738. * @private
  9739. */
  9740. Graph.prototype._setScale = function(scale) {
  9741. this.scale = scale;
  9742. };
  9743. /**
  9744. * Get the current scale of the graph
  9745. * @return {Number} scale Scaling factor 1.0 is unscaled
  9746. * @private
  9747. */
  9748. Graph.prototype._getScale = function() {
  9749. return this.scale;
  9750. };
  9751. Graph.prototype._xToCanvas = function(x) {
  9752. return (x - this.translation.x) / this.scale;
  9753. };
  9754. Graph.prototype._canvasToX = function(x) {
  9755. return x * this.scale + this.translation.x;
  9756. };
  9757. Graph.prototype._yToCanvas = function(y) {
  9758. return (y - this.translation.y) / this.scale;
  9759. };
  9760. Graph.prototype._canvasToY = function(y) {
  9761. return y * this.scale + this.translation.y ;
  9762. };
  9763. /**
  9764. * Redraw all nodes
  9765. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9766. * @param {CanvasRenderingContext2D} ctx
  9767. * @private
  9768. */
  9769. Graph.prototype._drawNodes = function(ctx) {
  9770. // first draw the unselected nodes
  9771. var nodes = this.nodes;
  9772. var selected = [];
  9773. for (var id in nodes) {
  9774. if (nodes.hasOwnProperty(id)) {
  9775. if (nodes[id].isSelected()) {
  9776. selected.push(id);
  9777. }
  9778. else {
  9779. nodes[id].draw(ctx);
  9780. }
  9781. }
  9782. }
  9783. // draw the selected nodes on top
  9784. for (var s = 0, sMax = selected.length; s < sMax; s++) {
  9785. nodes[selected[s]].draw(ctx);
  9786. }
  9787. };
  9788. /**
  9789. * Redraw all edges
  9790. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  9791. * @param {CanvasRenderingContext2D} ctx
  9792. * @private
  9793. */
  9794. Graph.prototype._drawEdges = function(ctx) {
  9795. var edges = this.edges;
  9796. for (var id in edges) {
  9797. if (edges.hasOwnProperty(id)) {
  9798. var edge = edges[id];
  9799. if (edge.connected) {
  9800. edges[id].draw(ctx);
  9801. }
  9802. }
  9803. }
  9804. };
  9805. /**
  9806. * Find a stable position for all nodes
  9807. * @private
  9808. */
  9809. Graph.prototype._doStabilize = function() {
  9810. var start = new Date();
  9811. // find stable position
  9812. var count = 0;
  9813. var vmin = this.constants.minVelocity;
  9814. var stable = false;
  9815. while (!stable && count < this.constants.maxIterations) {
  9816. this._calculateForces();
  9817. this._discreteStepNodes();
  9818. stable = !this._isMoving(vmin);
  9819. count++;
  9820. }
  9821. var end = new Date();
  9822. // console.log("Stabilized in " + (end-start) + " ms, " + count + " iterations" ); // TODO: cleanup
  9823. };
  9824. /**
  9825. * Calculate the external forces acting on the nodes
  9826. * Forces are caused by: edges, repulsing forces between nodes, gravity
  9827. * @private
  9828. */
  9829. Graph.prototype._calculateForces = function() {
  9830. // create a local edge to the nodes and edges, that is faster
  9831. var id, dx, dy, angle, distance, fx, fy,
  9832. repulsingForce, springForce, length, edgeLength,
  9833. nodes = this.nodes,
  9834. edges = this.edges;
  9835. // gravity, add a small constant force to pull the nodes towards the center of
  9836. // the graph
  9837. // Also, the forces are reset to zero in this loop by using _setForce instead
  9838. // of _addForce
  9839. var gravity = 0.01,
  9840. gx = this.frame.canvas.clientWidth / 2,
  9841. gy = this.frame.canvas.clientHeight / 2;
  9842. for (id in nodes) {
  9843. if (nodes.hasOwnProperty(id)) {
  9844. var node = nodes[id];
  9845. dx = gx - node.x;
  9846. dy = gy - node.y;
  9847. angle = Math.atan2(dy, dx);
  9848. fx = Math.cos(angle) * gravity;
  9849. fy = Math.sin(angle) * gravity;
  9850. node._setForce(fx, fy);
  9851. }
  9852. }
  9853. // repulsing forces between nodes
  9854. var minimumDistance = this.constants.nodes.distance,
  9855. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  9856. for (var id1 in nodes) {
  9857. if (nodes.hasOwnProperty(id1)) {
  9858. var node1 = nodes[id1];
  9859. for (var id2 in nodes) {
  9860. if (nodes.hasOwnProperty(id2)) {
  9861. var node2 = nodes[id2];
  9862. // calculate normally distributed force
  9863. dx = node2.x - node1.x;
  9864. dy = node2.y - node1.y;
  9865. distance = Math.sqrt(dx * dx + dy * dy);
  9866. angle = Math.atan2(dy, dx);
  9867. // TODO: correct factor for repulsing force
  9868. //repulsingForce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  9869. //repulsingForce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  9870. repulsingForce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)); // TODO: customize the repulsing force
  9871. fx = Math.cos(angle) * repulsingForce;
  9872. fy = Math.sin(angle) * repulsingForce;
  9873. node1._addForce(-fx, -fy);
  9874. node2._addForce(fx, fy);
  9875. }
  9876. }
  9877. }
  9878. }
  9879. /* TODO: re-implement repulsion of edges
  9880. for (var n = 0; n < nodes.length; n++) {
  9881. for (var l = 0; l < edges.length; l++) {
  9882. var lx = edges[l].from.x+(edges[l].to.x - edges[l].from.x)/2,
  9883. ly = edges[l].from.y+(edges[l].to.y - edges[l].from.y)/2,
  9884. // calculate normally distributed force
  9885. dx = nodes[n].x - lx,
  9886. dy = nodes[n].y - ly,
  9887. distance = Math.sqrt(dx * dx + dy * dy),
  9888. angle = Math.atan2(dy, dx),
  9889. // TODO: correct factor for repulsing force
  9890. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  9891. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  9892. repulsingforce = 1 / (1 + Math.exp((distance / (minimumDistance / 2) - 1) * steepness)), // TODO: customize the repulsing force
  9893. fx = Math.cos(angle) * repulsingforce,
  9894. fy = Math.sin(angle) * repulsingforce;
  9895. nodes[n]._addForce(fx, fy);
  9896. edges[l].from._addForce(-fx/2,-fy/2);
  9897. edges[l].to._addForce(-fx/2,-fy/2);
  9898. }
  9899. }
  9900. */
  9901. // forces caused by the edges, modelled as springs
  9902. for (id in edges) {
  9903. if (edges.hasOwnProperty(id)) {
  9904. var edge = edges[id];
  9905. if (edge.connected) {
  9906. dx = (edge.to.x - edge.from.x);
  9907. dy = (edge.to.y - edge.from.y);
  9908. //edgeLength = (edge.from.width + edge.from.height + edge.to.width + edge.to.height)/2 || edge.length; // TODO: dmin
  9909. //edgeLength = (edge.from.width + edge.to.width)/2 || edge.length; // TODO: dmin
  9910. //edgeLength = 20 + ((edge.from.width + edge.to.width) || 0) / 2;
  9911. edgeLength = edge.length;
  9912. length = Math.sqrt(dx * dx + dy * dy);
  9913. angle = Math.atan2(dy, dx);
  9914. springForce = edge.stiffness * (edgeLength - length);
  9915. fx = Math.cos(angle) * springForce;
  9916. fy = Math.sin(angle) * springForce;
  9917. edge.from._addForce(-fx, -fy);
  9918. edge.to._addForce(fx, fy);
  9919. }
  9920. }
  9921. }
  9922. /* TODO: re-implement repulsion of edges
  9923. // repulsing forces between edges
  9924. var minimumDistance = this.constants.edges.distance,
  9925. steepness = 10; // higher value gives steeper slope of the force around the given minimumDistance
  9926. for (var l = 0; l < edges.length; l++) {
  9927. //Keep distance from other edge centers
  9928. for (var l2 = l + 1; l2 < this.edges.length; l2++) {
  9929. //var dmin = (nodes[n].width + nodes[n].height + nodes[n2].width + nodes[n2].height) / 1 || minimumDistance, // TODO: dmin
  9930. //var dmin = (nodes[n].width + nodes[n2].width)/2 || minimumDistance, // TODO: dmin
  9931. //dmin = 40 + ((nodes[n].width/2 + nodes[n2].width/2) || 0),
  9932. var lx = edges[l].from.x+(edges[l].to.x - edges[l].from.x)/2,
  9933. ly = edges[l].from.y+(edges[l].to.y - edges[l].from.y)/2,
  9934. l2x = edges[l2].from.x+(edges[l2].to.x - edges[l2].from.x)/2,
  9935. l2y = edges[l2].from.y+(edges[l2].to.y - edges[l2].from.y)/2,
  9936. // calculate normally distributed force
  9937. dx = l2x - lx,
  9938. dy = l2y - ly,
  9939. distance = Math.sqrt(dx * dx + dy * dy),
  9940. angle = Math.atan2(dy, dx),
  9941. // TODO: correct factor for repulsing force
  9942. //var repulsingforce = 2 * Math.exp(-5 * (distance * distance) / (dmin * dmin) ); // TODO: customize the repulsing force
  9943. //repulsingforce = Math.exp(-1 * (distance * distance) / (dmin * dmin) ), // TODO: customize the repulsing force
  9944. repulsingforce = 1 / (1 + Math.exp((distance / minimumDistance - 1) * steepness)), // TODO: customize the repulsing force
  9945. fx = Math.cos(angle) * repulsingforce,
  9946. fy = Math.sin(angle) * repulsingforce;
  9947. edges[l].from._addForce(-fx, -fy);
  9948. edges[l].to._addForce(-fx, -fy);
  9949. edges[l2].from._addForce(fx, fy);
  9950. edges[l2].to._addForce(fx, fy);
  9951. }
  9952. }
  9953. */
  9954. };
  9955. /**
  9956. * Check if any of the nodes is still moving
  9957. * @param {number} vmin the minimum velocity considered as "moving"
  9958. * @return {boolean} true if moving, false if non of the nodes is moving
  9959. * @private
  9960. */
  9961. Graph.prototype._isMoving = function(vmin) {
  9962. // TODO: ismoving does not work well: should check the kinetic energy, not its velocity
  9963. var nodes = this.nodes;
  9964. for (var id in nodes) {
  9965. if (nodes.hasOwnProperty(id) && nodes[id].isMoving(vmin)) {
  9966. return true;
  9967. }
  9968. }
  9969. return false;
  9970. };
  9971. /**
  9972. * Perform one discrete step for all nodes
  9973. * @private
  9974. */
  9975. Graph.prototype._discreteStepNodes = function() {
  9976. var interval = this.refreshRate / 1000.0; // in seconds
  9977. var nodes = this.nodes;
  9978. for (var id in nodes) {
  9979. if (nodes.hasOwnProperty(id)) {
  9980. nodes[id].discreteStep(interval);
  9981. }
  9982. }
  9983. };
  9984. /**
  9985. * Start animating nodes and edges
  9986. */
  9987. Graph.prototype.start = function() {
  9988. if (this.moving) {
  9989. this._calculateForces();
  9990. this._discreteStepNodes();
  9991. var vmin = this.constants.minVelocity;
  9992. this.moving = this._isMoving(vmin);
  9993. }
  9994. if (this.moving) {
  9995. // start animation. only start timer if it is not already running
  9996. if (!this.timer) {
  9997. var graph = this;
  9998. this.timer = window.setTimeout(function () {
  9999. graph.timer = undefined;
  10000. graph.start();
  10001. graph._redraw();
  10002. }, this.refreshRate);
  10003. }
  10004. }
  10005. else {
  10006. this._redraw();
  10007. }
  10008. };
  10009. /**
  10010. * Stop animating nodes and edges.
  10011. */
  10012. Graph.prototype.stop = function () {
  10013. if (this.timer) {
  10014. window.clearInterval(this.timer);
  10015. this.timer = undefined;
  10016. }
  10017. };
  10018. /**
  10019. * vis.js module exports
  10020. */
  10021. var vis = {
  10022. util: util,
  10023. events: events,
  10024. Controller: Controller,
  10025. DataSet: DataSet,
  10026. DataView: DataView,
  10027. Range: Range,
  10028. Stack: Stack,
  10029. TimeStep: TimeStep,
  10030. EventBus: EventBus,
  10031. components: {
  10032. items: {
  10033. Item: Item,
  10034. ItemBox: ItemBox,
  10035. ItemPoint: ItemPoint,
  10036. ItemRange: ItemRange
  10037. },
  10038. Component: Component,
  10039. Panel: Panel,
  10040. RootPanel: RootPanel,
  10041. ItemSet: ItemSet,
  10042. TimeAxis: TimeAxis
  10043. },
  10044. graph: {
  10045. Node: Node,
  10046. Edge: Edge,
  10047. Popup: Popup,
  10048. Groups: Groups,
  10049. Images: Images
  10050. },
  10051. Timeline: Timeline,
  10052. Graph: Graph
  10053. };
  10054. /**
  10055. * CommonJS module exports
  10056. */
  10057. if (typeof exports !== 'undefined') {
  10058. exports = vis;
  10059. }
  10060. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  10061. module.exports = vis;
  10062. }
  10063. /**
  10064. * AMD module exports
  10065. */
  10066. if (typeof(define) === 'function') {
  10067. define(function () {
  10068. return vis;
  10069. });
  10070. }
  10071. /**
  10072. * Window exports
  10073. */
  10074. if (typeof window !== 'undefined') {
  10075. // attach the module to the window, load as a regular javascript file
  10076. window['vis'] = vis;
  10077. }
  10078. // inject css
  10079. util.loadCss("/* vis.js stylesheet */\n.vis.timeline {\n}\n\n\n.vis.timeline.rootpanel {\n position: relative;\n overflow: hidden;\n\n border: 1px solid #bfbfbf;\n -moz-box-sizing: border-box;\n box-sizing: border-box;\n}\n\n.vis.timeline .panel {\n position: absolute;\n overflow: hidden;\n}\n\n\n.vis.timeline .groupset {\n position: absolute;\n padding: 0;\n margin: 0;\n}\n\n.vis.timeline .labels {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n\n padding: 0;\n margin: 0;\n\n border-right: 1px solid #bfbfbf;\n box-sizing: border-box;\n -moz-box-sizing: border-box;\n}\n\n.vis.timeline .labels .label {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n border-bottom: 1px solid #bfbfbf;\n color: #4d4d4d;\n}\n\n.vis.timeline .labels .label .inner {\n display: inline-block;\n padding: 5px;\n}\n\n\n.vis.timeline .itemset {\n position: absolute;\n padding: 0;\n margin: 0;\n overflow: hidden;\n}\n\n.vis.timeline .background {\n}\n\n.vis.timeline .foreground {\n}\n\n.vis.timeline .itemset-axis {\n position: absolute;\n}\n\n.vis.timeline .groupset .itemset-axis {\n border-top: 1px solid #bfbfbf;\n}\n\n/* TODO: with orientation=='bottom', this will more or less overlap with timeline axis\n.vis.timeline .groupset .itemset-axis:last-child {\n border-top: none;\n}\n*/\n\n\n.vis.timeline .item {\n position: absolute;\n color: #1A1A1A;\n border-color: #97B0F8;\n background-color: #D5DDF6;\n display: inline-block;\n}\n\n.vis.timeline .item.selected {\n border-color: #FFC200;\n background-color: #FFF785;\n z-index: 999;\n}\n\n.vis.timeline .item.cluster {\n /* TODO: use another color or pattern? */\n background: #97B0F8 url('img/cluster_bg.png');\n color: white;\n}\n.vis.timeline .item.cluster.point {\n border-color: #D5DDF6;\n}\n\n.vis.timeline .item.box {\n text-align: center;\n border-style: solid;\n border-width: 1px;\n border-radius: 5px;\n -moz-border-radius: 5px; /* For Firefox 3.6 and older */\n}\n\n.vis.timeline .item.point {\n background: none;\n}\n\n.vis.timeline .dot {\n border: 5px solid #97B0F8;\n position: absolute;\n border-radius: 5px;\n -moz-border-radius: 5px; /* For Firefox 3.6 and older */\n}\n\n.vis.timeline .item.range {\n overflow: hidden;\n border-style: solid;\n border-width: 1px;\n border-radius: 2px;\n -moz-border-radius: 2px; /* For Firefox 3.6 and older */\n}\n\n.vis.timeline .item.range .drag-left {\n cursor: w-resize;\n z-index: 1000;\n}\n\n.vis.timeline .item.range .drag-right {\n cursor: e-resize;\n z-index: 1000;\n}\n\n.vis.timeline .item.range .content {\n position: relative;\n display: inline-block;\n}\n\n.vis.timeline .item.line {\n position: absolute;\n width: 0;\n border-left-width: 1px;\n border-left-style: solid;\n}\n\n.vis.timeline .item .content {\n margin: 5px;\n white-space: nowrap;\n overflow: hidden;\n}\n\n.vis.timeline .axis {\n position: relative;\n}\n\n.vis.timeline .axis .text {\n position: absolute;\n color: #4d4d4d;\n padding: 3px;\n white-space: nowrap;\n}\n\n.vis.timeline .axis .text.measure {\n position: absolute;\n padding-left: 0;\n padding-right: 0;\n margin-left: 0;\n margin-right: 0;\n visibility: hidden;\n}\n\n.vis.timeline .axis .grid.vertical {\n position: absolute;\n width: 0;\n border-right: 1px solid;\n}\n\n.vis.timeline .axis .grid.horizontal {\n position: absolute;\n left: 0;\n width: 100%;\n height: 0;\n border-bottom: 1px solid;\n}\n\n.vis.timeline .axis .grid.minor {\n border-color: #e5e5e5;\n}\n\n.vis.timeline .axis .grid.major {\n border-color: #bfbfbf;\n}\n\n");
  10080. })()
  10081. },{"moment":2}],2:[function(require,module,exports){
  10082. (function(){// moment.js
  10083. // version : 2.0.0
  10084. // author : Tim Wood
  10085. // license : MIT
  10086. // momentjs.com
  10087. (function (undefined) {
  10088. /************************************
  10089. Constants
  10090. ************************************/
  10091. var moment,
  10092. VERSION = "2.0.0",
  10093. round = Math.round, i,
  10094. // internal storage for language config files
  10095. languages = {},
  10096. // check for nodeJS
  10097. hasModule = (typeof module !== 'undefined' && module.exports),
  10098. // ASP.NET json date format regex
  10099. aspNetJsonRegex = /^\/?Date\((\-?\d+)/i,
  10100. // format tokens
  10101. 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,
  10102. localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,
  10103. // parsing tokens
  10104. parseMultipleFormatChunker = /([0-9a-zA-Z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)/gi,
  10105. // parsing token regexes
  10106. parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99
  10107. parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999
  10108. parseTokenThreeDigits = /\d{3}/, // 000 - 999
  10109. parseTokenFourDigits = /\d{1,4}/, // 0 - 9999
  10110. parseTokenSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999
  10111. 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.
  10112. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/i, // +00:00 -00:00 +0000 -0000 or Z
  10113. parseTokenT = /T/i, // T (ISO seperator)
  10114. parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
  10115. // preliminary iso regex
  10116. // 0000-00-00 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000
  10117. isoRegex = /^\s*\d{4}-\d\d-\d\d((T| )(\d\d(:\d\d(:\d\d(\.\d\d?\d?)?)?)?)?([\+\-]\d\d:?\d\d)?)?/,
  10118. isoFormat = 'YYYY-MM-DDTHH:mm:ssZ',
  10119. // iso time formats and regexes
  10120. isoTimes = [
  10121. ['HH:mm:ss.S', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/],
  10122. ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/],
  10123. ['HH:mm', /(T| )\d\d:\d\d/],
  10124. ['HH', /(T| )\d\d/]
  10125. ],
  10126. // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"]
  10127. parseTimezoneChunker = /([\+\-]|\d\d)/gi,
  10128. // getter and setter names
  10129. proxyGettersAndSetters = 'Month|Date|Hours|Minutes|Seconds|Milliseconds'.split('|'),
  10130. unitMillisecondFactors = {
  10131. 'Milliseconds' : 1,
  10132. 'Seconds' : 1e3,
  10133. 'Minutes' : 6e4,
  10134. 'Hours' : 36e5,
  10135. 'Days' : 864e5,
  10136. 'Months' : 2592e6,
  10137. 'Years' : 31536e6
  10138. },
  10139. // format function strings
  10140. formatFunctions = {},
  10141. // tokens to ordinalize and pad
  10142. ordinalizeTokens = 'DDD w W M D d'.split(' '),
  10143. paddedTokens = 'M D H h m s w W'.split(' '),
  10144. formatTokenFunctions = {
  10145. M : function () {
  10146. return this.month() + 1;
  10147. },
  10148. MMM : function (format) {
  10149. return this.lang().monthsShort(this, format);
  10150. },
  10151. MMMM : function (format) {
  10152. return this.lang().months(this, format);
  10153. },
  10154. D : function () {
  10155. return this.date();
  10156. },
  10157. DDD : function () {
  10158. return this.dayOfYear();
  10159. },
  10160. d : function () {
  10161. return this.day();
  10162. },
  10163. dd : function (format) {
  10164. return this.lang().weekdaysMin(this, format);
  10165. },
  10166. ddd : function (format) {
  10167. return this.lang().weekdaysShort(this, format);
  10168. },
  10169. dddd : function (format) {
  10170. return this.lang().weekdays(this, format);
  10171. },
  10172. w : function () {
  10173. return this.week();
  10174. },
  10175. W : function () {
  10176. return this.isoWeek();
  10177. },
  10178. YY : function () {
  10179. return leftZeroFill(this.year() % 100, 2);
  10180. },
  10181. YYYY : function () {
  10182. return leftZeroFill(this.year(), 4);
  10183. },
  10184. YYYYY : function () {
  10185. return leftZeroFill(this.year(), 5);
  10186. },
  10187. a : function () {
  10188. return this.lang().meridiem(this.hours(), this.minutes(), true);
  10189. },
  10190. A : function () {
  10191. return this.lang().meridiem(this.hours(), this.minutes(), false);
  10192. },
  10193. H : function () {
  10194. return this.hours();
  10195. },
  10196. h : function () {
  10197. return this.hours() % 12 || 12;
  10198. },
  10199. m : function () {
  10200. return this.minutes();
  10201. },
  10202. s : function () {
  10203. return this.seconds();
  10204. },
  10205. S : function () {
  10206. return ~~(this.milliseconds() / 100);
  10207. },
  10208. SS : function () {
  10209. return leftZeroFill(~~(this.milliseconds() / 10), 2);
  10210. },
  10211. SSS : function () {
  10212. return leftZeroFill(this.milliseconds(), 3);
  10213. },
  10214. Z : function () {
  10215. var a = -this.zone(),
  10216. b = "+";
  10217. if (a < 0) {
  10218. a = -a;
  10219. b = "-";
  10220. }
  10221. return b + leftZeroFill(~~(a / 60), 2) + ":" + leftZeroFill(~~a % 60, 2);
  10222. },
  10223. ZZ : function () {
  10224. var a = -this.zone(),
  10225. b = "+";
  10226. if (a < 0) {
  10227. a = -a;
  10228. b = "-";
  10229. }
  10230. return b + leftZeroFill(~~(10 * a / 6), 4);
  10231. },
  10232. X : function () {
  10233. return this.unix();
  10234. }
  10235. };
  10236. function padToken(func, count) {
  10237. return function (a) {
  10238. return leftZeroFill(func.call(this, a), count);
  10239. };
  10240. }
  10241. function ordinalizeToken(func) {
  10242. return function (a) {
  10243. return this.lang().ordinal(func.call(this, a));
  10244. };
  10245. }
  10246. while (ordinalizeTokens.length) {
  10247. i = ordinalizeTokens.pop();
  10248. formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i]);
  10249. }
  10250. while (paddedTokens.length) {
  10251. i = paddedTokens.pop();
  10252. formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2);
  10253. }
  10254. formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3);
  10255. /************************************
  10256. Constructors
  10257. ************************************/
  10258. function Language() {
  10259. }
  10260. // Moment prototype object
  10261. function Moment(config) {
  10262. extend(this, config);
  10263. }
  10264. // Duration Constructor
  10265. function Duration(duration) {
  10266. var data = this._data = {},
  10267. years = duration.years || duration.year || duration.y || 0,
  10268. months = duration.months || duration.month || duration.M || 0,
  10269. weeks = duration.weeks || duration.week || duration.w || 0,
  10270. days = duration.days || duration.day || duration.d || 0,
  10271. hours = duration.hours || duration.hour || duration.h || 0,
  10272. minutes = duration.minutes || duration.minute || duration.m || 0,
  10273. seconds = duration.seconds || duration.second || duration.s || 0,
  10274. milliseconds = duration.milliseconds || duration.millisecond || duration.ms || 0;
  10275. // representation for dateAddRemove
  10276. this._milliseconds = milliseconds +
  10277. seconds * 1e3 + // 1000
  10278. minutes * 6e4 + // 1000 * 60
  10279. hours * 36e5; // 1000 * 60 * 60
  10280. // Because of dateAddRemove treats 24 hours as different from a
  10281. // day when working around DST, we need to store them separately
  10282. this._days = days +
  10283. weeks * 7;
  10284. // It is impossible translate months into days without knowing
  10285. // which months you are are talking about, so we have to store
  10286. // it separately.
  10287. this._months = months +
  10288. years * 12;
  10289. // The following code bubbles up values, see the tests for
  10290. // examples of what that means.
  10291. data.milliseconds = milliseconds % 1000;
  10292. seconds += absRound(milliseconds / 1000);
  10293. data.seconds = seconds % 60;
  10294. minutes += absRound(seconds / 60);
  10295. data.minutes = minutes % 60;
  10296. hours += absRound(minutes / 60);
  10297. data.hours = hours % 24;
  10298. days += absRound(hours / 24);
  10299. days += weeks * 7;
  10300. data.days = days % 30;
  10301. months += absRound(days / 30);
  10302. data.months = months % 12;
  10303. years += absRound(months / 12);
  10304. data.years = years;
  10305. }
  10306. /************************************
  10307. Helpers
  10308. ************************************/
  10309. function extend(a, b) {
  10310. for (var i in b) {
  10311. if (b.hasOwnProperty(i)) {
  10312. a[i] = b[i];
  10313. }
  10314. }
  10315. return a;
  10316. }
  10317. function absRound(number) {
  10318. if (number < 0) {
  10319. return Math.ceil(number);
  10320. } else {
  10321. return Math.floor(number);
  10322. }
  10323. }
  10324. // left zero fill a number
  10325. // see http://jsperf.com/left-zero-filling for performance comparison
  10326. function leftZeroFill(number, targetLength) {
  10327. var output = number + '';
  10328. while (output.length < targetLength) {
  10329. output = '0' + output;
  10330. }
  10331. return output;
  10332. }
  10333. // helper function for _.addTime and _.subtractTime
  10334. function addOrSubtractDurationFromMoment(mom, duration, isAdding) {
  10335. var ms = duration._milliseconds,
  10336. d = duration._days,
  10337. M = duration._months,
  10338. currentDate;
  10339. if (ms) {
  10340. mom._d.setTime(+mom + ms * isAdding);
  10341. }
  10342. if (d) {
  10343. mom.date(mom.date() + d * isAdding);
  10344. }
  10345. if (M) {
  10346. currentDate = mom.date();
  10347. mom.date(1)
  10348. .month(mom.month() + M * isAdding)
  10349. .date(Math.min(currentDate, mom.daysInMonth()));
  10350. }
  10351. }
  10352. // check if is an array
  10353. function isArray(input) {
  10354. return Object.prototype.toString.call(input) === '[object Array]';
  10355. }
  10356. // compare two arrays, return the number of differences
  10357. function compareArrays(array1, array2) {
  10358. var len = Math.min(array1.length, array2.length),
  10359. lengthDiff = Math.abs(array1.length - array2.length),
  10360. diffs = 0,
  10361. i;
  10362. for (i = 0; i < len; i++) {
  10363. if (~~array1[i] !== ~~array2[i]) {
  10364. diffs++;
  10365. }
  10366. }
  10367. return diffs + lengthDiff;
  10368. }
  10369. /************************************
  10370. Languages
  10371. ************************************/
  10372. Language.prototype = {
  10373. set : function (config) {
  10374. var prop, i;
  10375. for (i in config) {
  10376. prop = config[i];
  10377. if (typeof prop === 'function') {
  10378. this[i] = prop;
  10379. } else {
  10380. this['_' + i] = prop;
  10381. }
  10382. }
  10383. },
  10384. _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
  10385. months : function (m) {
  10386. return this._months[m.month()];
  10387. },
  10388. _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
  10389. monthsShort : function (m) {
  10390. return this._monthsShort[m.month()];
  10391. },
  10392. monthsParse : function (monthName) {
  10393. var i, mom, regex, output;
  10394. if (!this._monthsParse) {
  10395. this._monthsParse = [];
  10396. }
  10397. for (i = 0; i < 12; i++) {
  10398. // make the regex if we don't have it already
  10399. if (!this._monthsParse[i]) {
  10400. mom = moment([2000, i]);
  10401. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  10402. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  10403. }
  10404. // test the regex
  10405. if (this._monthsParse[i].test(monthName)) {
  10406. return i;
  10407. }
  10408. }
  10409. },
  10410. _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
  10411. weekdays : function (m) {
  10412. return this._weekdays[m.day()];
  10413. },
  10414. _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
  10415. weekdaysShort : function (m) {
  10416. return this._weekdaysShort[m.day()];
  10417. },
  10418. _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
  10419. weekdaysMin : function (m) {
  10420. return this._weekdaysMin[m.day()];
  10421. },
  10422. _longDateFormat : {
  10423. LT : "h:mm A",
  10424. L : "MM/DD/YYYY",
  10425. LL : "MMMM D YYYY",
  10426. LLL : "MMMM D YYYY LT",
  10427. LLLL : "dddd, MMMM D YYYY LT"
  10428. },
  10429. longDateFormat : function (key) {
  10430. var output = this._longDateFormat[key];
  10431. if (!output && this._longDateFormat[key.toUpperCase()]) {
  10432. output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) {
  10433. return val.slice(1);
  10434. });
  10435. this._longDateFormat[key] = output;
  10436. }
  10437. return output;
  10438. },
  10439. meridiem : function (hours, minutes, isLower) {
  10440. if (hours > 11) {
  10441. return isLower ? 'pm' : 'PM';
  10442. } else {
  10443. return isLower ? 'am' : 'AM';
  10444. }
  10445. },
  10446. _calendar : {
  10447. sameDay : '[Today at] LT',
  10448. nextDay : '[Tomorrow at] LT',
  10449. nextWeek : 'dddd [at] LT',
  10450. lastDay : '[Yesterday at] LT',
  10451. lastWeek : '[last] dddd [at] LT',
  10452. sameElse : 'L'
  10453. },
  10454. calendar : function (key, mom) {
  10455. var output = this._calendar[key];
  10456. return typeof output === 'function' ? output.apply(mom) : output;
  10457. },
  10458. _relativeTime : {
  10459. future : "in %s",
  10460. past : "%s ago",
  10461. s : "a few seconds",
  10462. m : "a minute",
  10463. mm : "%d minutes",
  10464. h : "an hour",
  10465. hh : "%d hours",
  10466. d : "a day",
  10467. dd : "%d days",
  10468. M : "a month",
  10469. MM : "%d months",
  10470. y : "a year",
  10471. yy : "%d years"
  10472. },
  10473. relativeTime : function (number, withoutSuffix, string, isFuture) {
  10474. var output = this._relativeTime[string];
  10475. return (typeof output === 'function') ?
  10476. output(number, withoutSuffix, string, isFuture) :
  10477. output.replace(/%d/i, number);
  10478. },
  10479. pastFuture : function (diff, output) {
  10480. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  10481. return typeof format === 'function' ? format(output) : format.replace(/%s/i, output);
  10482. },
  10483. ordinal : function (number) {
  10484. return this._ordinal.replace("%d", number);
  10485. },
  10486. _ordinal : "%d",
  10487. preparse : function (string) {
  10488. return string;
  10489. },
  10490. postformat : function (string) {
  10491. return string;
  10492. },
  10493. week : function (mom) {
  10494. return weekOfYear(mom, this._week.dow, this._week.doy);
  10495. },
  10496. _week : {
  10497. dow : 0, // Sunday is the first day of the week.
  10498. doy : 6 // The week that contains Jan 1st is the first week of the year.
  10499. }
  10500. };
  10501. // Loads a language definition into the `languages` cache. The function
  10502. // takes a key and optionally values. If not in the browser and no values
  10503. // are provided, it will load the language file module. As a convenience,
  10504. // this function also returns the language values.
  10505. function loadLang(key, values) {
  10506. values.abbr = key;
  10507. if (!languages[key]) {
  10508. languages[key] = new Language();
  10509. }
  10510. languages[key].set(values);
  10511. return languages[key];
  10512. }
  10513. // Determines which language definition to use and returns it.
  10514. //
  10515. // With no parameters, it will return the global language. If you
  10516. // pass in a language key, such as 'en', it will return the
  10517. // definition for 'en', so long as 'en' has already been loaded using
  10518. // moment.lang.
  10519. function getLangDefinition(key) {
  10520. if (!key) {
  10521. return moment.fn._lang;
  10522. }
  10523. if (!languages[key] && hasModule) {
  10524. require('./lang/' + key);
  10525. }
  10526. return languages[key];
  10527. }
  10528. /************************************
  10529. Formatting
  10530. ************************************/
  10531. function removeFormattingTokens(input) {
  10532. if (input.match(/\[.*\]/)) {
  10533. return input.replace(/^\[|\]$/g, "");
  10534. }
  10535. return input.replace(/\\/g, "");
  10536. }
  10537. function makeFormatFunction(format) {
  10538. var array = format.match(formattingTokens), i, length;
  10539. for (i = 0, length = array.length; i < length; i++) {
  10540. if (formatTokenFunctions[array[i]]) {
  10541. array[i] = formatTokenFunctions[array[i]];
  10542. } else {
  10543. array[i] = removeFormattingTokens(array[i]);
  10544. }
  10545. }
  10546. return function (mom) {
  10547. var output = "";
  10548. for (i = 0; i < length; i++) {
  10549. output += typeof array[i].call === 'function' ? array[i].call(mom, format) : array[i];
  10550. }
  10551. return output;
  10552. };
  10553. }
  10554. // format date using native date object
  10555. function formatMoment(m, format) {
  10556. var i = 5;
  10557. function replaceLongDateFormatTokens(input) {
  10558. return m.lang().longDateFormat(input) || input;
  10559. }
  10560. while (i-- && localFormattingTokens.test(format)) {
  10561. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  10562. }
  10563. if (!formatFunctions[format]) {
  10564. formatFunctions[format] = makeFormatFunction(format);
  10565. }
  10566. return formatFunctions[format](m);
  10567. }
  10568. /************************************
  10569. Parsing
  10570. ************************************/
  10571. // get the regex to find the next token
  10572. function getParseRegexForToken(token) {
  10573. switch (token) {
  10574. case 'DDDD':
  10575. return parseTokenThreeDigits;
  10576. case 'YYYY':
  10577. return parseTokenFourDigits;
  10578. case 'YYYYY':
  10579. return parseTokenSixDigits;
  10580. case 'S':
  10581. case 'SS':
  10582. case 'SSS':
  10583. case 'DDD':
  10584. return parseTokenOneToThreeDigits;
  10585. case 'MMM':
  10586. case 'MMMM':
  10587. case 'dd':
  10588. case 'ddd':
  10589. case 'dddd':
  10590. case 'a':
  10591. case 'A':
  10592. return parseTokenWord;
  10593. case 'X':
  10594. return parseTokenTimestampMs;
  10595. case 'Z':
  10596. case 'ZZ':
  10597. return parseTokenTimezone;
  10598. case 'T':
  10599. return parseTokenT;
  10600. case 'MM':
  10601. case 'DD':
  10602. case 'YY':
  10603. case 'HH':
  10604. case 'hh':
  10605. case 'mm':
  10606. case 'ss':
  10607. case 'M':
  10608. case 'D':
  10609. case 'd':
  10610. case 'H':
  10611. case 'h':
  10612. case 'm':
  10613. case 's':
  10614. return parseTokenOneOrTwoDigits;
  10615. default :
  10616. return new RegExp(token.replace('\\', ''));
  10617. }
  10618. }
  10619. // function to convert string input to date
  10620. function addTimeToArrayFromToken(token, input, config) {
  10621. var a, b,
  10622. datePartArray = config._a;
  10623. switch (token) {
  10624. // MONTH
  10625. case 'M' : // fall through to MM
  10626. case 'MM' :
  10627. datePartArray[1] = (input == null) ? 0 : ~~input - 1;
  10628. break;
  10629. case 'MMM' : // fall through to MMMM
  10630. case 'MMMM' :
  10631. a = getLangDefinition(config._l).monthsParse(input);
  10632. // if we didn't find a month name, mark the date as invalid.
  10633. if (a != null) {
  10634. datePartArray[1] = a;
  10635. } else {
  10636. config._isValid = false;
  10637. }
  10638. break;
  10639. // DAY OF MONTH
  10640. case 'D' : // fall through to DDDD
  10641. case 'DD' : // fall through to DDDD
  10642. case 'DDD' : // fall through to DDDD
  10643. case 'DDDD' :
  10644. if (input != null) {
  10645. datePartArray[2] = ~~input;
  10646. }
  10647. break;
  10648. // YEAR
  10649. case 'YY' :
  10650. datePartArray[0] = ~~input + (~~input > 68 ? 1900 : 2000);
  10651. break;
  10652. case 'YYYY' :
  10653. case 'YYYYY' :
  10654. datePartArray[0] = ~~input;
  10655. break;
  10656. // AM / PM
  10657. case 'a' : // fall through to A
  10658. case 'A' :
  10659. config._isPm = ((input + '').toLowerCase() === 'pm');
  10660. break;
  10661. // 24 HOUR
  10662. case 'H' : // fall through to hh
  10663. case 'HH' : // fall through to hh
  10664. case 'h' : // fall through to hh
  10665. case 'hh' :
  10666. datePartArray[3] = ~~input;
  10667. break;
  10668. // MINUTE
  10669. case 'm' : // fall through to mm
  10670. case 'mm' :
  10671. datePartArray[4] = ~~input;
  10672. break;
  10673. // SECOND
  10674. case 's' : // fall through to ss
  10675. case 'ss' :
  10676. datePartArray[5] = ~~input;
  10677. break;
  10678. // MILLISECOND
  10679. case 'S' :
  10680. case 'SS' :
  10681. case 'SSS' :
  10682. datePartArray[6] = ~~ (('0.' + input) * 1000);
  10683. break;
  10684. // UNIX TIMESTAMP WITH MS
  10685. case 'X':
  10686. config._d = new Date(parseFloat(input) * 1000);
  10687. break;
  10688. // TIMEZONE
  10689. case 'Z' : // fall through to ZZ
  10690. case 'ZZ' :
  10691. config._useUTC = true;
  10692. a = (input + '').match(parseTimezoneChunker);
  10693. if (a && a[1]) {
  10694. config._tzh = ~~a[1];
  10695. }
  10696. if (a && a[2]) {
  10697. config._tzm = ~~a[2];
  10698. }
  10699. // reverse offsets
  10700. if (a && a[0] === '+') {
  10701. config._tzh = -config._tzh;
  10702. config._tzm = -config._tzm;
  10703. }
  10704. break;
  10705. }
  10706. // if the input is null, the date is not valid
  10707. if (input == null) {
  10708. config._isValid = false;
  10709. }
  10710. }
  10711. // convert an array to a date.
  10712. // the array should mirror the parameters below
  10713. // note: all values past the year are optional and will default to the lowest possible value.
  10714. // [year, month, day , hour, minute, second, millisecond]
  10715. function dateFromArray(config) {
  10716. var i, date, input = [];
  10717. if (config._d) {
  10718. return;
  10719. }
  10720. for (i = 0; i < 7; i++) {
  10721. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  10722. }
  10723. // add the offsets to the time to be parsed so that we can have a clean array for checking isValid
  10724. input[3] += config._tzh || 0;
  10725. input[4] += config._tzm || 0;
  10726. date = new Date(0);
  10727. if (config._useUTC) {
  10728. date.setUTCFullYear(input[0], input[1], input[2]);
  10729. date.setUTCHours(input[3], input[4], input[5], input[6]);
  10730. } else {
  10731. date.setFullYear(input[0], input[1], input[2]);
  10732. date.setHours(input[3], input[4], input[5], input[6]);
  10733. }
  10734. config._d = date;
  10735. }
  10736. // date from string and format string
  10737. function makeDateFromStringAndFormat(config) {
  10738. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  10739. var tokens = config._f.match(formattingTokens),
  10740. string = config._i,
  10741. i, parsedInput;
  10742. config._a = [];
  10743. for (i = 0; i < tokens.length; i++) {
  10744. parsedInput = (getParseRegexForToken(tokens[i]).exec(string) || [])[0];
  10745. if (parsedInput) {
  10746. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  10747. }
  10748. // don't parse if its not a known token
  10749. if (formatTokenFunctions[tokens[i]]) {
  10750. addTimeToArrayFromToken(tokens[i], parsedInput, config);
  10751. }
  10752. }
  10753. // handle am pm
  10754. if (config._isPm && config._a[3] < 12) {
  10755. config._a[3] += 12;
  10756. }
  10757. // if is 12 am, change hours to 0
  10758. if (config._isPm === false && config._a[3] === 12) {
  10759. config._a[3] = 0;
  10760. }
  10761. // return
  10762. dateFromArray(config);
  10763. }
  10764. // date from string and array of format strings
  10765. function makeDateFromStringAndArray(config) {
  10766. var tempConfig,
  10767. tempMoment,
  10768. bestMoment,
  10769. scoreToBeat = 99,
  10770. i,
  10771. currentDate,
  10772. currentScore;
  10773. while (config._f.length) {
  10774. tempConfig = extend({}, config);
  10775. tempConfig._f = config._f.pop();
  10776. makeDateFromStringAndFormat(tempConfig);
  10777. tempMoment = new Moment(tempConfig);
  10778. if (tempMoment.isValid()) {
  10779. bestMoment = tempMoment;
  10780. break;
  10781. }
  10782. currentScore = compareArrays(tempConfig._a, tempMoment.toArray());
  10783. if (currentScore < scoreToBeat) {
  10784. scoreToBeat = currentScore;
  10785. bestMoment = tempMoment;
  10786. }
  10787. }
  10788. extend(config, bestMoment);
  10789. }
  10790. // date from iso format
  10791. function makeDateFromString(config) {
  10792. var i,
  10793. string = config._i;
  10794. if (isoRegex.exec(string)) {
  10795. config._f = 'YYYY-MM-DDT';
  10796. for (i = 0; i < 4; i++) {
  10797. if (isoTimes[i][1].exec(string)) {
  10798. config._f += isoTimes[i][0];
  10799. break;
  10800. }
  10801. }
  10802. if (parseTokenTimezone.exec(string)) {
  10803. config._f += " Z";
  10804. }
  10805. makeDateFromStringAndFormat(config);
  10806. } else {
  10807. config._d = new Date(string);
  10808. }
  10809. }
  10810. function makeDateFromInput(config) {
  10811. var input = config._i,
  10812. matched = aspNetJsonRegex.exec(input);
  10813. if (input === undefined) {
  10814. config._d = new Date();
  10815. } else if (matched) {
  10816. config._d = new Date(+matched[1]);
  10817. } else if (typeof input === 'string') {
  10818. makeDateFromString(config);
  10819. } else if (isArray(input)) {
  10820. config._a = input.slice(0);
  10821. dateFromArray(config);
  10822. } else {
  10823. config._d = input instanceof Date ? new Date(+input) : new Date(input);
  10824. }
  10825. }
  10826. /************************************
  10827. Relative Time
  10828. ************************************/
  10829. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  10830. function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) {
  10831. return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  10832. }
  10833. function relativeTime(milliseconds, withoutSuffix, lang) {
  10834. var seconds = round(Math.abs(milliseconds) / 1000),
  10835. minutes = round(seconds / 60),
  10836. hours = round(minutes / 60),
  10837. days = round(hours / 24),
  10838. years = round(days / 365),
  10839. args = seconds < 45 && ['s', seconds] ||
  10840. minutes === 1 && ['m'] ||
  10841. minutes < 45 && ['mm', minutes] ||
  10842. hours === 1 && ['h'] ||
  10843. hours < 22 && ['hh', hours] ||
  10844. days === 1 && ['d'] ||
  10845. days <= 25 && ['dd', days] ||
  10846. days <= 45 && ['M'] ||
  10847. days < 345 && ['MM', round(days / 30)] ||
  10848. years === 1 && ['y'] || ['yy', years];
  10849. args[2] = withoutSuffix;
  10850. args[3] = milliseconds > 0;
  10851. args[4] = lang;
  10852. return substituteTimeAgo.apply({}, args);
  10853. }
  10854. /************************************
  10855. Week of Year
  10856. ************************************/
  10857. // firstDayOfWeek 0 = sun, 6 = sat
  10858. // the day of the week that starts the week
  10859. // (usually sunday or monday)
  10860. // firstDayOfWeekOfYear 0 = sun, 6 = sat
  10861. // the first week is the week that contains the first
  10862. // of this day of the week
  10863. // (eg. ISO weeks use thursday (4))
  10864. function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) {
  10865. var end = firstDayOfWeekOfYear - firstDayOfWeek,
  10866. daysToDayOfWeek = firstDayOfWeekOfYear - mom.day();
  10867. if (daysToDayOfWeek > end) {
  10868. daysToDayOfWeek -= 7;
  10869. }
  10870. if (daysToDayOfWeek < end - 7) {
  10871. daysToDayOfWeek += 7;
  10872. }
  10873. return Math.ceil(moment(mom).add('d', daysToDayOfWeek).dayOfYear() / 7);
  10874. }
  10875. /************************************
  10876. Top Level Functions
  10877. ************************************/
  10878. function makeMoment(config) {
  10879. var input = config._i,
  10880. format = config._f;
  10881. if (input === null || input === '') {
  10882. return null;
  10883. }
  10884. if (typeof input === 'string') {
  10885. config._i = input = getLangDefinition().preparse(input);
  10886. }
  10887. if (moment.isMoment(input)) {
  10888. config = extend({}, input);
  10889. config._d = new Date(+input._d);
  10890. } else if (format) {
  10891. if (isArray(format)) {
  10892. makeDateFromStringAndArray(config);
  10893. } else {
  10894. makeDateFromStringAndFormat(config);
  10895. }
  10896. } else {
  10897. makeDateFromInput(config);
  10898. }
  10899. return new Moment(config);
  10900. }
  10901. moment = function (input, format, lang) {
  10902. return makeMoment({
  10903. _i : input,
  10904. _f : format,
  10905. _l : lang,
  10906. _isUTC : false
  10907. });
  10908. };
  10909. // creating with utc
  10910. moment.utc = function (input, format, lang) {
  10911. return makeMoment({
  10912. _useUTC : true,
  10913. _isUTC : true,
  10914. _l : lang,
  10915. _i : input,
  10916. _f : format
  10917. });
  10918. };
  10919. // creating with unix timestamp (in seconds)
  10920. moment.unix = function (input) {
  10921. return moment(input * 1000);
  10922. };
  10923. // duration
  10924. moment.duration = function (input, key) {
  10925. var isDuration = moment.isDuration(input),
  10926. isNumber = (typeof input === 'number'),
  10927. duration = (isDuration ? input._data : (isNumber ? {} : input)),
  10928. ret;
  10929. if (isNumber) {
  10930. if (key) {
  10931. duration[key] = input;
  10932. } else {
  10933. duration.milliseconds = input;
  10934. }
  10935. }
  10936. ret = new Duration(duration);
  10937. if (isDuration && input.hasOwnProperty('_lang')) {
  10938. ret._lang = input._lang;
  10939. }
  10940. return ret;
  10941. };
  10942. // version number
  10943. moment.version = VERSION;
  10944. // default format
  10945. moment.defaultFormat = isoFormat;
  10946. // This function will load languages and then set the global language. If
  10947. // no arguments are passed in, it will simply return the current global
  10948. // language key.
  10949. moment.lang = function (key, values) {
  10950. var i;
  10951. if (!key) {
  10952. return moment.fn._lang._abbr;
  10953. }
  10954. if (values) {
  10955. loadLang(key, values);
  10956. } else if (!languages[key]) {
  10957. getLangDefinition(key);
  10958. }
  10959. moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key);
  10960. };
  10961. // returns language data
  10962. moment.langData = function (key) {
  10963. if (key && key._lang && key._lang._abbr) {
  10964. key = key._lang._abbr;
  10965. }
  10966. return getLangDefinition(key);
  10967. };
  10968. // compare moment object
  10969. moment.isMoment = function (obj) {
  10970. return obj instanceof Moment;
  10971. };
  10972. // for typechecking Duration objects
  10973. moment.isDuration = function (obj) {
  10974. return obj instanceof Duration;
  10975. };
  10976. /************************************
  10977. Moment Prototype
  10978. ************************************/
  10979. moment.fn = Moment.prototype = {
  10980. clone : function () {
  10981. return moment(this);
  10982. },
  10983. valueOf : function () {
  10984. return +this._d;
  10985. },
  10986. unix : function () {
  10987. return Math.floor(+this._d / 1000);
  10988. },
  10989. toString : function () {
  10990. return this.format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
  10991. },
  10992. toDate : function () {
  10993. return this._d;
  10994. },
  10995. toJSON : function () {
  10996. return moment.utc(this).format('YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  10997. },
  10998. toArray : function () {
  10999. var m = this;
  11000. return [
  11001. m.year(),
  11002. m.month(),
  11003. m.date(),
  11004. m.hours(),
  11005. m.minutes(),
  11006. m.seconds(),
  11007. m.milliseconds()
  11008. ];
  11009. },
  11010. isValid : function () {
  11011. if (this._isValid == null) {
  11012. if (this._a) {
  11013. this._isValid = !compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray());
  11014. } else {
  11015. this._isValid = !isNaN(this._d.getTime());
  11016. }
  11017. }
  11018. return !!this._isValid;
  11019. },
  11020. utc : function () {
  11021. this._isUTC = true;
  11022. return this;
  11023. },
  11024. local : function () {
  11025. this._isUTC = false;
  11026. return this;
  11027. },
  11028. format : function (inputString) {
  11029. var output = formatMoment(this, inputString || moment.defaultFormat);
  11030. return this.lang().postformat(output);
  11031. },
  11032. add : function (input, val) {
  11033. var dur;
  11034. // switch args to support add('s', 1) and add(1, 's')
  11035. if (typeof input === 'string') {
  11036. dur = moment.duration(+val, input);
  11037. } else {
  11038. dur = moment.duration(input, val);
  11039. }
  11040. addOrSubtractDurationFromMoment(this, dur, 1);
  11041. return this;
  11042. },
  11043. subtract : function (input, val) {
  11044. var dur;
  11045. // switch args to support subtract('s', 1) and subtract(1, 's')
  11046. if (typeof input === 'string') {
  11047. dur = moment.duration(+val, input);
  11048. } else {
  11049. dur = moment.duration(input, val);
  11050. }
  11051. addOrSubtractDurationFromMoment(this, dur, -1);
  11052. return this;
  11053. },
  11054. diff : function (input, units, asFloat) {
  11055. var that = this._isUTC ? moment(input).utc() : moment(input).local(),
  11056. zoneDiff = (this.zone() - that.zone()) * 6e4,
  11057. diff, output;
  11058. if (units) {
  11059. // standardize on singular form
  11060. units = units.replace(/s$/, '');
  11061. }
  11062. if (units === 'year' || units === 'month') {
  11063. diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2
  11064. output = ((this.year() - that.year()) * 12) + (this.month() - that.month());
  11065. output += ((this - moment(this).startOf('month')) - (that - moment(that).startOf('month'))) / diff;
  11066. if (units === 'year') {
  11067. output = output / 12;
  11068. }
  11069. } else {
  11070. diff = (this - that) - zoneDiff;
  11071. output = units === 'second' ? diff / 1e3 : // 1000
  11072. units === 'minute' ? diff / 6e4 : // 1000 * 60
  11073. units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60
  11074. units === 'day' ? diff / 864e5 : // 1000 * 60 * 60 * 24
  11075. units === 'week' ? diff / 6048e5 : // 1000 * 60 * 60 * 24 * 7
  11076. diff;
  11077. }
  11078. return asFloat ? output : absRound(output);
  11079. },
  11080. from : function (time, withoutSuffix) {
  11081. return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix);
  11082. },
  11083. fromNow : function (withoutSuffix) {
  11084. return this.from(moment(), withoutSuffix);
  11085. },
  11086. calendar : function () {
  11087. var diff = this.diff(moment().startOf('day'), 'days', true),
  11088. format = diff < -6 ? 'sameElse' :
  11089. diff < -1 ? 'lastWeek' :
  11090. diff < 0 ? 'lastDay' :
  11091. diff < 1 ? 'sameDay' :
  11092. diff < 2 ? 'nextDay' :
  11093. diff < 7 ? 'nextWeek' : 'sameElse';
  11094. return this.format(this.lang().calendar(format, this));
  11095. },
  11096. isLeapYear : function () {
  11097. var year = this.year();
  11098. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  11099. },
  11100. isDST : function () {
  11101. return (this.zone() < moment([this.year()]).zone() ||
  11102. this.zone() < moment([this.year(), 5]).zone());
  11103. },
  11104. day : function (input) {
  11105. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  11106. return input == null ? day :
  11107. this.add({ d : input - day });
  11108. },
  11109. startOf: function (units) {
  11110. units = units.replace(/s$/, '');
  11111. // the following switch intentionally omits break keywords
  11112. // to utilize falling through the cases.
  11113. switch (units) {
  11114. case 'year':
  11115. this.month(0);
  11116. /* falls through */
  11117. case 'month':
  11118. this.date(1);
  11119. /* falls through */
  11120. case 'week':
  11121. case 'day':
  11122. this.hours(0);
  11123. /* falls through */
  11124. case 'hour':
  11125. this.minutes(0);
  11126. /* falls through */
  11127. case 'minute':
  11128. this.seconds(0);
  11129. /* falls through */
  11130. case 'second':
  11131. this.milliseconds(0);
  11132. /* falls through */
  11133. }
  11134. // weeks are a special case
  11135. if (units === 'week') {
  11136. this.day(0);
  11137. }
  11138. return this;
  11139. },
  11140. endOf: function (units) {
  11141. return this.startOf(units).add(units.replace(/s?$/, 's'), 1).subtract('ms', 1);
  11142. },
  11143. isAfter: function (input, units) {
  11144. units = typeof units !== 'undefined' ? units : 'millisecond';
  11145. return +this.clone().startOf(units) > +moment(input).startOf(units);
  11146. },
  11147. isBefore: function (input, units) {
  11148. units = typeof units !== 'undefined' ? units : 'millisecond';
  11149. return +this.clone().startOf(units) < +moment(input).startOf(units);
  11150. },
  11151. isSame: function (input, units) {
  11152. units = typeof units !== 'undefined' ? units : 'millisecond';
  11153. return +this.clone().startOf(units) === +moment(input).startOf(units);
  11154. },
  11155. zone : function () {
  11156. return this._isUTC ? 0 : this._d.getTimezoneOffset();
  11157. },
  11158. daysInMonth : function () {
  11159. return moment.utc([this.year(), this.month() + 1, 0]).date();
  11160. },
  11161. dayOfYear : function (input) {
  11162. var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1;
  11163. return input == null ? dayOfYear : this.add("d", (input - dayOfYear));
  11164. },
  11165. isoWeek : function (input) {
  11166. var week = weekOfYear(this, 1, 4);
  11167. return input == null ? week : this.add("d", (input - week) * 7);
  11168. },
  11169. week : function (input) {
  11170. var week = this.lang().week(this);
  11171. return input == null ? week : this.add("d", (input - week) * 7);
  11172. },
  11173. // If passed a language key, it will set the language for this
  11174. // instance. Otherwise, it will return the language configuration
  11175. // variables for this instance.
  11176. lang : function (key) {
  11177. if (key === undefined) {
  11178. return this._lang;
  11179. } else {
  11180. this._lang = getLangDefinition(key);
  11181. return this;
  11182. }
  11183. }
  11184. };
  11185. // helper for adding shortcuts
  11186. function makeGetterAndSetter(name, key) {
  11187. moment.fn[name] = moment.fn[name + 's'] = function (input) {
  11188. var utc = this._isUTC ? 'UTC' : '';
  11189. if (input != null) {
  11190. this._d['set' + utc + key](input);
  11191. return this;
  11192. } else {
  11193. return this._d['get' + utc + key]();
  11194. }
  11195. };
  11196. }
  11197. // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds)
  11198. for (i = 0; i < proxyGettersAndSetters.length; i ++) {
  11199. makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]);
  11200. }
  11201. // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear')
  11202. makeGetterAndSetter('year', 'FullYear');
  11203. // add plural methods
  11204. moment.fn.days = moment.fn.day;
  11205. moment.fn.weeks = moment.fn.week;
  11206. moment.fn.isoWeeks = moment.fn.isoWeek;
  11207. /************************************
  11208. Duration Prototype
  11209. ************************************/
  11210. moment.duration.fn = Duration.prototype = {
  11211. weeks : function () {
  11212. return absRound(this.days() / 7);
  11213. },
  11214. valueOf : function () {
  11215. return this._milliseconds +
  11216. this._days * 864e5 +
  11217. this._months * 2592e6;
  11218. },
  11219. humanize : function (withSuffix) {
  11220. var difference = +this,
  11221. output = relativeTime(difference, !withSuffix, this.lang());
  11222. if (withSuffix) {
  11223. output = this.lang().pastFuture(difference, output);
  11224. }
  11225. return this.lang().postformat(output);
  11226. },
  11227. lang : moment.fn.lang
  11228. };
  11229. function makeDurationGetter(name) {
  11230. moment.duration.fn[name] = function () {
  11231. return this._data[name];
  11232. };
  11233. }
  11234. function makeDurationAsGetter(name, factor) {
  11235. moment.duration.fn['as' + name] = function () {
  11236. return +this / factor;
  11237. };
  11238. }
  11239. for (i in unitMillisecondFactors) {
  11240. if (unitMillisecondFactors.hasOwnProperty(i)) {
  11241. makeDurationAsGetter(i, unitMillisecondFactors[i]);
  11242. makeDurationGetter(i.toLowerCase());
  11243. }
  11244. }
  11245. makeDurationAsGetter('Weeks', 6048e5);
  11246. /************************************
  11247. Default Lang
  11248. ************************************/
  11249. // Set default language, other languages will inherit from English.
  11250. moment.lang('en', {
  11251. ordinal : function (number) {
  11252. var b = number % 10,
  11253. output = (~~ (number % 100 / 10) === 1) ? 'th' :
  11254. (b === 1) ? 'st' :
  11255. (b === 2) ? 'nd' :
  11256. (b === 3) ? 'rd' : 'th';
  11257. return number + output;
  11258. }
  11259. });
  11260. /************************************
  11261. Exposing Moment
  11262. ************************************/
  11263. // CommonJS module is defined
  11264. if (hasModule) {
  11265. module.exports = moment;
  11266. }
  11267. /*global ender:false */
  11268. if (typeof ender === 'undefined') {
  11269. // here, `this` means `window` in the browser, or `global` on the server
  11270. // add `moment` as a global object via a string identifier,
  11271. // for Closure Compiler "advanced" mode
  11272. this['moment'] = moment;
  11273. }
  11274. /*global define:false */
  11275. if (typeof define === "function" && define.amd) {
  11276. define("moment", [], function () {
  11277. return moment;
  11278. });
  11279. }
  11280. }).call(this);
  11281. })()
  11282. },{}]},{},[1])(1)
  11283. });
  11284. ;